package com.engine.organization.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.api.browser.bean.BrowserBean;
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.browser.po.CustomBrowserBean;
import com.engine.organization.entity.codesetting.po.CodeRulePO;
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.hrmresource.po.ResourcePO;
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.DeleteTypeEnum;
import com.engine.organization.exception.OrganizationRunTimeException;
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.job.JobMapper;
import com.engine.organization.mapper.resource.HrmResourceMapper;
import com.engine.organization.mapper.scheme.GradeMapper;
import com.engine.organization.service.ExtService;
import com.engine.organization.service.JobService;
import com.engine.organization.util.*;
import com.engine.organization.util.coderule.CodeRuleUtil;
import com.engine.organization.util.db.MapperProxyFactory;
import com.engine.organization.util.detach.DetachUtil;
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.tree.SearchTreeUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
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";

    /**
     * 岗位主表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);
    }

    private HrmResourceMapper getHrmResourceMapper() {
        return MapperProxyFactory.getProxy(HrmResourceMapper.class);
    }


    @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(), " show_order ");
        List<JobListDTO> allList = getJobMapper().listNoFilter(orderSql);
        new DetachUtil(user).filterJobDTOList(allList);
        // 通过子级遍历父级元素
        if (filter) {
            // 根据条件获取元素
            List<JobListDTO> filterJobPOs = getJobMapper().listByFilter(jobPO, orderSql);
            new DetachUtil(user).filterJobDTOList(allList);
            // 添加父级元素
            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() {
        Map<String, List<MenuBtn>> btnDatas = new HashMap<>();
        ArrayList<MenuBtn> topMenuList = new ArrayList<>();
        ArrayList<MenuBtn> rightMenuList = new ArrayList<>();
        // 批量删除
        topMenuList.add(MenuBtn.topMenu_batchDelete());
        topMenuList.add(MenuBtn.builder().isBatch("0").isTop("1").menuFun("refresh").menuIcon("icon-coms-Refresh").menuName("刷新").type("BTN_REFRESH").build());
        btnDatas.put("topMenu", topMenuList);
        // 日志
        rightMenuList.add(MenuBtn.rightMenu_btnLog());
        rightMenuList.add(MenuBtn.builder().isBatch("0").isTop("0").menuFun("refresh").menuIcon("icon-coms-Refresh").menuName("刷新").type("BTN_REFRESH").build());
        btnDatas.put("rightMenu", rightMenuList);
        return btnDatas;
    }

    @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 jobTitleNameItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "名称", "jobTitleName");
        // 所属分部
        SearchConditionItem parentCompBrowserItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "所属分部", "164", "subcompanyid1", "");
        // 所属部门
        SearchConditionItem parentDeptBrowserItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "所属部门", "4", "departmentid", "");
        // 是否关键岗
        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, "是否关键岗", "isKey");
        // 工作地点
        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(jobTitleNameItem);
        conditionItems.add(parentCompBrowserItem);
        conditionItems.add(parentDeptBrowserItem);
        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", compPO.getId());
                }
            }
            // 部门
            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", deptById.getId());
                    params.put("parent_comp", deptById.getSubCompanyId1());
                    params.put("ec_company", deptById.getSubCompanyId1());
                }
            }
            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(), "ec_jobTitle", "ec_department", "ec_company");
                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);
        JobSearchParam searchParam = JSONObject.parseObject(JSONObject.toJSONString(params), JobSearchParam.class);
        String jobNo = (String) params.get("job_no");
        // 判断是否开启自动编号
        jobNo = repeatDetermine(jobNo);
        params.put("job_no", jobNo);
        params.put("is_key", null == searchParam.getIsKey() ? 0 : searchParam.getIsKey());
        if (null != searchParam.getParentJob()) {
            JobPO parentJob = getJobMapper().getJobById(searchParam.getParentJob());
            params.put("ec_company", parentJob.getEcCompany());
            params.put("ec_department", parentJob.getEcDepartment());
        } else {
            Integer ecDepartment = searchParam.getEcDepartment();
            DepartmentPO jclDepartment = getDepartmentMapper().getDeptById(ecDepartment);
            params.put("ec_company", jclDepartment.getId());
            params.put("ec_department", jclDepartment.getSubCompanyId1());
        }

        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());
        // 上级岗位不能选择本身
        String parent_job = Util.null2String(params.get("parent_job"));
        if (StringUtils.isNotBlank(parent_job)) {
            OrganizationAssert.isFalse(parent_job.equals(searchParam.getId().toString()), "上级岗位不能选择本身");
        }
        if ("0".equals(groupId) || GROUP_ID.toString().equals(groupId)) {
            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());
            if (null != searchParam.getParentJob()) {
                JobPO parentJob = getJobMapper().getJobById(searchParam.getParentJob());
                params.put("ec_company", parentJob.getEcCompany());
                params.put("ec_department", parentJob.getEcDepartment());
            } else {
                Integer ecDepartment = searchParam.getEcDepartment();
                DepartmentPO jclDepartment = getDepartmentMapper().getDeptById(ecDepartment);
                params.put("ec_department", jclDepartment.getId());
                params.put("ec_company", jclDepartment.getSubCompanyId1());
            }
            //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());

            JobPO jobById = getJobMapper().getJobById(searchParam.getId());
            //TODO new JobTriggerRunnable(oldJobPO, jobById).run();
            // 更新人员关联字段
            // updateResourceJob(jobById);
        }
        // 更新主表拓展表
        getExtService(user).updateExtForm(user, EXTEND_TYPE, JCL_ORG_JOBEXT, params, "", 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(Integer.parseInt(department));
            DepartmentPO jclDepartmentId = getDepartmentMapper().getDeptById(jobById.getEcDepartment());
            if (null != jclDepartmentId) {
                //分部赋值
                jobById.setEcCompany(jclDepartmentId.getSubCompanyId1());
            }
            // 清空上级岗位
            jobById.setParentJob(null);
            jobById.setShowOrder(orderNum);
            insertCount += getJobMapper().insertIgnoreNull(jobById);
            // 更新组织架构图
            //TODO new JobTriggerRunnable(jobById.getId()).run();
        }

        return insertCount;
    }

    @Override
    public int updateForbiddenTagById(JobSearchParam params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        JobPO jobById = getJobMapper().getJobById(params.getId());
        JobPO jobPO = JobPO.builder().id(params.getId()).forbiddenTag(params.getForbiddenTag() ? 0 : 1).build();
        if (params.getForbiddenTag()) {
            // 启用：判断上级部门是否启用，上级部门启用，岗位才可启用
            DepartmentPO parentDepartment = getDepartmentMapper().getDeptById(jobById.getEcDepartment());
            OrganizationAssert.isTrue(0 == parentDepartment.getCanceled(), "该岗位不能解封，请先解封上级部门");

            // 启用：判断上级岗位是否启用，上级岗位启用，岗位才可启用
            if (null != jobById.getParentJob()) {
                JobPO parentJob = getJobMapper().getJobById(jobById.getParentJob());
                OrganizationAssert.isTrue(0 == parentJob.getForbiddenTag(), "该岗位不能解封，请先解封上级岗位");
            }
        } else {
            //禁用：判断当前岗位下是否有人员，如有人员则不能禁用
            // int hasResource = getJobMapper().isHasResource(params.getId());
            // OrganizationAssert.isTrue(hasResource == 0, "该岗位存在人员，不能封存");
            throw new OrganizationRunTimeException("该岗位不能封存");
        }
        //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) {
            // 判断是否可以删除
            List<String> allowDelete = getJobMapper().isAllowDelete(jobsById.getId());
            OrganizationAssert.isTrue(CollectionUtils.isEmpty(allowDelete), "该岗位存在引用，不允许删除");

            // 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(), null);
        }
        return getJobMapper().deleteByIds(ids);
    }

    @Override
    public Map<String, Object> getHrmListByJobId(Long jobId) {
        OrganizationWeaTable<EmployeeTableVO> table = new OrganizationWeaTable<>(user, EmployeeTableVO.class);
        String sqlWhere = " where 1=1 ";
        JobPO ecJobTitleByJobId = JobBO.getEcJobTitleByJobId(jobId);
        if (null != ecJobTitleByJobId) {
            sqlWhere += " AND t.subcompanyid1 = '" + ecJobTitleByJobId.getEcCompany() + "'";
            sqlWhere += " AND t.departmentid = '" + ecJobTitleByJobId.getEcDepartment() + "'";
            sqlWhere += " AND t.jobtitle = '" + ecJobTitleByJobId.getEcJobTitle() + "'";
        } else {
            sqlWhere = " where 1 = 2 ";
        }
        table.setSqlwhere(sqlWhere + " 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");
        BrowserBean browserBean = deptBrowserItem.getBrowserConditionParam();
        String s = JSONObject.toJSONString(browserBean);
        CustomBrowserBean customBrowserBean = JSONObject.parseObject(s, CustomBrowserBean.class);
        customBrowserBean.setHasLeftTree(true);
        customBrowserBean.setLeftToSearchKey("treeKey");
        deptBrowserItem.setBrowserConditionParam(customBrowserBean);
        SearchConditionItem mergeNameItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 3, 50, "合并后名称", "mergeName");
        mergeNameItem.setRules("required|string");
        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(), "请选择需要合并的岗位");
        OrganizationAssert.notBlank(mergeParam.getMergeName(), "请输入合并后的名称");

        // 不可选择岗位本身、以及子岗位
        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());

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

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

        // 人员信息变动，更新分部、部门、岗位
        // updateResourceJob(jobById, targetJob);

        // 更新合并后的岗位，更新组织架构图
        // updateEcJob(targetJob, mergeParam.getMergeName());

        // TODO targetJob.setJobName(mergeParam.getMergeName());
        getJobMapper().updateBaseJob(targetJob);
        //TODO new JobTriggerRunnable(jobById.getId(), targetJob.getId()).run();
        // 原岗位删除
        //new OrganizationSyncEc(user, LogModuleNameEnum.JOB, OperateTypeEnum.CANCELED, null, jobById).sync();
        getJobMapper().deleteByIds(Collections.singletonList(jobById.getId()));
        // 更新组织架构图
        //TODO new JobTriggerRunnable(jobById).run();
        return updateCount;
    }

    @Override
    public void refresh() {
        //1.人员表查询
        List<ResourcePO> resourcePOS = getHrmResourceMapper().selectFilterDatas();
        //2.数据过滤
        //3.数据插入
        resourcePOS.forEach(resourcePO -> {
            if (Objects.nonNull(resourcePO) && null != resourcePO.getJobtitle() && resourcePO.getJobtitle() > 0) {
                int count = getJobMapper().selectByConditions(resourcePO);
                if (count == 0) {
                    JobPO jobPO = JobPO.builder()
                            .ecCompany(resourcePO.getSubcompanyid1())
                            .ecDepartment(resourcePO.getDepartmentid())
                            .ecJobTitle(resourcePO.getJobtitle())
                            .isKey(0)
                            .deleteType(DeleteTypeEnum.NOT_DELETED.getValue())
                            .createTime(new Date())
                            .updateTime(new Date())
                            .build();
                    getJobMapper().insertIgnoreNull(jobPO);
                }
            }
        });

    }


    void recursionMergeJob(List<JobPO> jobs, Integer ecCompany, Integer ecDepartment, Long parentJob) {
        for (JobPO job : jobs) {
            job.setEcCompany(ecCompany);
            job.setEcDepartment(ecDepartment);
            job.setParentJob(parentJob);
            getJobMapper().updateBaseJob(job);
            // 更新人员信息
            // updateResourceJob(job);
            // 更新组织架构图
            //TODO new JobTriggerRunnable(job.getId()).run();

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

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

    /**
     * 添加查询元素的父级元素
     *
     * @param compPO
     * @param builderComps
     */
    private void buildParentComps(CompPO compPO, Set<CompPO> builderComps, Map<Integer, CompPO> allMaps) {
        builderComps.add(compPO);
        CompPO parentComp = allMaps.get(compPO.getSupSubComId());
        if (null != parentComp && (null == parentComp.getCanceled() || 0 == parentComp.getCanceled())) {
            buildParentComps(parentComp, builderComps, allMaps);
        }
    }

    /**
     * 根据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)) {
            Integer parentCompId = StringUtil.isEmpty(id) ? null : Integer.parseInt(id);
            DepartmentPO departmentBuild = DepartmentPO.builder().departmentName(keyword).subCompanyId1(parentCompId).canceled(0).build();
            CompPO compBuild = CompPO.builder().subCompanyName(keyword).supSubComId(parentCompId).canceled(0).build();
            searchTree = buildTreeByCompAndDept(departmentBuild, compBuild);
        } else if (TYPE_DEPT.equals(type)) {
            //
            // 查询部门信息
            List<DepartmentPO> filterDeparts = getDepartmentMapper().listByFilter(DepartmentPO.builder().departmentName(keyword).canceled(0).supDepId(Integer.parseInt(id)).build(), "showorder");
            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, "showorder");
        new DetachUtil(user).filterDepartmentList(filterDeparts);
        // 查询分部信息
        List<CompPO> filterComps = getCompMapper().listByFilter(compBuild, "showorder");
        new DetachUtil(user).filterCompanyList(filterComps);
        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);
            }
        }
        List<CompPO> allCompanys = getCompMapper().listAll("showorder");
        new DetachUtil(user).filterCompanyList(allCompanys);
        Map<Integer, CompPO> allMaps = allCompanys.stream().collect(Collectors.toMap(CompPO::getId, item -> item, (k1, k2) -> k1));
        Set<CompPO> builderComps = new HashSet<>();
        for (CompPO compPO : filterComps) {
            buildParentComps(compPO, builderComps, allMaps);
        }
        return SearchTreeUtil.builderTreeMode(CompBO.buildSetToSearchTree(builderComps), deptTrees);
    }


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

    /**
     * 判断编号是否重复
     *
     * @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 {
            OrganizationAssert.isTrue(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 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();
    //}
}
