package com.zcloud.service.system.impl;

import java.util.*;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.entity.system.Dictionaries;
import com.zcloud.mapper.dsno2.system.DictionariesMapper;
import com.zcloud.service.system.DictionariesService;
import com.zcloud.util.Jurisdiction;

/**
 * 说明：按钮权限服务接口实现类
 * 作者：luoxiaobao
 * 官网：www.qdkjchina.com
 */
@Service
@Transactional //开启事物
public class DictionariesServiceImpl implements DictionariesService {

    @Autowired
    private DictionariesMapper dictionariesMapper;

    /**
     * 获取所有数据并填充每条数据的子级列表(递归处理)
     *
     * @param MENU_ID
     * @return
     * @throws Exception
     */
    public List<Dictionaries> listAllDict(String parentId) throws Exception {
        List<Dictionaries> dictList = this.listSubDictByParentId(parentId);
        for (Dictionaries dict : dictList) {
            dict.setTreeurl("dictionaries_list.html?DICTIONARIES_ID=" + dict.getDICTIONARIES_ID());
            dict.setSubDict(this.listAllDict(dict.getDICTIONARIES_ID()));
            dict.setTarget("treeFrame");
        }
        return dictList;
    }

    /**
     * 通过ID获取其子级列表
     *
     * @param parentId
     * @return
     * @throws Exception
     */
    public List<Dictionaries> listSubDictByParentId(String parentId) throws Exception {

        return dictionariesMapper.listSubDictByParentId(parentId);
    }

    /**
     * 获取所有数据并填充每条数据的子级列表(递归处理)用于代码生成器引用数据字典
     *
     * @param MENU_ID
     * @return
     * @throws Exception
     */
    public List<Dictionaries> listAllDictToCreateCode(String parentId) throws Exception {
        List<Dictionaries> dictList = this.listSubDictByParentId(parentId);
        for (Dictionaries dict : dictList) {
            dict.setTreeurl("setDID('" + dict.getDICTIONARIES_ID() + "');");
            dict.setSubDict(this.listAllDictToCreateCode(dict.getDICTIONARIES_ID()));
            dict.setTarget("treeFrame");
        }
        return dictList;
    }

    /**
     * 获取所有数据并填充每条数据的子级列表(递归处理)下拉ztree用
     *
     * @param MENU_ID
     * @return
     * @throws Exception
     */
    public List<PageData> listAllDictToSelect(String parentId, List<PageData> zdicPdList) throws Exception {
        List<PageData>[] arrayDep = this.listAllbyPd(parentId, zdicPdList);
        List<PageData> dicPdList = arrayDep[1];
        for (PageData pd : dicPdList) {
            this.listAllDictToSelect(pd.getString("id"), arrayDep[0]);
        }
        return arrayDep[0];
    }

    /**
     * 下拉ztree用
     *
     * @param parentId
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public List<PageData>[] listAllbyPd(String parentId, List<PageData> zdicPdList) throws Exception {
        List<Dictionaries> dicList = this.listSubDictByParentId(parentId);
        List<PageData> dicPdList = new ArrayList<PageData>();
        for (Dictionaries dic : dicList) {
            PageData pd = new PageData();
            pd.put("id", dic.getDICTIONARIES_ID());
            pd.put("parentId", dic.getPARENT_ID());
            pd.put("name", dic.getNAME());
            pd.put("bianma", dic.getBIANMA());
            pd.put("icon", "../../../assets/images/user.gif");
            dicPdList.add(pd);
            zdicPdList.add(pd);
        }
        List<PageData>[] arrayDep = new List[2];
        arrayDep[0] = zdicPdList;
        arrayDep[1] = dicPdList;
        return arrayDep;
    }

    /**
     * 列表
     *
     * @param page
     * @throws Exception
     */
    public List<PageData> list(Page page) throws Exception {
        return dictionariesMapper.datalistPage(page);
    }

    /**
     * 通过id获取数据
     *
     * @param pd
     * @throws Exception
     */
    public PageData findById(PageData pd) throws Exception {
        return dictionariesMapper.findById(pd);
    }

    /**
     * 通过名称获取数据
     *
     * @param pd
     * @throws Exception
     */
    public PageData findByName(PageData pd) throws Exception {
        return dictionariesMapper.findByName(pd);
    }

    public PageData findByNames(String name, String PARENT_ID) throws Exception {
        PageData pageData = new PageData();
        pageData.put("NAME", name);
        pageData.put("PARENT_ID", PARENT_ID);
        return dictionariesMapper.getPdByParIdAndName(pageData);
    }

    /**
     * 通过编码获取数据
     *
     * @param pd
     * @throws Exception
     */
    public PageData findByBianma(PageData pd) throws Exception {
        return dictionariesMapper.findByBianma(pd);
    }

    /**
     * 新增
     *
     * @param pd
     * @throws Exception
     */
    public void save(PageData pd) throws Exception {
        dictionariesMapper.save(pd);
    }

    /**
     * 修改
     *
     * @param pd
     * @throws Exception
     */
    public void edit(PageData pd) throws Exception {
        dictionariesMapper.edit(pd);
    }

    /**
     * 排查表检查是否被占用
     *
     * @param pd
     * @throws Exception
     */
    public PageData findFromTbs(PageData pd) throws Exception {
        return dictionariesMapper.findFromTbs(pd);
    }

    /**
     * 删除
     *
     * @param pd
     * @throws Exception
     */
    public void delete(PageData pd) throws Exception {
        dictionariesMapper.delete(pd);
    }

    /**
     * 通过IDS获取列表
     *
     * @param dictionariesIds
     * @return
     * @throws Exception
     */
    public List<Dictionaries> listSubDictByIds(String[] dictionariesIds) throws Exception {
        return dictionariesMapper.listSubDictByIdS(dictionariesIds);
    }

    public List<PageData> listSubDictByParentIdAndSunCount(String parentId) throws Exception {
        return dictionariesMapper.listSubDictByParentIdAndSunCount(parentId);
    }

    /**
     * 从下而上查询树（无分支）
     *
     * @param dic
     * @return
     * @throws Exception
     */
    public List<PageData> getTreeFromBelow(List<PageData> nextList, PageData dic) throws Exception {
        List<PageData> dicList = dictionariesMapper.listBySameParent(dic.get("PARENT_ID").toString());
        if (nextList != null && dicList != null && nextList.size() > 0 && dicList.size() > 0) {
            for (PageData d : dicList) {
                if (dic.getString("DICTIONARIES_ID").equals(d.getString("id"))) {
                    d.put("children", nextList);
                }
            }
        }
        PageData parDic = new PageData();
        parDic.put("DICTIONARIES_ID", dic.get("PARENT_ID"));
        parDic.put("NOROOT", "1");
        parDic = dictionariesMapper.findById(parDic);
        if (parDic != null && parDic.get("DICTIONARIES_ID") != null) {
            dicList = getTreeFromBelow(dicList, parDic);
        }
        return dicList;
    }

    /**
     * 从下而上查询树（无分支，带禁用及级别）  代理人修改企业时使用
     *
     * @param dic
     * @return
     * @throws Exception
     */
    public List<PageData> getTreeFromBelow(List<PageData> nextList, PageData dic, int level, PageData agent, int num) throws Exception {
        System.out.println(dic.get("level"));
        List<PageData> dicList = dictionariesMapper.listBySameParent(dic.get("PARENT_ID").toString());
        if (dicList != null && dicList.size() > 0) {
            Map<String, Object> agentArea = new HashMap<String, Object>();
            if (!"1".equals(Jurisdiction.getUSER_ID())) {
                agentArea = (Map<String, Object>) agent.get("agentArea");
            }
            for (PageData d : dicList) {

                if (nextList != null && nextList.size() > 0 && dic.getString("DICTIONARIES_ID").equals(d.getString("id"))) {
                    d.put("children", nextList);
                }
                if (!"1".equals(Jurisdiction.getUSER_ID())) {
                    // 级别从 1-5 数越大。代表区域或代理的级别越低（1-省   2-市 ……）
                    if (level < Integer.valueOf(agent.get("agentLevel").toString())) {// 当区域级别高于代理级别时，一律禁用
                        d.put("disabled", true);
                    } else if (level == Integer.valueOf(agent.get("agentLevel").toString()) && !agentArea.containsKey(d.getString("numValue"))) { // 区域级别等于代理级别，若不在代理权限内。则禁用
                        d.put("disabled", true);
                    } else if (level > Integer.valueOf(agent.get("agentLevel").toString()) && d.getString("FULLID").indexOf(agent.getString("LEASTLEVLE")) == -1) {// 区域级别小于代理级别，若不在代理权限内（包含下级）。则禁用
                        d.put("disabled", true);
                    }
                    // leaf 为true时。下拉树中。不显示该数据的下级
                    if (agentArea.containsKey(d.getString("numValue")) || d.getString("FULLID").indexOf(agent.getString("LEASTLEVLE")) != -1) { // 判断当前地区。是否在代理权限内
                        // 在权限内，则有下级
                        //d.put("leaf", false); //此处if内不能有代码，且不能删除
                    } else if (dic.getString("BIANMA").equals(d.getString("numValue"))) {//判断当前地区。是否为公司目前所选地区
                        // 判断当前地区是否为公司所选公司的最后一级（即第一次递归）,若是。则当前地区没有下级。否，则有
                        if (num == 1) {
                            d.put("leaf", true);
                        } else {
                            d.put("leaf", false);
                        }
                    } else {// 不在代理权限内。且不是目前公司所选地区。都没有下级
                        d.put("leaf", true);
                    }
                }
                d.put("level", level);
            }
        }

        PageData parDic = new PageData();
        parDic.put("DICTIONARIES_ID", dic.get("PARENT_ID"));
        parDic.put("NOROOT", "1");
        parDic = dictionariesMapper.findById(parDic);
        if (parDic != null && parDic.get("DICTIONARIES_ID") != null) {
            dicList = getTreeFromBelow(dicList, parDic, level - 1, agent, num + 1);
        }
        return dicList;
    }

    @Override
    public List<PageData> findByCondition(PageData condition) {
        return dictionariesMapper.findByCondition(condition);
    }

    private List<PageData> fitAgentTree(List<PageData> varList, int level, PageData agent) {

//		for(PageData d :varList){
//			if(!"1".equals(Jurisdiction.getUSER_ID())){
//				if(level < agent.get("").){
//					pdf.put("DISABLED","true");
//					if(!agentArea.containsKey(pdf.getString("BIANMA"))){
//						pdf.put("zcount", 0);
//					} else {
//						pdf.put("zcount", d.get("zcount"));
//					}
//				} else if(level + 1 == agentLevel){
//
//					if(!agentArea.containsKey(pdf.getString("BIANMA"))){
//						pdf.put("DISABLED","true");
//						pdf.put("zcount", 0);
//					} else {
//						pdf.put("zcount", d.get("zcount"));
//					}
//				} else {
//					pdf.put("zcount", d.get("zcount"));
//				}
//			} else {
//				pdf.put("zcount", d.get("zcount"));
//			}
//
//			pdList.add(pdf);
//		}
        return null;
    }

    @Override
    public List<PageData> getDictTreeMoreLevel(String parentId) throws Exception {
        List<PageData> varList = dictionariesMapper.listSubDictByParentIdAndSunCount(parentId);
        List<PageData> pdList = new ArrayList<PageData>();
        for (PageData d : varList) {
            PageData pdf = new PageData();
            pdf.put("value", d.getString("DICTIONARIES_ID"));
            pdf.put("label", d.getString("NAME"));
            if (Integer.parseInt(d.getString("zcount")) > 0) {
                setDictTreeMoreLevelChild(pdf, d);
            }
            pdList.add(pdf);
        }
        return pdList;
    }

    @Override
    public List<PageData> listAllDictCetByParentId(PageData pageData) {
        List<PageData> dataList = dictionariesMapper.listAllDictCetByParentId(pageData);
        List<PageData> dictDataList = new ArrayList<>();
        dataList.forEach(item -> {
            if (item.getString("PARENT_ID").equals(pageData.getString("DICTIONARIES_ID"))) {
                // 初始化1级菜单
                item.put("value", item.getString("DICTIONARIES_ID"));
                item.put("label", item.getString("NAME"));
                dictDataList.add(item);
            }
        });
        for (PageData dict : dictDataList) {
            List<PageData> childList = TreeChildren(dict.getString("DICTIONARIES_ID"), dataList);
            dict.put("children", childList);
        }
        return dictDataList;
    }

    private List<PageData> TreeChildren(String parentId, List<PageData> routeList) {
        List<PageData> childList = new ArrayList<>();
        for (PageData route : routeList) {
            //遍历所有节点，与上级传过来的父节点id比较
            if (parentId.equals(route.getString("PARENT_ID"))) {
				route.put("value", route.getString("DICTIONARIES_ID"));
				route.put("label", route.getString("NAME"));
                childList.add(route);
            }
        }
        //递归
        for (PageData route : childList) {
            List<PageData> dataList = TreeChildren(route.getString("DICTIONARIES_ID"), routeList);
            if (!dataList.isEmpty()) {
                route.put("children", dataList);
            }
        }
        return childList;
    }

    private void setDictTreeMoreLevelChild(PageData parent, PageData dict) {
        List<PageData> varList = dictionariesMapper.listSubDictByParentIdAndSunCount(dict.getString("DICTIONARIES_ID"));
        List<PageData> childList = new ArrayList<PageData>();
        for (PageData d : varList) {
            PageData pdf = new PageData();
            pdf.put("value", d.getString("DICTIONARIES_ID"));
            pdf.put("label", d.getString("NAME"));
            if (Integer.parseInt(d.getString("zcount")) > 0) {
                setDictTreeMoreLevelChild(pdf, d);
            }
            childList.add(pdf);
        }
        parent.put("children", childList);
    }
}
