package com.yeejoin.amos.fas.business.service.impl;

import com.google.common.collect.Lists;
import com.yeejoin.amos.fas.business.constants.FasConstant;
import com.yeejoin.amos.fas.business.dao.mapper.DictMapper;
import com.yeejoin.amos.fas.business.dao.mapper.PlanVisual3dMapper;
import com.yeejoin.amos.fas.business.dao.repository.ITextPlanDao;
import com.yeejoin.amos.fas.business.feign.IMaasVisualServer;
import com.yeejoin.amos.fas.business.service.intfc.IDictService;
import com.yeejoin.amos.fas.business.service.intfc.IPlanVisual3dService;
import com.yeejoin.amos.fas.business.vo.TreeSubjectVo;
import com.yeejoin.amos.fas.core.util.CommonResponse;
import com.yeejoin.amos.fas.core.util.CommonResponseUtil;
import com.yeejoin.amos.fas.dao.entity.Dict;
import com.yeejoin.amos.fas.dao.entity.TextPlan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service("planVisual3dService")
public class PlanVisual3dServiceImpl implements IPlanVisual3dService {

    @Autowired
    IMaasVisualServer maasVisualServer;

    @Autowired
    ITextPlanDao iTextPlanDao;

    @Autowired
    PlanVisual3dMapper planVisual3dMapper;

    @Autowired
    IDictService dictService;

    @Autowired
    private DictMapper dictMapper;

    @Override
    public List<TreeSubjectVo> getPlanTree() {

        CommonResponse response = maasVisualServer.getTree();
        List<TreeSubjectVo> treeSubjectVos = Lists.newArrayList();
        if (null != response.getDataList()) {
            List<Object> res = (List<Object>) response.getDataList();
            if (!CollectionUtils.isEmpty(res)) {
                treeSubjectVos = listToTree(res);
            }
        }
        return treeSubjectVos;
    }

    @Override
    public void uploadTextPlan(String appId, Map<String, String> pathNameMap) {
        if (null != pathNameMap && !pathNameMap.isEmpty()) {
            for (Map.Entry<String, String> entry : pathNameMap.entrySet()) {
                TextPlan textPlan = new TextPlan();
                textPlan.setAppId(appId);
                textPlan.setTextName(entry.getValue());
                textPlan.setFilePath(entry.getKey());
                iTextPlanDao.save(textPlan);
            }
        }
    }

    @Override
    public TextPlan getTextPlanInfoById(Long id) {
    	Optional<TextPlan> textPlan =iTextPlanDao.findById(id);
    	if(textPlan.isPresent()){
    		return textPlan.get();
    	}
    	return null;
    }

    private List<TreeSubjectVo> listToTree(List<Object> list) {
        List<TreeSubjectVo> treeSubjectVos = Lists.newArrayList();
        for (Object obj : list) {
            TreeSubjectVo treeItem = new TreeSubjectVo();
            LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) obj;
            treeItem.setId((String) map.get("id"));
            treeItem.setTreeName((String) map.get("treeName"));
            treeItem.setParentId((String) map.get("parentId"));
            treeItem.setMaxSubjectNumber((Integer) map.get("maxSubjectNumber"));
            treeItem.setType("treeNode");

            List<Object> children = (List<Object>) map.get("children");
            if (null != children) {
                List<TreeSubjectVo> subjectVos = listToTree(children);
                treeItem.setChildren(subjectVos);
            }

            CommonResponse response = maasVisualServer.getSubjectById(String.valueOf(map.get("id")));
            if (null != response) {
                List<TreeSubjectVo> childrenVos = Lists.newArrayList();
                List<Object> res = (List<Object>) response.getDataList();
                res.forEach(r -> {
                	LinkedHashMap<String, Object> map1 = (LinkedHashMap<String, Object>) r;
                	Integer state = (Integer) map1.get("publishState");
                	if(state == 0) {//过滤 未发布状态
                		return;
                	}
                    TreeSubjectVo subjectVo = new TreeSubjectVo();
                    subjectVo.setType("listNode");
                    subjectVo.setParentId((String) map.get("id"));
                    subjectVo.setId((String) map1.get("id"));
                    subjectVo.setDelete(map1.get("isDelete") == null || (Integer) map1.get("isDelete") == 0 ? false : true);
                    subjectVo.setCreateTime((String) map1.get("createTime"));
                    subjectVo.setCreator(map1.get("creator") == null ? 0 : (Integer) map1.get("creator"));
                    subjectVo.setSubjectName((String) map1.get("subjectName"));
                    subjectVo.setTreeName((String) map1.get("subjectName"));
                    subjectVo.setSubjectDetail((String) map1.get("subjectDetail"));
                    subjectVo.setSubjectType((String) map1.get("subjectType"));
                    subjectVo.setSubjectTypeName((String) map1.get("subjectTypeName"));
                    subjectVo.setPublishState(state);
                    subjectVo.setBelongTreeId((String) map1.get("belongTreeId"));
                    subjectVo.setScenes(map1.get("scenes") == null ? "" : (String) map1.get("scenes"));

                    //关联文字预案
                    List<TextPlan> textPlans = iTextPlanDao.findByAppId(String.valueOf(subjectVo.getId()));
                    textPlans.forEach(t -> {
                        TreeSubjectVo textTreeSubjectVo = new TreeSubjectVo();
                        textTreeSubjectVo.setParentId(String.valueOf(t.getAppId()));
                        textTreeSubjectVo.setTreeName(t.getTextName());
                        textTreeSubjectVo.setId(String.valueOf(t.getId()));
                        textTreeSubjectVo.setType("textNode");
                        subjectVo.getChildren().add(textTreeSubjectVo);
                    });

                    childrenVos.add(subjectVo);
                });
                treeItem.getChildren().addAll(childrenVos);
            }
            treeSubjectVos.add(treeItem);
        }
        return treeSubjectVos;
    }

    @Override
    public CommonResponse getResourceListByType(String type) {
        //1.校验是否是约定的字典，不存在则提示失败
        Dict dict = new Dict();
        dict.setDictCode(FasConstant.PLAN_SOURCE_TYPE);
        dict.setDictValue(type);
        List<Dict> dictList = dictService.getDictList(dict);
        if (CollectionUtils.isEmpty(dictList)) {
            return CommonResponseUtil.failure(type + "字典类型不存在");
        }
        //2.返回存在的数据
//        return CommonResponseUtil.success(planVisual3dMapper.getResourceListByType(type));
        return CommonResponseUtil.success();
    }

    @Override
    public List<Map<String, Object>> getResourceById(String type, Long id) {
        //1.查询出要返回数据
//        Map<String, Object> map = planVisual3dMapper.queryOneByTypeAndId(type, id);
        Map<String, Object> map = new HashMap<String, Object>();
        //1.1无数据则返回
        if (CollectionUtils.isEmpty(map)) {
            return new ArrayList<>();
        }
        //2.加工数据
        //2.0查询出中英文对照字典映射
        Dict dict = new Dict();
        dict.setDictCode(type);
        List<Dict> dictList = dictService.getDictList(dict);
        Map<String, String> dicts = dictList.stream().collect(
                Collectors.toMap(Dict::getDictValue, Dict::getDictName, (key1, key2) -> key2));

        //2.1换key为中文
        Map<String, Object> tempMap = new HashMap<String, Object>();
        map.forEach((k, v) -> {
            if (dicts.containsKey(k)) {
                tempMap.put(dicts.get(k), v);
            }
        });

        //2.2map转list
        List<Map<String, Object>> list = new ArrayList<>();
        list = tempMap.entrySet().stream().map(e -> {
            Map<String, Object> newMap = new HashMap<String, Object>();
            newMap.put("label", e.getKey());
            newMap.put("value", e.getValue());
            return newMap;
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<Map<String, Object>> getResourceTypeList() {
        Dict dict = new Dict();
        dict.setDictCode(FasConstant.PLAN_SOURCE_TYPE);
        List<Dict> dictList = dictMapper.getDictList(dict);
        List<Map<String, Object>> list = new ArrayList<>();
        list = dictList.stream().map(e->{
            Map<String, Object> newMap = new HashMap<String, Object>();
            newMap.put("key",e.getDictValue());
            newMap.put("value",e.getDictValue());//前端级联Cascader使用
            newMap.put("isLeaf",false);////前端级联Cascader使用
            newMap.put("dataType","type");
            newMap.put("label",e.getDictName());
            return newMap;
        }).collect(Collectors.toList());
        return list;
    }

	@Override
	public List<TreeSubjectVo> getTextPlanBySubjectId(String appId) {
		//关联文字预案
		List<TreeSubjectVo> subjectVos = new ArrayList<>();
        List<TextPlan> textPlans = iTextPlanDao.findByAppId(appId);
        textPlans.forEach(t -> {
            TreeSubjectVo textTreeSubjectVo = new TreeSubjectVo();
            textTreeSubjectVo.setParentId(String.valueOf(t.getAppId()));
            textTreeSubjectVo.setTreeName(t.getTextName());
            textTreeSubjectVo.setId(String.valueOf(t.getId()));
            textTreeSubjectVo.setType("textNode");
            subjectVos.add(textTreeSubjectVo);
        });
		return subjectVos;
	}

	@Override
	public void deleteTextPlanFile(Long id) {
		iTextPlanDao.deleteById(id);
	}


}
