package com.chinaweal.aiccs.org.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaweal.aiccs.common.base.entity.dto.login.LoginMessage;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.org.entity.OrgUnits;
import com.chinaweal.aiccs.org.entity.dto.OrgTreeNode;
import com.chinaweal.aiccs.org.entity.vo.CascaderVO;
import com.chinaweal.aiccs.org.mapper.AicorgMapper;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aicorg.pojo.AICUser;
import com.chinaweal.aicorg.services.OrgUM;
import com.chinaweal.youfool.framework.springboot.util.AssertUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 组织架构相关接口
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2020/8/18 10:20
 **/
@Service
public class AicorgServiceImpl extends ServiceImpl<AicorgMapper, OrgUnits> implements AicorgService {

    @Autowired
    private OrgUM orgUM;

    @Autowired
    private AicorgMapper aicorgMapper;

    @Override
    public List<OrgTreeNode> getOrgTreeWithPermission(List<String> permissions, LoginMessage loginMessage) {

        AssertUtils.isNotEmpty(permissions);
        List<OrgTreeNode> result = new ArrayList<>();

        List<AICUser> users = new ArrayList<>();
        if (permissions.contains("seed-area")) {      //seed-area标记：树结构与权限无关
            com.chinaweal.aicorg.model.AICUser aicUser = orgUM.findUserByPrimaryKey(loginMessage.getUserId());
            //查询当前用户的下级用户
            users = aicorgMapper.selectAllAICUserWithAreaOrglevel("69");
        } else {
            //查询所有包含指定权限的用户信息
            users = aicorgMapper.selectAllAICUserWithPermissions(permissions);
        }

        if (CollectionUtils.isEmpty(users)) return result;

        //获取架构树
        JSONArray orgTree = orgUM.getOrgTree();
        //获取工商机构类型的全部用户
        List<OrgUnits> aicOrgUnits = aicorgMapper.selectTreeOrgAndDeptByOrgUnitType("69");

        Set<OrgTreeNode> nodeSet = new HashSet<>(); // 用户所在的节点
        Map<String, OrgTreeNode> treeMap = new HashMap<>(); // 用于查找

        Set<OrgTreeNode> nodeOrgSet = new HashSet<>(); //区级单位节点集
        Set<OrgTreeNode> nodeDeptSet = new HashSet<>(); //区级单位的科室、所级单位的节点集

        if (permissions.contains("seed-area")) {


            for (int i = 0; i < aicOrgUnits.size(); i++) {
                OrgUnits orgUnit = aicOrgUnits.get(i);
                String id = StringUtils.trim(orgUnit.getOrgUnitId());
                String name = orgUnit.getOrgUnitName();
                String pId = StringUtils.trim(orgUnit.getParentId());
                String unitType = orgUnit.getUnitType();
                Integer level = orgUnit.getOrgLevel();
                OrgTreeNode node = new OrgTreeNode(pId, name, id, unitType, level);
                treeMap.put(id, node);
                if (pId.equals("150000") && unitType.equals("1")) {
                    nodeOrgSet.add(node);
                } else {
                    nodeDeptSet.add(node);
                }
            }
        } else {

            for (int i = 0; i < orgTree.size(); i++) {
                JSONObject each = orgTree.getJSONObject(i);
                String id = StringUtils.trim(each.getString("id"));
                String name = each.getString("text");
                String pId = StringUtils.trim(each.getString("pid"));
                OrgTreeNode node = new OrgTreeNode(pId, name, id);
                treeMap.put(id, node);
                for (AICUser user : users) {
                    if (id.equals(user.getOrgUnitId().trim())) {
                        nodeSet.add(node);
                        break;
                    }
                }
            }
        }


        if (permissions.contains("seed-area")) {

            //组装树
            Map<String, OrgTreeNode> duplicateMap = new HashMap<>(); // 去重map


            for (OrgTreeNode node : nodeDeptSet) {
                //组装树：所级单位下的用户
                if (node.getStatus().equals("1") && node.getLevel().equals(4)) {
                    for (AICUser user : users) {
                        if (user.getOrgUnitId().trim().equals(node.getValue())) {
                            node.addChild(new OrgTreeNode(node.getValue(), user.getRealName(), user.getUserId()));
                        }
                    }
                } else {//组装树：区级科室下的用户
                    for (AICUser user : users) {
                        if (user.getOrgDeptId().trim().equals(node.getValue())) {
                            node.addChild(new OrgTreeNode(node.getValue(), user.getRealName(), user.getUserId()));
                        }
                    }
                }

            }

            //组装树：将区级科室+所级单位追加到区级单位下
            for (OrgTreeNode deptNode : nodeDeptSet) {
                for (OrgTreeNode orgNode : nodeOrgSet) {
                    if (deptNode.getPId().equals(orgNode.getValue())) {
                        orgNode.addChild(deptNode);
                        //针对区级的下级单位和科室进行排序，区级科室排在前面
                        orgNode.getChildren().sort((o1, o2) -> ((OrgTreeNode) o2).getStatus().compareTo(((OrgTreeNode) o1).getStatus()));
                    }
                }
            }

            //组装树：将区级单位追加到内蒙古自治区市场监督管理局单位下
            for (OrgTreeNode node : nodeOrgSet) {
                OrgTreeNode parent = treeMap.get("150000");
                parent.addChild(node);
                duplicateMap.put(parent.getValue(), parent);
            }

            result.addAll(duplicateMap.values());

        } else {
            // 组装树
            Map<String, OrgTreeNode> duplicateMap = new HashMap<>(); // 去重map
            for (OrgTreeNode node : nodeSet) {
                for (AICUser user : users) {
                    if (user.getOrgUnitId().trim().equals(node.getValue())) {
                        node.addChild(new OrgTreeNode(node.getValue(), user.getRealName(), user.getUserId()));
                    }
                }
                // 往上查找组装
                /*OrgTreeNode root = node;
                while (root.getPId() != null) {
                    OrgTreeNode parent = treeMap.get(root.getPId());
                    if (parent == null) break;
                    parent.addChild(root);
                    root = parent;
                }*/
                //duplicateMap.put(root.getValue(), root);
                if (node.getValue().equals("150000")) {
                    duplicateMap.put(node.getValue(), node);
                    continue;
                }

                OrgTreeNode parent = treeMap.get("150000");
                parent.addChild(node);
                duplicateMap.put(parent.getValue(), parent);


            }

            result.addAll(duplicateMap.values());
        }

        return result;
    }

    @Override
    public String getRegionByUser(com.chinaweal.aicorg.model.AICUser curUser) {
        if (curUser == null) return null;
        String id = curUser.getOrgID();
        String name = curUser.getOrgName();
        while (true) {
            String region = StringUtils.getRegionByStr(name);
            if (StringUtils.isNotBlank(region)) {
                return region;
            }
            OrgUnits parentOrg = aicorgMapper.selectParentOrg(id);
            if (parentOrg == null) break;
            id = parentOrg.getOrgUnitId();
            name = parentOrg.getOrgUnitName();
        }
        return null;
    }

    @Override
    public String getRegionCodeByUser(com.chinaweal.aicorg.model.AICUser curUser) {
        if (curUser == null) return null;
        if (StringUtils.isNotEmpty(curUser.getRegionID())) {
            return curUser.getRegionID().substring(0, Math.min(curUser.getRegionID().length(), 6));
        }
        return null;
    }

    @Override
    public OrgUnits queryByOrgNumber(String orgNumber) {
        return aicorgMapper.queryByOrgNumber(orgNumber);
    }

    @Override
    public List<com.chinaweal.aicorg.model.AICUser> queryByOrgNumberAndSysMenu(String sysMenuFiled, String orgNumber) {
        return aicorgMapper.queryByOrgNumberAndSysMenu(sysMenuFiled, orgNumber);
    }

    @Override
    public List<String> jurisdictionCheck(String sysMenuFiled, String userid) {
        return aicorgMapper.jurisdictionCheck(sysMenuFiled, userid);
    }

    @Override
    public com.chinaweal.aicorg.model.AICUser queryUserByUserName(String username) {
        return aicorgMapper.queryUserByUserName(username);
    }

    @Override
    public String getOrgnumberByUserLevel(com.chinaweal.aicorg.model.AICUser user, boolean sjCheck) {
        String orgnumber = "";
//        LambdaQueryWrapper<OrgUnits> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(OrgUnits::getOrgUnitId, user.getOrgID());
//        OrgUnits orgunits = getOne(queryWrapper);
        OrgUnits orgunits = aicorgMapper.getOrgunitsByOrgId(user.getOrgID());
        if(orgunits.getOrgLevel() == 2){    //省级直接查省局自己的业务
            if(sjCheck){
                orgnumber = StringUtils.substring(orgunits.getOrgNumber(),0,2)+"%";
            } else {
                orgnumber = orgunits.getOrgNumber();
            }
        } else if(orgunits.getOrgLevel() == 3){    //地市
            orgnumber = StringUtils.substring(orgunits.getOrgNumber(),0,4)+"%";
        } else if(orgunits.getOrgLevel() >= 4){    //区级
            orgnumber = StringUtils.substring(orgunits.getOrgNumber(),0,6)+"%";
        }
        return orgnumber;
    }

    @Override
    public OrgUnits getTOrgunitsById(String orgUnitID) {
        return baseMapper.selectTOrgunitsById(orgUnitID);
    }

    @Override
    public OrgUnits queryByOrgNumberMap(Map<String, String> params) {
        return aicorgMapper.queryByOrgNumberMap(params);
    }

    @Override
    public String getRegionCodeByOrgLevel(com.chinaweal.aicorg.model.AICUser curUser) {
        Map<String, String> map = new HashMap<>();
        map.put("orgNumber", curUser.getRegionID());
        map.put("deleted", "0");
        map.put("unittype", "1");
        OrgUnits org = this.queryByOrgNumberMap(map);
        Integer orgLevel = org.getOrgLevel();
        String suporg = "";
        //根据机构等级判断
        if (orgLevel == 1) {    //省局
            suporg = StringUtils.substring(org.getOrgNumber(), 0, 2);
        } else if (orgLevel == 2) {    //市局
            suporg = StringUtils.substring(org.getOrgNumber(), 0, 4);
        } else if (orgLevel == 3) {    //区局
            suporg = StringUtils.substring(org.getOrgNumber(), 0, 6);
        } else if (orgLevel >= 4) {    //所
            suporg = StringUtils.substring(org.getOrgNumber(), 0, 6);
        }
        return suporg;
    }

    @Override
    public List<CascaderVO> queryAll(String orgNumber) {
        return baseMapper.queryAlls(orgNumber);
    }

    @Override
    public List<com.chinaweal.aicorg.model.AICUser> getUsersByOrgAndPermission(String perm, String orgId) {
        return aicorgMapper.selectUsersByOrgAndPermission(perm, orgId);
    }

    @Override
    public OrgUnits findParentOrgByPK(String deptId) {
        return aicorgMapper.selectParentOrgByDeptId(deptId);
    }
}
