package cn.com.countrygarden.bi.main.service.dup.impl;


import cn.com.countrygarden.bi.main.dao.common.OrganMapper;
import cn.com.countrygarden.bi.main.dao.dup.ManagerCommMapper;
import cn.com.countrygarden.bi.main.dao.sys.PilotCommMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.ManagerMapForErpMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbHsprCommunityMapper;
import cn.com.countrygarden.bi.main.dto.manager.CommunityInfo;
import cn.com.countrygarden.bi.main.dto.manager.TreeNode;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.common.Organ;
import cn.com.countrygarden.bi.main.model.dup.DupComm;
import cn.com.countrygarden.bi.main.model.dup.DupOrgan;
import cn.com.countrygarden.bi.main.model.dup.ManagerComm;
import cn.com.countrygarden.bi.main.model.sys.PilotComm;
import cn.com.countrygarden.bi.main.model.twerp.ErpCommunity;
import cn.com.countrygarden.bi.main.service.UserRoleService;
import cn.com.countrygarden.bi.main.service.dup.DupCommService;
import cn.com.countrygarden.bi.main.util.RedisCacheUtils;
import cn.com.countrygarden.bi.main.util.RedisUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ComparatorUtils;
import org.apache.commons.collections4.comparators.ComparableComparator;
import org.apache.commons.collections4.comparators.ComparatorChain;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by chenweijiang on 2017/9/13.
 */
@Service
@Transactional(readOnly = false, value = "txManager")
public class DupCommServiceImpl implements DupCommService {

    @Autowired
    private PilotCommMapper pilotCommMapper;

    @Autowired
    private TbHsprCommunityMapper tbHsprCommunityMapper;

    @Autowired
    private ManagerCommMapper managerCommMapper;
    @Autowired
    private OrganMapper organMapper;
    /**
     * 同步
     */
    @Override
    public void synchronizationOrg() {
        List<Map<String, Object>> response = new ArrayList<>();
        List<ErpCommunity> dupOrgans = tbHsprCommunityMapper.findAllComm();
        Byte isDelete ='0';
        for (ErpCommunity dupOrgan : dupOrgans) {
            Organ o = new Organ();
            o.setOrganCode(dupOrgan.getOrganCode());
            List<Organ> list= organMapper.select(o);

            o.setName(dupOrgan.getOrganName());
            o.setIsDelete(isDelete);
            try {
                if(list.size() < 1) {
                    o.setGmtCreate(new Date());
                    o.setCreateBy("sys");
                    organMapper.insert(o);
                }else {
                    o.setId(list.get(0).getId());
                    o.setGmtModified(new Date());
                    o.setModifiedBy("sys");
                    organMapper.updateByPrimaryKeySelective(o);
                }
            } catch (Exception e) {
                System.out.println(e);
            }

//             response.add(new HashMap<String, Object>() {{
//                 put("organCode", dupOrgan.getOrganCode());
//                 put("organName", dupOrgan.getOrganName());
//             }});
        }
    }
    @Override
    public List<DupOrgan> listAllComm() {
        Map<String, String> paramter = new HashMap<String, String>();
        List<ErpCommunity> erpCommunities = RedisCacheUtils.remeberList(DupCommConstant.ManagerComm.CACHE_KEY, DupCommConstant.ManagerComm.EXPIRED_TIME,
                paramter, ErpCommunity.class, p -> {
                    List<ErpCommunity> communities = tbHsprCommunityMapper.findAllBaseComm();
                    if (communities.size() > 0) {
                        Comparator cmp = ComparableComparator.comparableComparator();
                        cmp = ComparatorUtils.nullLowComparator(cmp);
                        ArrayList<Object> sortFields = new ArrayList<Object>();
                        sortFields.add(new BeanComparator("organCode", cmp));
                        sortFields.add(new BeanComparator("commId", cmp));
                        ComparatorChain multiSort = new ComparatorChain(sortFields);
                        Collections.sort(communities, multiSort);
                    }
                    return communities;
                }
        );

        List<ManagerComm> managerCommList = managerCommMapper.selectAll();
        Map<String, String> managerCommMap = new HashMap<String, String>();
        for (ManagerComm mComm : managerCommList) {
            managerCommMap.put(mComm.getErpCommId(), mComm.getErpCommId());
        }

        List<DupOrgan> result = new ArrayList<DupOrgan>();
        DupOrgan dupOrgan = new DupOrgan();
        for (ErpCommunity comm : erpCommunities) {
            if (comm.getOrganCode() != null && comm.getOrganCode().equals(dupOrgan.getOrganCode())) {
                DupComm dupComm = new DupComm();
                dupComm.setCommId(comm.getCommId());
                dupComm.setCommName(comm.getCommName());
                dupComm.setNcSystemNumber(comm.getNcSystemNumber());
                if (managerCommMap.get(dupComm.getCommId()) != null) {
                    dupComm.setManagerComm(Boolean.TRUE);
                } else {
                    dupComm.setManagerComm(Boolean.FALSE);
                }
                List<DupComm> dupComms = dupOrgan.getComms();
                if (dupComms == null) {
                    dupComms = new ArrayList<DupComm>();
                    dupOrgan.setComms(dupComms);
                }
                dupComms.add(dupComm);
            } else {
                dupOrgan = new DupOrgan();
                dupOrgan.setOrganCode(comm.getOrganCode());
                dupOrgan.setOrganName(comm.getOrganName());
                List<DupComm> dupComms = new ArrayList<DupComm>();
                DupComm dupComm = new DupComm();
                dupComm.setCommId(comm.getCommId());
                dupComm.setCommName(comm.getCommName());
                dupComm.setNcSystemNumber(comm.getNcSystemNumber());
                if (managerCommMap.get(dupComm.getCommId()) != null) {
                    dupComm.setManagerComm(Boolean.TRUE);
                } else {
                    dupComm.setManagerComm(Boolean.FALSE);
                }
                dupComms.add(dupComm);
                dupOrgan.setComms(dupComms);
                result.add(dupOrgan);
            }
        }
        return result;
    }


    @Autowired
    private UserRoleService userRoleService;

    /**
     * 根据人员查询组织权限
     * 1. 是否管理员查询全部
     * 2。 列表数据加载的数据权限也要根据该功能变化
     * @param userCode
     * @param organCode
     * @param isPilot
     * @param isManager
     * @return
     */
    @Override
    public List<DupOrgan> findDupCommByUserCode(String userCode, String organCode, boolean isPilot, boolean isManager) {
        Map<String, String> paramter = new HashMap<String, String>();
        paramter.put("userCode", userCode);
        paramter.put("organCode", organCode);
        paramter.put("isPilot", isPilot + "");
        paramter.put("isManager", isManager + "");
//        List<DupOrgan> cacheResult = RedisCacheUtils.remeberList(DupCommConstant.CACHE_KEY, DupCommConstant.EXPIRED_TIME,
//                paramter, DupOrgan.class, p -> {
        Map<String, String> managerCommMap = new HashMap<String, String>();
        Integer count = userRoleService.countByUserCodeAndRoleCode(userCode,"admin");
        if(count>0){
            List<DupOrgan> result =managerMapForErpMapper.queryAllRegion();
            for (DupOrgan organ : result) {
                List<DupComm> comms=managerMapForErpMapper.queryAllComm(organ.getOrganCode());
                organ.setComms(comms);
            }
            return  result;
        }
        if (isManager) {
            List<ManagerComm> managerCommList = managerCommMapper.selectAll();
            for (ManagerComm mComm : managerCommList) {
                managerCommMap.put(mComm.getErpCommId(), mComm.getErpCommId());
            }
        }
        List<DupOrgan> result = new ArrayList<DupOrgan>();
        List<TreeNode> companyTree = getCommTree(userCode);
        if(!CollectionUtils.isEmpty(companyTree)&&!CollectionUtils.isEmpty(companyTree.get(0).getChildren())){
            for (TreeNode compList : companyTree) {
                List<TreeNode> regionList = compList.getChildren();
                for (int i = 0; i < regionList.size(); i++) {
                    TreeNode treeNode = regionList.get(i);
                    DupOrgan organ = new DupOrgan();
                    organ.setOrganCode(treeNode.getId());
                    organ.setOrganName(treeNode.getLabel());
                    List<DupComm> comms = new ArrayList<>();
                    if (treeNode.getChildren() == null) {
                        result.add(organ);
                        continue;
                    }
                    for (TreeNode node : treeNode.getChildren()) {
                        DupComm comm = new DupComm();
                        comm.setCommId(node.getId());
                        comm.setCommName(node.getLabel());
                        comm.setNcSystemNumber(node.getNcSystemNumber());
                        if (!isManager || managerCommMap.get(comm.getCommId()) != null) {
                            comms.add(comm);
                        }
                    }
                    organ.setComms(comms);
                    result.add(organ);
                }
            }
        }
//        if (isManager) {
//            List<DupOrgan> managerResult = new ArrayList<>();
//            for (DupOrgan organ : result) {
//                if (organ.getComms() != null && organ.getComms().size() > 0) {
//                    managerResult.add(organ);
//                }
//            }
//            return managerResult;
//        }
        return uniqueData(result);
//                });
//        return cacheResult;
    }

    @Override
    public List<DupOrgan> findDupCommByUserCodeCase(String userCode, String organCode, boolean isPilot, boolean isManager) {
        Map<String, String> paramter = new HashMap<String, String>();
        paramter.put("userCode", userCode);
        paramter.put("organCode", organCode);
        paramter.put("isPilot", isPilot + "");
        paramter.put("isManager", isManager + "");
//        List<DupOrgan> cacheResult = RedisCacheUtils.remeberList(DupCommConstant.CACHE_KEY, DupCommConstant.EXPIRED_TIME,
//                paramter, DupOrgan.class, p -> {
        Map<String, String> managerCommMap = new HashMap<String, String>();
        Integer count = userRoleService.countByUserCodeAndRoleCode(userCode,"admin");
        List<String> CommIdfenghuang=tbHsprCommunityMapper.findCommsByUserCodeAndOrganCodefenghuang(userCode,organCode);
        if(count>0){
            List<DupOrgan> result =managerMapForErpMapper.queryAllRegion();
            for (DupOrgan organ : result) {
                //查项目
                List<DupComm> comms=managerMapForErpMapper.queryAllCommCase(organ.getOrganCode(),CommIdfenghuang);
                organ.setComms(comms);
            }
            return  result;
        }
        if (isManager) {
            List<ManagerComm> managerCommList = managerCommMapper.selectAll();
            for (ManagerComm mComm : managerCommList) {
                managerCommMap.put(mComm.getErpCommId(), mComm.getErpCommId());
            }
        }
        List<DupOrgan> result = new ArrayList<DupOrgan>();
        List<TreeNode> companyTree = getCommTree(userCode);
        if(!CollectionUtils.isEmpty(companyTree)&&!CollectionUtils.isEmpty(companyTree.get(0).getChildren())){
            for (TreeNode compList : companyTree) {
                List<TreeNode> regionList = compList.getChildren();
                for (int i = 0; i < regionList.size(); i++) {
                    TreeNode treeNode = regionList.get(i);
                    DupOrgan organ = new DupOrgan();
                    organ.setOrganCode(treeNode.getId());
                    organ.setOrganName(treeNode.getLabel());
                    List<DupComm> comms = new ArrayList<>();
                    if (treeNode.getChildren() == null) {
                        result.add(organ);
                        continue;
                    }
                    for (TreeNode node : treeNode.getChildren()) {
                        DupComm comm = new DupComm();
                        comm.setCommId(node.getId());
                        comm.setCommName(node.getLabel());
                        comm.setNcSystemNumber(node.getNcSystemNumber());
                        if (!isManager || managerCommMap.get(comm.getCommId()) != null) {
                            comms.add(comm);
                        }
                    }
                    organ.setComms(comms);
                    result.add(organ);
                }
            }
        }

        return uniqueData(result);

    }

    Logger logger= LoggerFactory.getLogger(DupCommServiceImpl.class);
    /**
     * 合并多个公司的区域权限
     * @param result
     * @return
     */
    private List<DupOrgan> uniqueData(List<DupOrgan> result) {
        List<DupOrgan> data=new ArrayList<>();
        Map<String,DupOrgan> organMap=new HashMap<>();
        System.out.println("区域权限："+ (CollectionUtils.isEmpty(result)?"":JSON.toJSONString(result)));
        for (DupOrgan organ : result) {
            if(organMap.containsKey(organ.getOrganCode())){
                List<DupComm> comms = organMap.get(organ.getOrganCode()).getComms();
                if(CollectionUtils.isEmpty(comms)){
                    comms=new ArrayList<>();
                }
                if(!CollectionUtils.isEmpty(organ.getComms())){
                    comms.addAll(organ.getComms());
                }
                organMap.get(organ.getOrganCode()).setComms(comms);
            }else{
                organMap.put(organ.getOrganCode(),organ);
            }
        }
        for (String s:organMap.keySet()){
            data.add(organMap.get(s));
        }

        System.out.println("区域权限："+ (CollectionUtils.isEmpty(data)?"":JSON.toJSONString(data)));
        return data;
    }

    @Autowired
    private ManagerMapForErpMapper managerMapForErpMapper;

    public List<TreeNode> getCommTree(String userCode) {
        List<TreeNode> tree = new LinkedList<>();
        List<CommunityInfo> communityInfoList = managerMapForErpMapper.queryCommInfo(null);
        List<Integer> commIds = managerMapForErpMapper.queryCommId(userCode);
        System.out.println("区域集："+ (CollectionUtils.isEmpty(communityInfoList)?"":JSON.toJSONString(communityInfoList)));
        System.out.println("已有区域集："+ commIds);

        TreeNode tempCompany = new TreeNode();
        TreeNode tempOrgan = new TreeNode();
        for (CommunityInfo info : communityInfoList) {
            logger.info(info.getCommID()+"");
            TreeNode communityTreeNode = new TreeNode(info.getCommID().toString(), info.getCommName());
            communityTreeNode.setNcSystemNumber(info.getNcSystemNumber());
            for (Integer id : commIds) {
//                String idStr= id+"";
//                if(info.getCommID()==186902){
//                    System.out.println("123213");
//                }
                if (id==info.getCommID()||info.getCommID().equals(id)) {
                    if (info.getCompanyCode().equals(tempCompany.getId())) {
                        if (info.getOrganCode().equals(tempOrgan.getId())) {
                            // 同一（城市）公司，同一区域，不同项目
                            tempCompany.getChildren().get(tempCompany.getChildren().size() - 1)
                                    .getChildren().add(communityTreeNode);
                        } else {
                            // 同一（城市）公司，不同区域
                            tempOrgan = new TreeNode(info.getOrganCode(), info.getOrganName(), new LinkedList<>());
                            tempOrgan.getChildren().add(communityTreeNode);
                            tempCompany.getChildren().add(tempOrgan);
                        }
                    } else {
                        // 将（城市）公司临时变量加入结果列表中，排除第一次循环
                        if (!StringUtils.isEmpty(tempCompany.getId())) {
                            tree.add(tempCompany);
                        }

                        // 从当前记录获取（城市）公司的编码和名称、区域的编码和名称、项目的ID和名称，并保存在临时变量中
                        tempOrgan = new TreeNode(info.getOrganCode(), info.getOrganName(), new LinkedList<>());
                        tempOrgan.getChildren().add(communityTreeNode);
                        tempCompany = new TreeNode(info.getCompanyCode(), info.getCompanyName(), new LinkedList<>());
                        tempCompany.getChildren().add(tempOrgan);
                    }
                }
            }
        }
        // 最后一个（城市）公司临时变量也需加入到结果列表中
        tree.add(tempCompany);

        return tree;
    }

    @Override
    public List<ErpCommunity> findByUserCode(String userCode, String organCode, boolean isPilot) {
        List<ErpCommunity> result = new ArrayList<ErpCommunity>();
        List<PilotComm> pilotCommList = new ArrayList<PilotComm>();
        List<ErpCommunity> erpCommunity = findErpCommunitByUserCode(userCode, organCode);

        if (isPilot) {
            PilotComm query = new PilotComm();
            query.setOrganCode(organCode);
            pilotCommList = pilotCommMapper.select(query);
        }
        if (pilotCommList.size() == 0) {
            return erpCommunity;
        } else {
            Map<String, PilotComm> keyMap = new HashMap<String, PilotComm>();
            for (PilotComm comm : pilotCommList) {
                keyMap.put(comm.getOrganCode() + ":" + comm.getCommId(), comm);
            }
            for (ErpCommunity comm : erpCommunity) {
                String key = comm.getOrganCode() + ":" + comm.getCommId();
                if (keyMap.get(key) != null) {
                    result.add(comm);
                }
            }
        }

        return result;
    }

    public List<ErpCommunity> findErpCommunitByUserCode(String userCode, String organCode) {
        List<ErpCommunity> result = new ArrayList<ErpCommunity>();

        //查区域范围
        List<ErpCommunity> organBaseList = tbHsprCommunityMapper.findOrganBaseByUserCode(userCode, organCode);
        List<String> organCodes = new ArrayList<String>();
        for (ErpCommunity organBase : organBaseList) {
            organCodes.add(organBase.getOrganCode());
        }
        if (organCodes.size() > 0) {
            organBaseList = tbHsprCommunityMapper.findCommBaseByOrgCodes(organCodes);
        }
        //查项目范围
        List<ErpCommunity> commBaseList = tbHsprCommunityMapper.findCommBaseByUserCode(userCode, organCode);
        Map<String, String> checkDuplicateMap = new HashMap<String, String>();
        for (ErpCommunity comm : organBaseList) {
            if (checkDuplicateMap.get(comm.getCommId()) == null) {
                checkDuplicateMap.put(comm.getCommId(), comm.getCommId());
                result.add(comm);
            }
        }
        for (ErpCommunity comm : commBaseList) {
            if (checkDuplicateMap.get(comm.getCommId()) == null) {
                checkDuplicateMap.put(comm.getCommId(), comm.getCommId());
                result.add(comm);
            }
        }

        return result;
    }

    @Override
    @Transactional(readOnly = false)
    public void addManagerComm(String commId, String userCode) {

        ManagerComm query = new ManagerComm();
        query.setErpCommId(commId);
        List<ManagerComm> duplicateList = managerCommMapper.select(query);
        if (duplicateList.size() > 0) {
            return;
        }
        ManagerComm entity = new ManagerComm();
        entity.setErpCommId(commId);
        entity.setCreatedBy(userCode);
        entity.setGmtCreate(new Date());
        managerCommMapper.insert(entity);
        Set<String> keys = RedisUtils.getKeys("*" + DupCommConstant.CACHE_KEY + "*");
        if (keys.size() > 0) {
            for (String key : keys) {
                RedisUtils.del(key);
            }
        }
    }

    @Override
    @Transactional(readOnly = false)
    public void deleteManagerComm(String commId) {
        PilotComm query = new PilotComm();
        query.setCommId(commId);
        List<PilotComm> pilotComms = pilotCommMapper.select(query);
        if (pilotComms.size() > 0) {
            throw new ServiceException("该项目属于浮标试点项目，不能有移除");
        }
        ManagerComm delteComm = new ManagerComm();
        delteComm.setErpCommId(commId);
        managerCommMapper.delete(delteComm);
        Set<String> keys = RedisUtils.getKeys("*" + DupCommConstant.CACHE_KEY + "*");
        if (keys.size() > 0) {
            for (String key : keys) {
                RedisUtils.del(key);
            }
        }
    }


    /**
     * 通过userCode去查询所有该用户可查看的区域
     *
     * @param userCode
     * @return
     */
    @Override
    public List<Map<String, String>> findOrgansByUserCode(String userCode) {
        List<Map<String, String>> resultList = new ArrayList<>();
        List<ErpCommunity> erpCommunityList = tbHsprCommunityMapper.findOrgansByUserCode(userCode);
        if (erpCommunityList != null && erpCommunityList.size() > 0) {
            for (ErpCommunity erpCommunity : erpCommunityList) {
                Map<String, String> tempMap = new HashMap<>();
                tempMap.put("organCode", erpCommunity.getOrganCode());
                tempMap.put("organName", erpCommunity.getOrganName());
                resultList.add(tempMap);
            }
        }

        return resultList;

    }

    @Override
    public List<Map<String, String>> findCommsByUserCodeAndOrganCode(String userCode, String organCode) {
        List<Map<String, String>> resultList = new ArrayList<>();
        List<ErpCommunity> erpCommunityList = tbHsprCommunityMapper.findCommsByUserCodeAndOrganCode(userCode, organCode);

        if (erpCommunityList != null && erpCommunityList.size() > 0) {
            for (ErpCommunity erpCommunity : erpCommunityList) {
                Map<String, String> tempMap = new HashMap<>();
                tempMap.put("commId", erpCommunity.getCommId());
                tempMap.put("commName", erpCommunity.getCommName());
                resultList.add(tempMap);
            }
        }

        return resultList;
    }

    @Override
    public List<Map<String, String>> findCommsByUserCode(String userCode) {

        List<Map<String, String>> resultList = new ArrayList<>();
        List<ErpCommunity> erpCommunityList = tbHsprCommunityMapper.findCommsByUserCode(userCode);

        if (erpCommunityList != null && erpCommunityList.size() > 0) {
            for (ErpCommunity erpCommunity : erpCommunityList) {
                Map<String, String> tempMap = new HashMap<>();
                tempMap.put("commId", erpCommunity.getCommId());
                tempMap.put("commName", erpCommunity.getCommName());
                resultList.add(tempMap);
            }
        }

        return resultList;
    }


}
