package com.engine.organization.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.api.browser.bean.SearchConditionGroup;
import com.api.browser.bean.SearchConditionItem;
import com.api.browser.bean.SearchConditionOption;
import com.cloudstore.eccom.pc.table.WeaTableColumn;
import com.cloudstore.eccom.result.WeaResultMsg;
import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.hrm.entity.RuleCodeType;
import com.engine.organization.component.OrganizationWeaTable;
import com.engine.organization.entity.DeleteParam;
import com.engine.organization.entity.codesetting.po.CodeRulePO;
import com.engine.organization.entity.commom.RecordInfo;
import com.engine.organization.entity.company.bo.CompBO;
import com.engine.organization.entity.company.po.CompPO;
import com.engine.organization.entity.department.bo.DepartmentBO;
import com.engine.organization.entity.department.po.DepartmentPO;
import com.engine.organization.entity.employee.vo.EmployeeTableVO;
import com.engine.organization.entity.extend.po.ExtendTitlePO;
import com.engine.organization.entity.job.bo.JobBO;
import com.engine.organization.entity.job.dto.JobListDTO;
import com.engine.organization.entity.job.param.JobMergeParam;
import com.engine.organization.entity.job.param.JobSearchParam;
import com.engine.organization.entity.job.po.JobPO;
import com.engine.organization.entity.scheme.po.GradePO;
import com.engine.organization.entity.searchtree.SearchTree;
import com.engine.organization.entity.searchtree.SearchTreeParams;
import com.engine.organization.enums.LogModuleNameEnum;
import com.engine.organization.enums.OperateTypeEnum;
import com.engine.organization.mapper.codesetting.CodeRuleMapper;
import com.engine.organization.mapper.comp.CompMapper;
import com.engine.organization.mapper.department.DepartmentMapper;
import com.engine.organization.mapper.extend.ExtDTMapper;
import com.engine.organization.mapper.extend.ExtMapper;
import com.engine.organization.mapper.extend.ExtendTitleMapper;
import com.engine.organization.mapper.hrmresource.SystemDataMapper;
import com.engine.organization.mapper.job.JobMapper;
import com.engine.organization.mapper.scheme.GradeMapper;
import com.engine.organization.service.ExtService;
import com.engine.organization.service.JobService;
import com.engine.organization.thread.JobTriggerRunnable;
import com.engine.organization.thread.OrganizationSyncEc;
import com.engine.organization.trigger.cusfielddata.CusFieldDataTrigger;
import com.engine.organization.util.*;
import com.engine.organization.util.coderule.CodeRuleUtil;
import com.engine.organization.util.db.MapperProxyFactory;
import com.engine.organization.util.page.Column;
import com.engine.organization.util.page.PageInfo;
import com.engine.organization.util.page.PageUtil;
import com.engine.organization.util.relation.EcHrmRelationUtil;
import com.engine.organization.util.tree.SearchTreeUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.StringUtil;
import weaver.general.Util;
import weaver.hrm.User;

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

/**
 * @description:
 * @author:dxfeng
 * @createTime: 2022/05/26
 * @version: 1.0
 */
public class JobServiceImpl extends Service implements JobService {

    /**
     * 左侧树 类型表示
     * <p>
     * 0：集团
     * 1：分部
     * 2：部门
     */
    private static final String TYPE_COMP = "1";
    private static final String TYPE_DEPT = "2";

    /**
     * 分组类型
     * 1：分部
     * 2：部门
     * 3：岗位
     */
    private static final String EXTEND_TYPE = "3";
    /**
     * 主表
     */
    private static final String JCL_ORG_JOB = "JCL_ORG_JOB";
    /**
     * 主表拓展表
     */
    private static final String JCL_ORG_JOBEXT = "JCL_ORG_JOBEXT";
    /**
     * 明细表拓展表
     */
    private static final String JCL_ORG_JOBEXT_DT1 = "JCL_ORG_JOBEXT_DT1";

    private static final String RIGHT_NAME = "Job:All";

    public static final String JOB_ACTIVITY_ID;

    /**
     * 岗位主表title指定ID
     */
    private static final Long GROUP_ID = 3L;

    private static JobMapper getJobMapper() {
        return MapperProxyFactory.getProxy(JobMapper.class);
    }

    private CompMapper getCompMapper() {
        return MapperProxyFactory.getProxy(CompMapper.class);
    }

    private DepartmentMapper getDepartmentMapper() {
        return MapperProxyFactory.getProxy(DepartmentMapper.class);
    }

    private ExtendTitleMapper getExtendTitleMapper() {
        return MapperProxyFactory.getProxy(ExtendTitleMapper.class);
    }

    private ExtService getExtService(User user) {
        return ServiceUtil.getService(ExtServiceImpl.class, user);
    }


    static {
        RecordInfo hrmJobActivity = MapperProxyFactory.getProxy(SystemDataMapper.class).getHrmObjectByUUID("hrmjobactivities", "3a2efce3-95de-4ec2-afe1-347783817bdb");
        JOB_ACTIVITY_ID = hrmJobActivity.getId();
    }

    @Override
    public Map<String, Object> getSearchTree(SearchTreeParams params) {
        String keyword = params.getKeyword();
        String id = params.getId();
        String type = Util.null2String(params.getType());
        List<SearchTree> treeList = getFilterCompany(id, type, keyword);
        return SearchTreeUtil.getSearchTree(type, treeList);
    }

    @Override
    public Map<String, Object> listPage(JobSearchParam param) {
        Map<String, Object> datas = new HashMap<>();
        boolean hasRight = HasRightUtil.hasRight(user, RIGHT_NAME, true);
        datas.put("hasRight", hasRight);
        if (!hasRight) {
            return datas;
        }
        JobPO jobPO = JobBO.convertParamsToPO(param, user.getUID());
        boolean filter = isFilter(jobPO);
        PageInfo<JobListDTO> pageInfos;
        String orderSql = PageInfoSortUtil.getSortSql(param.getSortParams());
        List<JobListDTO> allList = getJobMapper().listNoFilter(orderSql);
        // 通过子级遍历父级元素
        if (filter) {
            // 根据条件获取元素
            List<JobListDTO> filterJobPOs = getJobMapper().listByFilter(jobPO, orderSql);
            // 添加父级元素
            List<JobListDTO> jobListDTOS = JobBO.buildJobDTOList(allList, filterJobPOs);
            List<JobListDTO> subList = PageUtil.subList(param.getCurrent(), param.getPageSize(), jobListDTOS);
            pageInfos = new PageInfo<>(subList, JobListDTO.class);
            pageInfos.setTotal(jobListDTOS.size());
        } else {
            // 组合list
            List<JobListDTO> jobListDTOS = JobBO.buildDTOList(allList);
            List<JobListDTO> subList = PageUtil.subList(param.getCurrent(), param.getPageSize(), jobListDTOS);
            pageInfos = new PageInfo<>(subList, JobListDTO.class);
            pageInfos.setTotal(jobListDTOS.size());
        }

        pageInfos.setPageNum(param.getCurrent());
        pageInfos.setPageSize(param.getPageSize());

        OrganizationWeaTable<JobListDTO> table = new OrganizationWeaTable<>(user, JobListDTO.class);
        List<Column> columns = pageInfos.getColumns();
        List<WeaTableColumn> weaTableColumn = columns.stream().map(v -> new WeaTableColumn("100", v.getTitle(), v.getKey())).collect(Collectors.toList());

        table.setColumns(weaTableColumn);

        WeaResultMsg result = new WeaResultMsg(false);
        result.putAll(table.makeDataResult());
        result.success();

        datas.put("pageInfo", pageInfos);
        datas.put("dataKey", result.getResultMap());
        return datas;
    }

    @Override
    public Map<String, List<MenuBtn>> getHasRight() {
        return MenuBtn.getDatasHasCopy();
    }

    @Override
    public Map<String, Object> getSearchCondition() {
        Map<String, Object> apiDatas = new HashMap<>();
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<SearchConditionItem> conditionItems = 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", "");
        // 岗位序列
        SearchConditionItem sequenceBrowserItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "岗位序列", "161", "sequenceId", "sequenceBrowser");
        // 等级方案
        SearchConditionItem schemeBrowserItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "等级方案", "161", "schemeId", "schemeBrowser");
        // 上级岗位
        SearchConditionItem parentJobBrowserItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "上级岗位", "666", "parentJob", "");
        // 是否关键岗
        List<SearchConditionOption> isKeyOptions = new ArrayList<>();
        SearchConditionOption yesOption = new SearchConditionOption("0", "否");
        SearchConditionOption noOption = new SearchConditionOption("1", "是");
        isKeyOptions.add(yesOption);
        isKeyOptions.add(noOption);
        SearchConditionItem isKeyItem = OrganizationFormItemUtil.selectItem(user, isKeyOptions, 2, 16, 6, false, "是否关键岗", "forbiddenTag");
        // 工作地点
        SearchConditionItem workplaceItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "工作地点", "workplace");
        // 禁用标记
        List<SearchConditionOption> selectOptions = new ArrayList<>();
        SearchConditionOption enableOption = new SearchConditionOption("true", "启用");
        SearchConditionOption disableOption = new SearchConditionOption("false", "禁用");
        selectOptions.add(enableOption);
        selectOptions.add(disableOption);
        SearchConditionItem forbiddenTagItem = OrganizationFormItemUtil.selectItem(user, selectOptions, 2, 16, 6, false, "禁用标记", "forbiddenTag");

        conditionItems.add(jobNoItem);
        conditionItems.add(jobNameItem);
        conditionItems.add(parentCompBrowserItem);
        conditionItems.add(parentDeptBrowserItem);
        conditionItems.add(sequenceBrowserItem);
        conditionItems.add(schemeBrowserItem);
        conditionItems.add(parentJobBrowserItem);
        conditionItems.add(isKeyItem);
        conditionItems.add(workplaceItem);
        conditionItems.add(forbiddenTagItem);

        addGroups.add(new SearchConditionGroup("高级搜索条件", true, conditionItems));
        apiDatas.put("conditions", addGroups);
        return apiDatas;
    }

    @Override
    public Map<String, Object> getSaveForm(JobSearchParam param) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        Map<String, Object> apiDatas = new HashMap<>();
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<ExtendTitlePO> extendTitles = getExtendTitleMapper().getTitlesByGroupID(GROUP_ID, "1");
        if (CollectionUtils.isNotEmpty(extendTitles)) {
            Map<String, Object> params = new HashMap<>();
            // 分部
            if (StringUtils.isNotBlank(Util.null2String(param.getSubcompanyid1()))) {
                CompPO compPO = getCompMapper().listById(param.getSubcompanyid1());
                if (null != compPO) {
                    params.put("parent_comp", compPO.getId());
                    params.put("ec_company", EcHrmRelationUtil.getEcCompanyId(compPO.getId().toString()));
                }
            }
            // 部门
            if (StringUtils.isNotBlank(Util.null2String(param.getDepartmentid()))) {
                DepartmentPO deptById = getDepartmentMapper().getDeptById(param.getDepartmentid());
                if (null != deptById) {
                    params.put("parent_dept", deptById.getId());
                    params.put("ec_department", EcHrmRelationUtil.getEcDepartmentId(deptById.getId().toString()));
                    params.put("parent_comp", deptById.getParentComp());
                    params.put("ec_company", EcHrmRelationUtil.getEcCompanyId(deptById.getParentComp().toString()));
                }
            }
            for (ExtendTitlePO extendTitle : extendTitles) {
                List<SearchConditionItem> items = getExtService(user).getExtSaveForm(user, EXTEND_TYPE + "", JCL_ORG_JOB, 2, extendTitle.getId().toString(), "job_no", RuleCodeType.JOBTITLES.getValue(), params, "scheme_id", "parent_comp");
                if (CollectionUtils.isNotEmpty(items)) {
                    addGroups.add(new SearchConditionGroup(extendTitle.getTitle(), true, items));
                }
            }
        }
        apiDatas.put("condition", addGroups);
        return apiDatas;
    }

    @Override
    public Map<String, Object> getJobBaseForm(Map<String, Object> params) {
        OrganizationAssert.notNull(params.get("viewAttr"), "请标识操作类型");

        // 2编辑 1查看
        int viewAttr = Integer.parseInt((String) params.get("viewAttr"));
        long id = Long.parseLong((String) params.get("id"));
        String groupId = (String) params.get("viewCondition");

        HashMap<String, Object> buttonsMap = new HashMap<>();
        buttonsMap.put("hasEdit", true);
        buttonsMap.put("hasSave", true);

        List<SearchConditionGroup> addGroups = new ArrayList<>();
        if ("0".equals(groupId)) {
            groupId = GROUP_ID.toString();
        }
        List<ExtendTitlePO> extendTitles = getExtendTitleMapper().getTitlesByGroupID(Long.parseLong(groupId), "1");
        if (CollectionUtils.isNotEmpty(extendTitles)) {
            for (ExtendTitlePO extendTitle : extendTitles) {
                List<SearchConditionItem> items = getExtService(user).getExtForm(user, EXTEND_TYPE + "", GROUP_ID.equals(Long.parseLong(groupId)) ? JCL_ORG_JOB : JCL_ORG_JOBEXT, viewAttr, id, extendTitle.getId().toString(), "scheme_id", "parent_comp");
                if (CollectionUtils.isNotEmpty(items)) {
                    addGroups.add(new SearchConditionGroup(extendTitle.getTitle(), true, items));
                }
            }
        }
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("buttons", buttonsMap);
        resultMap.put("conditions", addGroups);
        resultMap.put("id", id);
        // 拓展页面分组
        resultMap.put("tabInfo", getExtService(user).getTabInfo(EXTEND_TYPE, JCL_ORG_JOBEXT));
        // 处理明细表
        List<Map<String, Object>> extendTables = getExtService(user).getExtendTables(user, EXTEND_TYPE, Long.parseLong(groupId), JCL_ORG_JOBEXT_DT1, id, viewAttr, false);

        resultMap.put("tables", extendTables);

        Map<String, Object> apiDatas = new HashMap<>();

        apiDatas.put("result", resultMap);
        // 返回职等信息
        JobPO jobById = getJobMapper().getJobById(id);
        if (null != jobById && StringUtils.isNotBlank(jobById.getGradeId())) {
            GradePO gradeByID = MapperProxyFactory.getProxy(GradeMapper.class).getGradeByID(Long.parseLong(jobById.getGradeId()));
            if (null != gradeByID) {
                apiDatas.put("levelIds", gradeByID.getLevelId());
            }
        }

        return apiDatas;
    }

    @Override
    public Long saveBaseForm(Map<String, Object> params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        String jobNo = (String) params.get("job_no");
        // 判断是否开启自动编号
        jobNo = repeatDetermine(jobNo);
        params.put("job_no", jobNo);
        JobSearchParam searchParam = JSONObject.parseObject(JSONObject.toJSONString(params), JobSearchParam.class);

        params.put("is_key", null == searchParam.getIsKey() ? 0 : searchParam.getIsKey());
        Long ecDepartment = searchParam.getEcDepartment();
        DepartmentPO jclDepartment = EcHrmRelationUtil.getJclDepartmentId(Util.null2String(ecDepartment));
        params.put("parent_dept", jclDepartment.getId());
        params.put("parent_comp", jclDepartment.getParentComp());
        if (null != jclDepartment.getParentComp()) {
            params.put("ec_company", EcHrmRelationUtil.getEcCompanyId(Util.null2String(jclDepartment.getParentComp())));
        }

        if (StringUtils.isBlank(params.get("show_order").toString())) {
            Integer maxShowOrder = getJobMapper().getMaxShowOrder();
            if (null == maxShowOrder) {
                maxShowOrder = 0;
            }
            params.put("show_order", maxShowOrder + 1);
        }
        params.put("jobactivityid", JOB_ACTIVITY_ID);
        new OrganizationSyncEc(user, LogModuleNameEnum.JOB, OperateTypeEnum.ADD, params).sync();
        return getExtService(user).updateExtForm(user, EXTEND_TYPE, JCL_ORG_JOB, params, "", null);
    }

    @Override
    public Long updateForm(Map<String, Object> params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        JobSearchParam searchParam = JSONObject.parseObject(JSONObject.toJSONString(params), JobSearchParam.class);
        String groupId = (String) params.get("viewCondition");
        searchParam.setIsKey(null == searchParam.getIsKey() ? 0 : searchParam.getIsKey());
        if ("0".equals(groupId)) {
            groupId = GROUP_ID.toString();
        }
        JobPO oldJobPO = getJobMapper().getJobById(searchParam.getId());
        String oldJobNo = oldJobPO.getJobNo();
        String jobNo = searchParam.getJobNo();
        if (!jobNo.equals(oldJobNo)) {
            jobNo = repeatDetermine(jobNo);
            params.put("job_no", jobNo);
        }

        // 更新主表数据
        params.put("is_key", searchParam.getIsKey());
        Long ecDepartment = searchParam.getEcDepartment();
        DepartmentPO jclDepartment = EcHrmRelationUtil.getJclDepartmentId(Util.null2String(ecDepartment));
        params.put("parent_dept", jclDepartment.getId());
        params.put("parent_comp", jclDepartment.getParentComp());
        if (null != jclDepartment.getParentComp()) {
            params.put("ec_company", EcHrmRelationUtil.getEcCompanyId(Util.null2String(jclDepartment.getParentComp())));
        }
        params.put("jobactivityid", JOB_ACTIVITY_ID);
        new OrganizationSyncEc(user, LogModuleNameEnum.JOB, OperateTypeEnum.UPDATE, params, oldJobPO).sync();
        getExtService(user).updateExtForm(user, EXTEND_TYPE, JCL_ORG_JOB, params, "", searchParam.getId());
        // 更新主表拓展表
        getExtService(user).updateExtForm(user, EXTEND_TYPE, JCL_ORG_JOBEXT, params, groupId, searchParam.getId());
        // 更新明细表
        getExtService(user).updateExtDT(user, EXTEND_TYPE, JCL_ORG_JOBEXT_DT1, params, searchParam.getId());
        return searchParam.getId();
    }

    @Override
    public int copyJobItem(String ids, String department) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        OrganizationAssert.notBlank(department, "请指定需要复制的部门");
        int insertCount = 0;
        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        Integer orderNum = getJobMapper().getMaxShowOrder();
        orderNum = null == orderNum ? 0 : orderNum;
        for (Long id : idList) {
            orderNum++;
            JobPO jobById = getJobMapper().getJobById(id);
            // 处理自动编号
            jobById.setJobNo(CodeRuleUtil.generateCode(RuleCodeType.JOBTITLES, jobById.getJobNo(), System.currentTimeMillis()));
            // 部门赋值
            jobById.setEcDepartment(Long.parseLong(department));
            DepartmentPO jclDepartmentId = EcHrmRelationUtil.getJclDepartmentId(department);
            if (null != jclDepartmentId) {
                jobById.setParentDept(jclDepartmentId.getId());
                //分部赋值
                jobById.setEcCompany(jclDepartmentId.getEcCompany());
                jobById.setParentComp(jclDepartmentId.getParentComp());
            }
            // 清空上级岗位
            jobById.setParentJob(null);
            jobById.setShowOrder(orderNum);
            insertCount += getJobMapper().insertIgnoreNull(jobById);
            // 更新组织架构图
            new Thread(new JobTriggerRunnable(jobById.getId())).start();
        }

        return insertCount;
    }

    @Override
    public int updateForbiddenTagById(JobSearchParam params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        JobPO jobPO = JobPO.builder().id(params.getId()).forbiddenTag(params.getForbiddenTag() ? 0 : 1).jobName(getJobMapper().getJobById(params.getId()).getJobName()).build();
        new OrganizationSyncEc(user, LogModuleNameEnum.JOB, OperateTypeEnum.CANCELED, null, jobPO).sync();
        return getJobMapper().updateForbiddenTagById(jobPO.getId(), jobPO.getForbiddenTag());
    }

    @Override
    public int deleteByIds(Collection<Long> ids) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        OrganizationAssert.notEmpty(ids, "请选择要删除的数据");
        List<JobPO> jobsByIds = getJobMapper().getJobsByIds(ids);
        for (JobPO jobsById : jobsByIds) {
            jobsById.setForbiddenTag(1);
            new OrganizationSyncEc(user, LogModuleNameEnum.JOB, OperateTypeEnum.CANCELED, null, jobsById).sync();
            // 删除拓展表、明细表
            MapperProxyFactory.getProxy(ExtMapper.class).deleteByID("jcl_org_jobext", jobsById.getId());
            MapperProxyFactory.getProxy(ExtDTMapper.class).deleteByMainID("jcl_org_jobext_dt1", jobsById.getId());
        }
        return getJobMapper().deleteByIds(ids);
    }

    @Override
    public Map<String, Object> getHrmListByJobId(Long jobId) {
        OrganizationWeaTable<EmployeeTableVO> table = new OrganizationWeaTable<>(user, EmployeeTableVO.class);
        RecordSet rs = new RecordSet();
        List<String> ids = new ArrayList<>();
        rs.executeQuery("select id from cus_fielddata where field100002 = ?",jobId);
        while (rs.next()) {
            ids.add(Util.null2String(rs.getString("id")));
        }
        if (CollectionUtils.isEmpty(ids)){
            ids.add("-1");
        }
        table.setSqlwhere(" where id in ("+StringUtils.join(ids,",")+") and status<4");
        WeaResultMsg result = new WeaResultMsg(false);
        result.putAll(table.makeDataResult());
        result.success();
        return result.getResultMap();
    }

    @Override
    public List<SearchConditionGroup> getMergeForm(Long id) {
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<SearchConditionItem> condition = new ArrayList<>();
        SearchConditionItem deptBrowserItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 3, false, "合并到岗位", "666", "targetJob", "");
        deptBrowserItem.setRules("required");
        SearchConditionItem mergeNameItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 3, 50, "合并后名称", "mergeName");
        mergeNameItem.setRules("required|string");
        JobPO jobById = getJobMapper().getJobById(id);
        if (null != jobById) {
            String jobName = jobById.getJobName();
            mergeNameItem.setValue(jobName);
        }
        condition.add(deptBrowserItem);
        condition.add(mergeNameItem);
        addGroups.add(new SearchConditionGroup("", true, condition));
        return addGroups;
    }

    @Override
    public int mergeJob(JobMergeParam mergeParam) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        int updateCount = 0;
        OrganizationAssert.notNull(mergeParam.getTargetJob(), "请选择需要合并的岗位");

        // 不可选择岗位本身、以及子岗位
        Set<Long> disableIds = new HashSet<>();
        disableIds.add(mergeParam.getId());
        // 第一层级的子元素
        List<JobPO> jobs = getJobMapper().getJobsByPid(mergeParam.getId());
        if (CollectionUtils.isNotEmpty(jobs)) {
            addDisableIds(disableIds, jobs);
        }
        OrganizationAssert.isFalse(disableIds.contains(mergeParam.getTargetJob()), "请勿选择当前岗位本身及其子岗位");

        // 合并到的岗位
        JobPO targetJob = getJobMapper().getJobById(mergeParam.getTargetJob());
        // 合并后名称
        targetJob.setJobName(mergeParam.getMergeName());

        // 待合并的部门
        JobPO jobById = getJobMapper().getJobById(mergeParam.getId());

        // 递归处理子岗位所属分部、所部部门、上级岗位
        recursionMergeJob(jobs, targetJob.getParentComp(), targetJob.getEcCompany(), targetJob.getParentDept(), targetJob.getEcDepartment(), targetJob.getId());

        // 人员信息变动，更新分部、部门、岗位
        RecordSet rs = new RecordSet();
        rs.executeUpdate("SELECT ID FROM CUS_FIELDDATA WHERE SCOPEID =-1 AND FIELD100002 = ?", jobById.getId());
        while (rs.next()) {
            long userId = Long.parseLong(Util.null2String(rs.getString("ID")));
            // 更新岗位 、岗位更新触发器
            rs.executeUpdate("update CUS_FIELDDATA set FIELD100002 = ? where SCOPEID =-1 and id = ", targetJob.getId(), userId);
            CusFieldDataTrigger.run(userId);
            // 更新人员组织架构图
        }
        // 更新合并后的岗位，更新组织架构图
        updateEcJob(targetJob,mergeParam.getMergeName());

        targetJob.setJobName(mergeParam.getMergeName());
        getJobMapper().updateBaseJob(targetJob);
        new Thread(new JobTriggerRunnable(targetJob.getId())).start();
        // 原岗位删除
        jobById.setForbiddenTag(1);
        new OrganizationSyncEc(user, LogModuleNameEnum.JOB, OperateTypeEnum.CANCELED, null, jobById).sync();

        // 更新组织架构图
        new Thread(new JobTriggerRunnable(jobById)).start();
        return updateCount;
    }


    void recursionMergeJob(List<JobPO> jobs, Long parentCompany, Long ecCompany, Long parentDepartment, Long ecDepartment, Long parentJob) {
        for (JobPO job : jobs) {
            job.setParentComp(parentCompany);
            job.setEcCompany(ecCompany);
            job.setParentDept(parentDepartment);
            job.setEcDepartment(ecDepartment);
            job.setParentJob(parentJob);
            // 更新人员信息
            RecordSet rs = new RecordSet();
            rs.executeUpdate("SELECT ID FROM CUS_FIELDDATA WHERE SCOPEID =-1 AND FIELD100002 = ?", job.getId());
            while (rs.next()) {
                long userId = Long.parseLong(Util.null2String(rs.getString("ID")));
                // 更新人员分部、部门
                rs.executeUpdate("UPDATE HRMRESOURCE SET SUBCOMPANYID1 = ? , DEPARTMENTID = ? WHERE ID =? ", ecCompany, ecDepartment, userId);
                // 更新人员组织架构图
                CusFieldDataTrigger.run(userId);
            }
            // 更新组织架构图
            new Thread(new JobTriggerRunnable(job.getId())).start();

            // 递归处理子级元素
            List<JobPO> jobsByPid = getJobMapper().getJobsByPid(job.getId());
            recursionMergeJob(jobsByPid, parentCompany, ecCompany, parentDepartment, ecDepartment, parentJob);
        }
    }

    /**
     * 添加查询元素的父级元素
     *
     * @param departmentPO
     * @param builderDeparts
     */
    private void buildParentDepts(DepartmentPO departmentPO, Set<DepartmentPO> builderDeparts) {
        builderDeparts.add(departmentPO);
        if (SearchTreeUtil.isTop(departmentPO.getParentDept())) {
            return;
        }
        DepartmentPO parentDept = getDepartmentMapper().getDeptById(departmentPO.getParentDept());
        if (null != parentDept && 0 == parentDept.getForbiddenTag()) {
            buildParentDepts(parentDept, builderDeparts);
        }
    }

    /**
     * 添加查询元素的父级元素
     *
     * @param compPO
     * @param builderComps
     */
    private void buildParentComps(CompPO compPO, Set<CompPO> builderComps) {
        builderComps.add(compPO);
        if (SearchTreeUtil.isTop(compPO.getParentCompany())) {
            return;
        }
        CompPO parentComp = getCompMapper().listById(compPO.getParentCompany());
        if (null != parentComp && 0 == parentComp.getForbiddenTag()) {
            buildParentComps(parentComp, builderComps);
        }
    }

    /**
     * 根据keyword查询数据
     *
     * @param id
     * @param type
     * @param keyword
     * @return
     */
    private List<SearchTree> getFilterCompany(String id, String type, String keyword) {
        List<SearchTree> searchTree = new ArrayList<>();
        // 通过分部、公司 组装数据
        if (StringUtil.isEmpty(id) || TYPE_COMP.equals(type)) {
            Long parentCompId = StringUtil.isEmpty(id) ? null : Long.parseLong(id);
            DepartmentPO departmentBuild = DepartmentPO.builder().deptName(keyword).parentComp(parentCompId).forbiddenTag(0).build();
            CompPO compBuild = CompPO.builder().compName(keyword).parentCompany(parentCompId).forbiddenTag(0).build();
            searchTree = buildTreeByCompAndDept(departmentBuild, compBuild);
        } else if (TYPE_DEPT.equals(type)) {
            //
            // 查询部门信息
            List<DepartmentPO> filterDeparts = getDepartmentMapper().listByFilter(DepartmentPO.builder().deptName(keyword).forbiddenTag(0).parentDept(Long.parseLong(id)).build(), "show_order");
            Set<DepartmentPO> builderDeparts = new HashSet<>();
            for (DepartmentPO departmentPO : filterDeparts) {
                buildParentDepts(departmentPO, builderDeparts);
            }
            searchTree = SearchTreeUtil.builderTreeMode(DepartmentBO.buildSetToSearchTree(builderDeparts));

        }
        return searchTree;
    }

    /**
     * 分部、部门 组装左侧树
     *
     * @param departmentBuild
     * @param compBuild
     * @return
     */
    private List<SearchTree> buildTreeByCompAndDept(DepartmentPO departmentBuild, CompPO compBuild) {
        List<DepartmentPO> filterDeparts = getDepartmentMapper().listByFilter(departmentBuild, "show_order");
        // 查询分部信息
        List<CompPO> filterComps = getCompMapper().listByFilter(compBuild, "show_order");
        Set<DepartmentPO> builderDeparts = new HashSet<>();
        for (DepartmentPO departmentPO : filterDeparts) {
            buildParentDepts(departmentPO, builderDeparts);
        }
        List<SearchTree> deptTrees = SearchTreeUtil.builderTreeMode(DepartmentBO.buildSetToSearchTree(builderDeparts));
        // 添加部门的上级分部
        String parentCompS = deptTrees.stream().map(SearchTree::getParentComp).collect(Collectors.joining(","));
        if (!StringUtil.isEmpty(parentCompS)) {
            List<CompPO> compsByIds = getCompMapper().getCompsByIds(DeleteParam.builder().ids(parentCompS).build().getIds());
            if (CollectionUtils.isNotEmpty(compsByIds)) {
                filterComps.addAll(compsByIds);
            }
        }
        Set<CompPO> builderComps = new HashSet<>();
        for (CompPO compPO : filterComps) {
            buildParentComps(compPO, builderComps);
        }
        return SearchTreeUtil.builderTreeMode(CompBO.buildSetToSearchTree(builderComps), deptTrees);
    }


    /**
     * 是否有搜索查询
     *
     * @param jobPO
     * @return
     */
    private boolean isFilter(JobPO jobPO) {
        return !(StringUtil.isEmpty(jobPO.getJobNo())
                && StringUtil.isEmpty(jobPO.getJobName())
                && StringUtil.isEmpty(jobPO.getWorkplace())
                && StringUtil.isEmpty(jobPO.getDescription())
                && StringUtil.isEmpty(jobPO.getWorkDuty())
                && StringUtil.isEmpty(jobPO.getWorkAuthority())
                && null == jobPO.getParentComp()
                && null == jobPO.getParentDept()
                && null == jobPO.getSequenceId()
                && null == jobPO.getSchemeId()
                && null == jobPO.getIsKey()
                && null == jobPO.getForbiddenTag()
                && null == jobPO.getEcCompany()
                && null == jobPO.getEcDepartment()
        );
    }

    /**
     * 判断编号是否重复
     *
     * @return
     */
    public static String repeatDetermine(String jobNo) {
        CodeRulePO codeRuleByType = MapperProxyFactory.getProxy(CodeRuleMapper.class).getCodeRuleByType(RuleCodeType.JOBTITLES.getValue());
        if (StringUtils.isNotBlank(jobNo)) {
            jobNo = CodeRuleUtil.generateCode(RuleCodeType.JOBTITLES, jobNo);
            List<JobPO> list = getJobMapper().listByNo(Util.null2String(jobNo));
            OrganizationAssert.isEmpty(list, "编号不允许重复");
        } else {
            if (null != codeRuleByType && "1".equals(codeRuleByType.getSerialEnable())) {
                jobNo = autoCreateCompanyNo();
            }
        }
        return jobNo;
    }

    /**
     * 自动编号处理
     *
     * @return
     */
    private static String autoCreateCompanyNo() {
        String generateCode = CodeRuleUtil.generateCode(RuleCodeType.JOBTITLES, "");
        List<JobPO> list = getJobMapper().listByNo(Util.null2String(generateCode));
        if (CollectionUtils.isNotEmpty(list)) {
            generateCode = autoCreateCompanyNo();
        }
        return generateCode;
    }

    /**
     * 获取所有子部门id
     *
     * @param parentComp
     * @param parentDept
     * @param jobList
     */
    void forbiddenChildTag(Long parentComp, Long parentDept, Long parentJob, List<JobPO> jobList) {
        if (CollectionUtils.isNotEmpty(jobList)) {
            for (JobPO job : jobList) {
                job.setParentComp(parentComp);
                job.setParentDept(parentDept);
                job.setParentJob(parentJob);
                job.setForbiddenTag(1);
                new OrganizationSyncEc(user, LogModuleNameEnum.JOB, OperateTypeEnum.CANCELED, null, job).sync();
                getJobMapper().updateBaseJob(job);
                // 更新组织架构图
                new Thread(new JobTriggerRunnable(job.getId())).start();
                List<JobPO> childJobs = getJobMapper().getJobsByPid(job.getId());
                forbiddenChildTag(parentComp, parentDept, job.getId(), childJobs);
            }
        }
    }

    /**
     * 添加子元素ID
     *
     * @param disableIds
     * @param jobPOS
     */
    private void addDisableIds(Set<Long> disableIds, List<JobPO> jobPOS) {
        for (JobPO jobPO : jobPOS) {
            disableIds.add(jobPO.getId());
            List<JobPO> jobsByPid = getJobMapper().getJobsByPid(jobPO.getId());
            addDisableIds(disableIds, jobsByPid);
        }
    }

    /**
     * 更新EC岗位
     * @param jobPO
     */
    private void updateEcJob(JobPO jobPO,String newName){
        Map<String, Object> params = new HashMap<>();
        params.put("job_name", newName);
        params.put("jobactivityid", JOB_ACTIVITY_ID);
        params.put("work_duty", jobPO.getWorkDuty());
        params.put("work_authority", jobPO.getWorkAuthority());
        params.put("description", jobPO.getDescription());
        params.put("job_no", jobPO.getJobNo());
        new OrganizationSyncEc(user, LogModuleNameEnum.JOB, OperateTypeEnum.UPDATE, params, jobPO).sync();
    }

}
