package com.api.browser.service.impl;

import com.api.browser.bean.SearchConditionItem;
import com.api.browser.service.BrowserService;
import com.api.browser.util.BrowserConstant;
import com.api.hrm.bean.TreeNode;
import com.cloudstore.eccom.result.WeaResultMsg;
import com.engine.organization.component.OrganizationWeaTable;
import com.engine.organization.entity.browser.bo.CusBowserTreeBO;
import com.engine.organization.entity.browser.enums.TreeNodeTypeEnum;
import com.engine.organization.entity.browser.po.CusBrowserTree;
import com.engine.organization.entity.company.po.CompPO;
import com.engine.organization.entity.department.po.DepartmentPO;
import com.engine.organization.entity.job.vo.JobBrowserVO;
import com.engine.organization.entity.searchtree.SearchTree;
import com.engine.organization.entity.searchtree.SearchTreeParams;
import com.engine.organization.mapper.comp.CompMapper;
import com.engine.organization.mapper.department.DepartmentMapper;
import com.engine.organization.util.OrganizationFormItemUtil;
import com.engine.organization.util.db.DBType;
import com.engine.organization.util.db.MapperProxyFactory;
import com.engine.organization.util.detach.DetachUtil;
import com.engine.organization.util.tree.SearchTreeUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;

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

/**
 * @author:dxfeng
 * @createTime: 2022/07/15
 * @version: 1.0
 */
public class JobBrowserService extends BrowserService {


    @Override
    public Map<String, Object> getBrowserData(Map<String, Object> params) {

        Map<String, Object> resultMap = new HashMap<>();
        String datatype = Util.null2String(params.get("datatype"));
        if ("tree".equals(datatype)) {
            String id = Util.null2String(params.get("id"));
            SearchTreeParams searchTreeParams = new SearchTreeParams();
            searchTreeParams.setId(id);
            String[] idArray = id.split("_");
            if (idArray.length == 2) {
                if (TreeNodeTypeEnum.TYPE_COMP.getName().equals(idArray[0])) {
                    searchTreeParams.setType(TreeNodeTypeEnum.TYPE_COMP.getValue());
                } else if (TreeNodeTypeEnum.TYPE_DEPT.getName().equals(idArray[0])) {
                    searchTreeParams.setType(TreeNodeTypeEnum.TYPE_DEPT.getValue());
                }
                searchTreeParams.setId(idArray[1]);
            }
            List<TreeNode> nodeData = getCurrentTreeNode(searchTreeParams);
            List<CusBrowserTree> cusBrowserTrees = CusBowserTreeBO.convertSearchTreeToBorwserTree(nodeData);
            resultMap.put("datas", cusBrowserTrees);
        } else {
            OrganizationWeaTable<JobBrowserVO> table = new OrganizationWeaTable<>(user, JobBrowserVO.class);
            String sqlWhere = buildSqlWhere(params);
            table.setSqlwhere(sqlWhere);
            WeaResultMsg result = new WeaResultMsg(false);
            result.putAll(table.makeDataResult());
            result.success();
            resultMap.putAll(result.getResultMap());
        }
        return resultMap;
    }

    @Override
    public Map getBrowserConditionInfo(Map<String, Object> map) {
        Map<String, List<SearchConditionItem>> apiDatas = new HashMap<>();
        List<SearchConditionItem> conditions = new ArrayList<>();
        // 编号
        SearchConditionItem jobNoItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "编号", "jobNo");
        // 名称
        SearchConditionItem jobNameItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "名称", "jobName");
        // 所属分部
        SearchConditionItem parentCompBrowserItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "所属分部", "164", "ecCompany", "");
        // 所属部门
        SearchConditionItem parentDeptBrowserItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "所属部门", "4", "ecDepartment", "");

        conditions.add(jobNoItem);
        conditions.add(jobNameItem);
        conditions.add(parentCompBrowserItem);
        conditions.add(parentDeptBrowserItem);
        apiDatas.put(BrowserConstant.BROWSER_RESULT_CONDITIONS, conditions);
        return apiDatas;
    }

    /**
     * 查询条件
     *
     * @param params
     * @return
     */
    private String buildSqlWhere(Map<String, Object> params) {
        DBType dbType = DBType.get(new RecordSet().getDBType());
        String sqlWhere = " where t.delete_type = 0 ";
        String jobNo = Util.null2String(params.get("jobNo"));
        if (StringUtils.isNotBlank(jobNo)) {
            sqlWhere += " AND t.job_no " + dbType.like(jobNo);
        }
        String jobName = Util.null2String(params.get("jobName"));
        if (StringUtils.isNotBlank(jobName)) {
            sqlWhere += " AND h.jobtitlename " + dbType.like(jobName);
        }
        String ecCompany = Util.null2String(params.get("ecCompany"));
        if (StringUtils.isNotBlank(ecCompany)) {
            sqlWhere += " AND t.ec_company = '" + Long.parseLong(ecCompany) + "'";
        }
        String ecDepartment = Util.null2String(params.get("ecDepartment"));
        if (StringUtils.isNotBlank(ecDepartment)) {
            sqlWhere += " AND t.ec_department = '" + Long.parseLong(ecDepartment) + "'";
        }
        String treeKey = Util.null2String(params.get("treeKey"));
        if (StringUtils.isNotBlank(treeKey)) {
            String[] keyArray = treeKey.split("_");
            if (keyArray.length == 2) {
                if (TreeNodeTypeEnum.TYPE_COMP.getName().equals(keyArray[0])) {
                    sqlWhere += " AND t.ec_company = '" + Long.parseLong(keyArray[1]) + "'";
                } else if (TreeNodeTypeEnum.TYPE_DEPT.getName().equals(keyArray[0])) {
                    sqlWhere += " AND t.ec_department = '" + Long.parseLong(keyArray[1]) + "'";
                }
            }
        }
        // 分权
        DetachUtil detachUtil = new DetachUtil(user);
        if (detachUtil.isDETACH()) {
            sqlWhere += "  AND t.parent_comp  in (" + detachUtil.getJclRoleLevels() + ")";
        }
        return sqlWhere;
    }

    /**
     * 获取当前点击节点下的层级数据
     *
     * @param params
     * @return
     */
    private List<TreeNode> getCurrentTreeNode(SearchTreeParams params) {
        // 分权
        DetachUtil detachUtil = new DetachUtil(user);
        List<Long> jclRoleLevelList;
        if (StringUtils.isNotBlank(detachUtil.getJclRoleLevels())) {
            jclRoleLevelList = Arrays.stream(detachUtil.getJclRoleLevels().split(",")).map(Long::parseLong).collect(Collectors.toList());
        } else {
            jclRoleLevelList = new ArrayList<>();
        }
        List<TreeNode> treeNodes = new ArrayList<>();
        if (StringUtils.isBlank(params.getId())) {
            // 集团总部
            SearchTree topGroup = SearchTreeUtil.getTopGroup();
            if (detachUtil.isDETACH()) {
                topGroup.setIsParent(StringUtils.isNotBlank(detachUtil.getJclRoleLevels()));
            } else {
                topGroup.setIsParent(true);
            }
            treeNodes.add(topGroup);
        } else {
            // 分部存在下级的ID
            List<String> compHasSubs;
            if (detachUtil.isDETACH()) {
                if (CollectionUtils.isNotEmpty(jclRoleLevelList)) {
                    compHasSubs = MapperProxyFactory.getProxy(CompMapper.class).hasDetachSubs(jclRoleLevelList);
                } else {
                    compHasSubs = new ArrayList<>();
                }
            } else {
                compHasSubs = MapperProxyFactory.getProxy(CompMapper.class).hasSubs();
            }
            // 部门存在下级的ID
            List<String> hasSubDepartment = MapperProxyFactory.getProxy(DepartmentMapper.class).hasSubs();

            if ("0".equals(params.getId())) {
                List<CompPO> compList;
                if (detachUtil.isDETACH()) {
                    if (CollectionUtils.isNotEmpty(jclRoleLevelList)) {
                        compList = MapperProxyFactory.getProxy(CompMapper.class).getCompsByIds(jclRoleLevelList);
                        // 处理上下级关系
                        Set<Integer> collectIds = compList.stream().map(CompPO::getId).collect(Collectors.toSet());
                        compList.removeIf(item -> collectIds.contains(item.getSupSubComId()));

                    } else {
                        compList = new ArrayList<>();
                    }
                } else {
                    compList = MapperProxyFactory.getProxy(CompMapper.class).listParent();
                }
                // 获取顶层分部
                compList.stream().sorted(Comparator.comparing(item -> null == item.getShowOrder() ? 0 : item.getShowOrder())).forEach(item -> buildCompNodes(treeNodes, compHasSubs, item));
            } else if ("1".equals(params.getType())) {
                // 当前节点下的元素
                CompPO compBuild = CompPO.builder().supSubComId(Integer.parseInt(params.getId())).canceled(0).build();
                List<CompPO> compList = MapperProxyFactory.getProxy(CompMapper.class).listByFilter(compBuild, "showorder");
                if (detachUtil.isDETACH()) {
                    detachUtil.filterCompanyList(compList);
                }
                DepartmentPO departmentBuild = DepartmentPO.builder().subCompanyId1(Integer.parseInt(params.getId())).canceled(0).build();
                List<DepartmentPO> departmentList = MapperProxyFactory.getProxy(DepartmentMapper.class).listByFilter(departmentBuild, "showorder");
                compList.forEach(item -> buildCompNodes(treeNodes, compHasSubs, item));

                departmentList.stream().filter(item -> null == item.getSupDepId() || 0 == item.getSupDepId()).forEach(item -> buildDeptNodes(treeNodes, hasSubDepartment, item));
            } else if ("2".equals(params.getType())) {
                DepartmentPO departmentBuild = DepartmentPO.builder().supDepId(Integer.parseInt(params.getId())).canceled(0).build();
                List<DepartmentPO> departmentList = MapperProxyFactory.getProxy(DepartmentMapper.class).listByFilter(departmentBuild, "showorder");
                departmentList.forEach(item -> buildDeptNodes(treeNodes, hasSubDepartment, item));
            }

        }
        return treeNodes;
    }


    /**
     * 构建分部节点
     *
     * @param treeNodes
     * @param compHasSubs
     * @param company
     */
    private void buildCompNodes(List<TreeNode> treeNodes, List<String> compHasSubs, CompPO company) {
        SearchTree searchTree = new SearchTree();
        searchTree.setId(company.getId().toString());
        searchTree.setType(TreeNodeTypeEnum.TYPE_COMP.getValue());
        searchTree.setName(company.getSubCompanyName());
        searchTree.setIsParent(compHasSubs.contains(company.getId().toString()));
        treeNodes.add(searchTree);
    }

    /**
     * 构建部门节点
     *
     * @param treeNodes
     * @param hasSubDepartment
     * @param department
     */
    private void buildDeptNodes(List<TreeNode> treeNodes, List<String> hasSubDepartment, DepartmentPO department) {
        SearchTree searchTree = new SearchTree();
        searchTree.setId(department.getId().toString());
        searchTree.setName(department.getDepartmentName());
        searchTree.setType(TreeNodeTypeEnum.TYPE_DEPT.getValue());
        searchTree.setIsParent(hasSubDepartment.contains(department.getId().toString()));
        treeNodes.add(searchTree);
    }
}
