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.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.hrm.util.face.HrmFaceCheckManager;
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.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.extend.po.ExtendTitlePO;
import com.engine.organization.entity.hrmresource.bo.HrmRelationBO;
import com.engine.organization.entity.hrmresource.param.HrmRelationSaveParam;
import com.engine.organization.entity.hrmresource.param.HrmResourceSearchParam;
import com.engine.organization.entity.hrmresource.po.HrmRelationPO;
import com.engine.organization.entity.hrmresource.po.HrmResourcePO;
import com.engine.organization.entity.hrmresource.vo.HrmResourceVO;
import com.engine.organization.entity.job.bo.JobBO;
import com.engine.organization.entity.job.po.JobPO;
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.ExtendTitleMapper;
import com.engine.organization.mapper.hrmresource.HrmRelationMapper;
import com.engine.organization.mapper.hrmresource.HrmResourceMapper;
import com.engine.organization.mapper.hrmresource.SystemDataMapper;
import com.engine.organization.mapper.job.JobMapper;
import com.engine.organization.mapper.post.PostInfoMapper;
import com.engine.organization.mapper.post.PostMapper;
import com.engine.organization.mapper.resource.ResourceMapper;
import com.engine.organization.mapper.scheme.GradeMapper;
import com.engine.organization.mapper.scheme.LevelMapper;
import com.engine.organization.mapper.scheme.SchemeMapper;
import com.engine.organization.mapper.sequence.SequenceMapper;
import com.engine.organization.service.ExtService;
import com.engine.organization.service.HrmResourceService;
import com.engine.organization.thread.HrmResourceTriggerRunnable;
import com.engine.organization.thread.OrganizationSyncEc;
import com.engine.organization.util.HasRightUtil;
import com.engine.organization.util.MenuBtn;
import com.engine.organization.util.OrganizationAssert;
import com.engine.organization.util.OrganizationFormItemUtil;
import com.engine.organization.util.coderule.CodeRuleUtil;
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.page.PageUtil;
import com.engine.organization.util.tree.SearchTreeUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.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;
import java.util.stream.Stream;

/**
 * @author:dxfeng
 * @createTime: 2022/06/20
 * @version: 1.0
 */
public class HrmResourceServiceImpl extends Service implements HrmResourceService {
    /**
     * 左侧树 类型表示
     * <p>
     * 0：集团
     * 1：分部
     * 2：部门
     * 3：岗位
     */
    private static final String TYPE_COMP = "1";
    private static final String TYPE_DEPT = "2";
    private static final String TYPE_JOB = "3";

    private static final Long GROUP_ID = 4L;

    /**
     * 分组类型
     * 1：分部
     * 2：部门
     * 3：岗位
     * 4：人员
     */
    private static final String EXTEND_TYPE = "4";

    /**
     * 主表表名
     */
    private static final String JCL_ORG_HRM = "JCL_ORG_HRMRESOURCE";
    /**
     * 主表拓展表
     */
    private static final String JCL_ORG_HRMEXT = "JCL_ORG_HRMRESOURCEEXT";
    /**
     * 明细表拓展表
     */
    private static final String JCL_ORG_HRMEXT_DT1 = "JCL_ORG_HRMRESOURCEEXT_DT1";

    private static final String HRM_RESOURCE = "hrmresource";


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

    private SchemeMapper getSchemeMapper() {
        return MapperProxyFactory.getProxy(SchemeMapper.class);
    }

    private LevelMapper getLevelMapper() {
        return MapperProxyFactory.getProxy(LevelMapper.class);
    }

    private GradeMapper getGradeMapper() {
        return MapperProxyFactory.getProxy(GradeMapper.class);
    }

    private SequenceMapper getSequenceMapper() {
        return MapperProxyFactory.getProxy(SequenceMapper.class);
    }

    private PostMapper getPostMapper() {
        return MapperProxyFactory.getProxy(PostMapper.class);
    }

    private PostInfoMapper getPostInfoMapper() {
        return MapperProxyFactory.getProxy(PostInfoMapper.class);
    }

    private HrmRelationMapper getHrmRelationMapper() {
        return MapperProxyFactory.getProxy(HrmRelationMapper.class);
    }

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

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

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

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

    private static ResourceMapper getResourceMapper() {
        return MapperProxyFactory.getProxy(ResourceMapper.class);
    }

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

    private SystemDataMapper getSystemDataMapper() {
        return MapperProxyFactory.getProxy(SystemDataMapper.class);
    }

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


    @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(HrmResourceSearchParam params) {
        OrganizationWeaTable<HrmResourceVO> table = new OrganizationWeaTable<>(user, HrmResourceVO.class);
        String sqlWhere = buildSqlWhere(params);
        table.setSqlwhere(sqlWhere);
        WeaResultMsg result = new WeaResultMsg(false);
        result.putAll(table.makeDataResult());
        result.success();
        return new HashMap<>(result.getResultMap());
    }

    @Override
    public Map<String, Object> getSaveForm() {
        Map<String, Object> apiDatas = new HashMap<>();
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<ExtendTitlePO> extendTitles = getExtendTitleMapper().getTitlesByGroupID(GROUP_ID, "1");
        if (CollectionUtils.isNotEmpty(extendTitles)) {
            for (ExtendTitlePO extendTitle : extendTitles) {
                List<SearchConditionItem> items = getExtService(user).getExtSaveForm(user, EXTEND_TYPE + "", JCL_ORG_HRM, 2, extendTitle.getId().toString(), null, null, null);
                if (CollectionUtils.isNotEmpty(items)) {
                    addGroups.add(new SearchConditionGroup(extendTitle.getTitle(), true, items));
                }
            }
        }
        apiDatas.put("condition", addGroups);
        return apiDatas;
    }

    @Override
    public Long saveBaseForm(Map<String, Object> params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        String workCode = (String) params.get("work_code");
        // 判断是否开启自动编号
        workCode = repeatDetermine(workCode);
        params.put("work_code", workCode);
        // 完善新增参数
        completeParams(params);

        // 新增EC人员,新增成功后，新增到聚才林人员表
        Map<String, Object> syncMap = new OrganizationSyncEc(user, LogModuleNameEnum.RESOURCE, OperateTypeEnum.ADD, params).sync();
        String ecResourceId = Util.null2String(syncMap.get("id"));
        OrganizationAssert.isTrue(StringUtils.isNotBlank(ecResourceId), Util.null2String(syncMap.get("message")));
        // 获取人员UUID
        RecordInfo recordInfo = getSystemDataMapper().getHrmObjectByID(HRM_RESOURCE, ecResourceId);
        params.put("uuid", recordInfo.getUuid());
        Long resourceId = getExtService(user).updateExtForm(user, EXTEND_TYPE, JCL_ORG_HRM, params, "", null);
        new HrmResourceTriggerRunnable(resourceId).run();
        return resourceId;
    }

    @Override
    public Map<String, Object> getBaseForm(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_HRM : JCL_ORG_HRMEXT, viewAttr, id, extendTitle.getId() + "", "");
                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_HRMEXT));
        // 处理明细表
        resultMap.put("tables", getExtService(user).getExtendTables(user, EXTEND_TYPE, Long.parseLong(groupId), JCL_ORG_HRMEXT_DT1, id, viewAttr, false));
        Map<String, Object> apiDatas = new HashMap<>();

        apiDatas.put("result", resultMap);

        return apiDatas;
    }

    @Override
    public int updateForm(Map<String, Object> params) {
        Long id = Long.parseLong((String) params.get("id"));
        String groupId = (String) params.get("viewCondition");
        if ("0".equals(groupId)) {
            groupId = GROUP_ID.toString();
        }
        // 判断编号是否重复
        String workCode = Util.null2String(params.get("work_code"));
        HrmResourcePO resourceById = getResourceMapper().getResourceById(id.toString());
        if (!workCode.equals(resourceById.getWorkCode())) {
            workCode = repeatDetermine(workCode);
            params.put("work_code", workCode);
        }

        // 完善更新参数
        completeParams(params);

        // 更新EC人员,更新成功后，更新聚才林人员表
        Map<String, Object> syncMap = new OrganizationSyncEc(user, LogModuleNameEnum.RESOURCE, OperateTypeEnum.UPDATE, params).sync();
        String ecResourceId = Util.null2String(syncMap.get("id"));
        OrganizationAssert.isTrue(StringUtils.isNotBlank(ecResourceId), Util.null2String(syncMap.get("message")));

        int updateCount = 0;
        // 更新主表数据
        updateCount += getExtService(user).updateExtForm(user, EXTEND_TYPE, JCL_ORG_HRM, params, "", id);
        // 更新主表拓展表
        getExtService(user).updateExtForm(user, EXTEND_TYPE, JCL_ORG_HRMEXT, params, groupId, id);
        //更新明细表
        getExtService(user).updateExtDT(user, EXTEND_TYPE, JCL_ORG_HRMEXT_DT1, params, id);

        new HrmResourceTriggerRunnable(id).run();
        return updateCount;
    }

    @Override
    public Map<String, Object> getSearchCondition(Map<String, Object> params) {
        Map<String, Object> apiDatas = new HashMap<>();
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<SearchConditionItem> conditionItems = new ArrayList<>();
        SearchConditionItem lastNameItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "姓名", "lastName");
        SearchConditionItem jobTitleItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "岗位", "666", "jobTitle", "");
        BrowserBean browserBean = jobTitleItem.getBrowserConditionParam();
        String s = JSONObject.toJSONString(browserBean);
        CustomBrowserBean customBrowserBean = JSONObject.parseObject(s, CustomBrowserBean.class);
        customBrowserBean.setHasLeftTree(true);
        customBrowserBean.setLeftToSearchKey("treeKey");
        jobTitleItem.setBrowserConditionParam(customBrowserBean);
        SearchConditionItem companyIdItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "分部", "164", "ecCompany", "");
        SearchConditionItem departmentIdItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "部门", "4", "ecDepartment", "");
        SearchConditionItem telephoneItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "办公电话", "telephone");
        SearchConditionItem mobileItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "移动电话", "mobile");

        conditionItems.add(lastNameItem);
        conditionItems.add(jobTitleItem);
        conditionItems.add(companyIdItem);
        conditionItems.add(departmentIdItem);
        conditionItems.add(telephoneItem);
        conditionItems.add(mobileItem);

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

    @Override
    public Map<String, Object> getHasRight() {
        Map<String, Object> btnDatas = new HashMap<>();
        if (HasRightUtil.hasRight(user, RIGHT_NAME, true)) {
            ArrayList<MenuBtn> topMenuList = new ArrayList<>();
            ArrayList<MenuBtn> rightMenuList = new ArrayList<>();
            topMenuList.add(MenuBtn.builder().isBatch("1").isTop("1").menuFun("new").menuIcon("icon-coms-New-Flow").menuName("新建人员").type("BTN_Addnew").build());
            btnDatas.put("topMenu", topMenuList);
            rightMenuList.add(MenuBtn.builder().isBatch("1").isTop("1").menuFun("new").menuIcon("icon-coms-New-Flow").menuName("新建人员").type("BTN_Addnew").build());
            rightMenuList.add(MenuBtn.builder().isBatch("0").isTop("0").menuFun("custom").menuIcon("icon-coms-task-list").menuName("显示列定制").type("BTN_COLUMN").build());
            rightMenuList.add(MenuBtn.rightMenu_btnLog());
            btnDatas.put("rightMenu", rightMenuList);
        }
        btnDatas.put("hasRight", true);
        return btnDatas;
    }

    @Override
    public Map<String, Object> getTabForm(Map<String, Object> params) {
        String viewAttrStr = (String) params.get("viewAttr");
        OrganizationAssert.notBlank(viewAttrStr, "未指定操作类型，请确认");
        String id = Util.null2String(params.get("id"));
        OrganizationAssert.notBlank(id, "数据有误，请确认");
        int viewAttr = Integer.parseInt(viewAttrStr);
        Map<String, Object> apiDatas = new HashMap<>();

        List<SearchConditionGroup> addGroups = new ArrayList<>();
        SearchConditionItem schemeId = OrganizationFormItemUtil.browserItem(user, 2, 17, viewAttr, false, "等级方案", "161", "schemeId", "schemeBrowser");
        schemeId.setRules("required");
        SearchConditionItem gradeId = OrganizationFormItemUtil.browserItem(user, 2, 17, viewAttr, false, "职级", "161", "gradeId", "gradeBrowser");
        gradeId.setRules("required");
        SearchConditionItem levelId = OrganizationFormItemUtil.browserItem(user, 2, 17, viewAttr, false, "职等", "162", "levelId", "levelBrowser");
        levelId.setRules("required");
        SearchConditionItem sequenceId = OrganizationFormItemUtil.browserItem(user, 2, 17, viewAttr, false, "岗位序列", "161", "sequenceId", "sequenceBrowser");
        sequenceId.setRules("required");
        SearchConditionItem postId = OrganizationFormItemUtil.browserItem(user, 2, 17, viewAttr, false, "职务分类", "161", "postId", "postBrowser");
        postId.setRules("required");
        SearchConditionItem postInfoId = OrganizationFormItemUtil.browserItem(user, 2, 17, viewAttr, false, "职务信息", "161", "postInfoId", "postInfoBrowser");
        postInfoId.setRules("required");
        SearchConditionItem companyId = OrganizationFormItemUtil.browserItem(user, 2, 17, viewAttr, false, "分部", "164", "companyId", "");
        companyId.setRules("required");
        SearchConditionItem departmentId = OrganizationFormItemUtil.browserItem(user, 2, 17, viewAttr, false, "部门", "4", "departmentId", "");
        departmentId.setRules("required");
        SearchConditionItem jobId = OrganizationFormItemUtil.browserItem(user, 2, 17, viewAttr, false, "岗位", "161", "jobId", "jobBrowser");
        jobId.setRules("required");


        // 编辑状态下赋值操作
        HrmRelationPO relationPO = getHrmRelationMapper().getRelationById(Long.parseLong(id));
        if (null != relationPO) {
            setBrowserValue(schemeId, relationPO.getSchemeId(), getSchemeMapper().listSchemesByIds(Stream.of(relationPO.getSchemeId()).collect(Collectors.toList())), null, null);
            setBrowserValue(gradeId, relationPO.getGradeId(), getGradeMapper().listGradessByIds(Stream.of(relationPO.getGradeId()).collect(Collectors.toList())), "scheme_id", relationPO.getSchemeId());
            setBrowserValue(levelId, relationPO.getLevelId(), getLevelMapper().listLevelsByIds(DeleteParam.builder().ids(relationPO.getLevelId()).build().getIds()), "grade_id", relationPO.getGradeId());
            setBrowserValue(sequenceId, relationPO.getSequenceId(), getSequenceMapper().listSequencesByIds(Stream.of(relationPO.getSequenceId()).collect(Collectors.toList())), "scheme_id", relationPO.getSchemeId());
            setBrowserValue(postId, relationPO.getPostId(), getPostMapper().listPostsByIds(Stream.of(relationPO.getPostId()).collect(Collectors.toList())), null, null);
            setBrowserValue(postInfoId, relationPO.getPostInfoId(), getPostInfoMapper().listPostInfosByIds(Stream.of(relationPO.getPostInfoId()).collect(Collectors.toList())), "post_id", relationPO.getPostId());

            List<Map<String, Object>> companyMaps = new ArrayList<>();
            String scCompanyNameById = MapperProxyFactory.getProxy(SystemDataMapper.class).getScCompanyNameById(relationPO.getCompanyId().toString());
            Map<String, Object> companyMap = new HashMap<>();
            companyMap.put(relationPO.getCompanyId().toString(), scCompanyNameById);
            companyMaps.add(companyMap);
            setBrowserValue(companyId, relationPO.getCompanyId(), companyMaps, null, null);

            List<Map<String, Object>> departmentMaps = new ArrayList<>();
            String departmentNameById = MapperProxyFactory.getProxy(SystemDataMapper.class).getScDepartmentNameById(relationPO.getDepartmentId().toString());
            Map<String, Object> departmentMap = new HashMap<>();
            departmentMap.put(relationPO.getDepartmentId().toString(), departmentNameById);
            departmentMaps.add(departmentMap);
            setBrowserValue(departmentId, relationPO.getDepartmentId(), departmentMaps, "subcompany1", relationPO.getCompanyId());

            setBrowserValue(jobId, relationPO.getJobId(), getJobMapper().listJobsByIds(Stream.of(relationPO.getJobId()).collect(Collectors.toList())), "departmentid", relationPO.getDepartmentId());
        }

        addGroups.add(new SearchConditionGroup("岗职位体系", true, Stream.of(schemeId, gradeId, levelId, sequenceId, postId, postInfoId).collect(Collectors.toList())));
        addGroups.add(new SearchConditionGroup("组织机构", true, Stream.of(companyId, departmentId, jobId).collect(Collectors.toList())));
        HashMap<String, Object> buttonsMap = new HashMap<>();
        buttonsMap.put("hasEdit", true);
        buttonsMap.put("hasSave", true);
        apiDatas.put("buttons", buttonsMap);
        apiDatas.put("conditions", addGroups);
        return apiDatas;
    }

    @Override
    public long saveTabForm(HrmRelationSaveParam params) {
        HrmRelationPO hrmRelationPO = HrmRelationBO.convertSaveParamToPO(params);
        hrmRelationPO.setCreator((long) user.getUID());
        hrmRelationPO.setCreateTime(new Date());
        hrmRelationPO.setDeleteType(0);
        getHrmRelationMapper().insertIgnoreNull(hrmRelationPO);
        return hrmRelationPO.getId();
    }

    @Override
    public long updateTabForm(HrmRelationSaveParam params) {
        HrmRelationPO hrmRelationPO = HrmRelationBO.convertSaveParamToPO(params);
        // 判断新增OR更新
        HrmRelationPO relationPO = getHrmRelationMapper().getRelationById(params.getId());
        if (null == relationPO) {
            hrmRelationPO.setCreator((long) user.getUID());
            hrmRelationPO.setCreateTime(new Date());
            hrmRelationPO.setDeleteType(0);
            getHrmRelationMapper().insertIgnoreNull(hrmRelationPO);
        } else {
            hrmRelationPO.setUpdateTime(new Date());
            getHrmRelationMapper().updateHrmRelation(hrmRelationPO);
        }
        RecordSet rs = new RecordSet();
        rs.execute("update HrmResource set subcompanyid1 = " + params.getCompanyId() + " ,departmentid = " + params.getDepartmentId() + " ,jobtitle = " + params.getJobId() + " where id = " + params.getId());
        HrmFaceCheckManager.sync(params.getId().toString(), HrmFaceCheckManager.getOptUpdate(), "hrm_e9_HrmResourceBaseService_editResourceBase", HrmFaceCheckManager.getOaResource());
        return hrmRelationPO.getId();
    }

    /**
     * 浏览按钮赋值
     *
     * @param browserItem
     * @param browserValue
     * @param maps
     */
    private void setBrowserValue(SearchConditionItem browserItem, Object browserValue, List<Map<String, Object>> maps, String relateField, Object relatedValue) {
        browserItem.setValue(browserValue);
        BrowserBean browserBean = browserItem.getBrowserConditionParam();
        browserBean.setReplaceDatas(maps);
        browserItem.setBrowserConditionParam(browserBean);

        if (StringUtils.isNotBlank(relateField) && 1 != browserItem.getViewAttr()) {
            long l = System.currentTimeMillis();
            Map<String, Object> completeParams = browserBean.getCompleteParams();
            completeParams.put("currenttime", l);
            completeParams.put(relateField + "_" + l, relatedValue);
            Map<String, Object> conditionDataParams = browserBean.getConditionDataParams();
            conditionDataParams.put("currenttime", l);
            conditionDataParams.put(relateField + "_" + l, relatedValue);
            Map<String, Object> dataParams = browserBean.getDataParams();
            dataParams.put("currenttime", l);
            dataParams.put(relateField + "_" + l, relatedValue);
            Map<String, Object> destDataParams = browserBean.getDestDataParams();
            destDataParams.put("currenttime", l);
            destDataParams.put(relateField + "_" + l, relatedValue);
        }
    }

    /**
     * 查询条件
     *
     * @param params
     * @return
     */
    private String buildSqlWhere(HrmResourceSearchParam params) {
        DBType dbType = DBType.get(new RecordSet().getDBType());
        String sqlWhere = " where 1=1 ";
        String lastName = params.getLastName();
        if (StringUtils.isNotBlank(lastName)) {
            sqlWhere += " AND t.last_name " + dbType.like(lastName);
        }
        Long companyId = params.getCompanyId();
        if (null != companyId) {
            sqlWhere += " AND t.company_id = '" + companyId + "'";
        }
        Long departmentId = params.getDepartmentId();
        if (null != departmentId) {
            sqlWhere += " AND t.department_id = '" + departmentId + "'";
        }
        Long ecCompany = params.getEcCompany();
        if (null != ecCompany) {
            sqlWhere += " AND t.ec_company = '" + ecCompany + "'";
        }
        Long ecDepartment = params.getEcDepartment();
        if (null != ecDepartment) {
            sqlWhere += " AND t.ec_department = '" + ecDepartment + "'";
        }
        String telephone = params.getTelephone();
        if (StringUtils.isNotBlank(telephone)) {
            sqlWhere += " AND t.telephone " + dbType.like(telephone);
        }
        String mobile = params.getMobile();
        if (StringUtils.isNotBlank(mobile)) {
            sqlWhere += " AND t.mobile " + dbType.like(mobile);
        }
        Long jobTitle = params.getJobTitle();
        if (null != jobTitle) {
            sqlWhere += " AND t.job_title = '" + jobTitle + "'";
        }

        // 分权查询
        DetachUtil detachUtil = new DetachUtil(user.getUID());
        String parentCompanyIds = detachUtil.getJclRoleLevels();
        if (detachUtil.isDETACH()) {
            sqlWhere += " And t.company_id in(" + parentCompanyIds + ")";
        }

        return sqlWhere;
    }

    public 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).build();
            CompPO compBuild = CompPO.builder().compName(keyword).parentCompany(parentCompId).build();
            // 所属分部下的岗位
            JobPO jobBuild = JobPO.builder().jobName(keyword).parentComp(parentCompId).build();
            searchTree = buildTreeByCompAndDept(departmentBuild, compBuild, jobBuild);
        } else if (TYPE_DEPT.equals(type)) {
            Long parentDeptId = Long.parseLong(id);
            DepartmentPO departmentBuild = DepartmentPO.builder().deptName(keyword).parentDept(parentDeptId).build();
            // 所属分部下的岗位
            JobPO jobBuild = JobPO.builder().jobName(keyword).parentDept(parentDeptId).build();
            searchTree = buildTreeByDeptAndJob(departmentBuild, jobBuild);

        } else if (TYPE_JOB.equals(type)) {
            // 查询部门信息
            List<JobPO> filterDeparts = getJobMapper().listPOsByFilter(JobPO.builder().jobName(keyword).parentJob(Long.parseLong(id)).build());
            Set<JobPO> builderJobs = new HashSet<>();
            for (JobPO departmentPO : filterDeparts) {
                buildParentJobs(departmentPO, builderJobs);
            }
            searchTree = SearchTreeUtil.builderTreeMode(JobBO.buildSetToSearchTree(builderJobs));
        }
        return searchTree;
    }

    /**
     * 分部、部门 组装左侧树
     *
     * @param departmentBuild
     * @param compBuild
     * @param jobBuild
     * @return
     */
    private List<SearchTree> buildTreeByCompAndDept(DepartmentPO departmentBuild, CompPO compBuild, JobPO jobBuild) {
        List<JobPO> jobPOS = getJobMapper().listPOsByFilter(jobBuild);
        new DetachUtil(user.getUID()).filterJobList(jobPOS);
        List<DepartmentPO> filterDeparts = getDepartmentMapper().listByFilter(departmentBuild, "show_order");
        new DetachUtil(user.getUID()).filterDepartmentList(filterDeparts);
        // 添加父级岗位
        Set<JobPO> builderJobs = new HashSet<>();
        for (JobPO jobPO : jobPOS) {
            buildParentJobs(jobPO, builderJobs);
        }
        // 添加岗位的上级部门或分部
        List<SearchTree> jobTrees = SearchTreeUtil.builderTreeMode(JobBO.buildSetToSearchTree(builderJobs));
        String parentDeptS = jobTrees.stream().map(SearchTree::getParentComp).collect(Collectors.joining(","));
        if (!StringUtil.isEmpty(parentDeptS)) {
            // 兼容SQLServer每次最多in,2100条数据
            List<Long> ids = (List<Long>) DeleteParam.builder().ids(parentDeptS).build().getIds();
            int ceilCount = (int) Math.ceil((double) ids.size() / 1000);
            List<DepartmentPO> departmentsByIds = new ArrayList<>();
            for (int i = 1; i < ceilCount + 1; i++) {
                List<Long> longs = PageUtil.subList(i, 1000, ids);
                List<DepartmentPO> departmentsById = getDepartmentMapper().getDeptsByIds(longs);
                if (CollectionUtils.isNotEmpty(departmentsById)) {
                    departmentsByIds.addAll(departmentsById);
                }
            }


            if (CollectionUtils.isNotEmpty(departmentsByIds)) {
                filterDeparts.addAll(departmentsByIds);
            }
        }

        // 查询分部信息
        List<CompPO> filterComps = getCompMapper().listByFilter(compBuild, "show_order");
        new DetachUtil(user.getUID()).filterCompanyList(filterComps);
        Set<DepartmentPO> builderDeparts = new HashSet<>();
        for (DepartmentPO departmentPO : filterDeparts) {
            buildParentDepts(departmentPO, builderDeparts);
        }
        List<SearchTree> departmentList = DepartmentBO.buildSetToSearchTree(builderDeparts);
        List<SearchTree> deptTrees = SearchTreeUtil.builderTreeMode(departmentList);
        List<SearchTree> searchTrees = SearchTreeUtil.builderTreeMode(departmentList, jobTrees);
        // 添加部门的上级分部
        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().list("show_order");
        new DetachUtil(user.getUID()).filterCompanyList(allCompanys);
        Map<Long, 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), searchTrees);
    }

    private List<SearchTree> buildTreeByDeptAndJob(DepartmentPO departmentBuild, JobPO jobBuild) {
        List<JobPO> jobPOS = getJobMapper().listPOsByFilter(jobBuild);
        List<DepartmentPO> filterDeparts = getDepartmentMapper().listByFilter(departmentBuild, "show_order");
        // 添加父级岗位
        Set<JobPO> builderJobs = new HashSet<>();
        for (JobPO jobPO : jobPOS) {
            buildParentJobs(jobPO, builderJobs);
        }
        // 添加岗位的上级部门或分部
        List<SearchTree> jobTrees = SearchTreeUtil.builderTreeMode(JobBO.buildSetToSearchTree(builderJobs));
        String parentDeptS = jobTrees.stream().map(SearchTree::getParentComp).collect(Collectors.joining(","));
        if (!StringUtil.isEmpty(parentDeptS)) {
            // 兼容SQLServer每次最多in,2100条数据
            List<Long> ids = (List<Long>) DeleteParam.builder().ids(parentDeptS).build().getIds();
            int ceilCount = (int) Math.ceil((double) ids.size() / 1000);
            List<DepartmentPO> departmentsByIds = new ArrayList<>();
            for (int i = 0; i < ceilCount - 1; i++) {
                List<DepartmentPO> departmentsById = getDepartmentMapper().getDeptsByIds(PageUtil.subList(i, 1000, ids));
                if (CollectionUtils.isNotEmpty(departmentsById)) {
                    departmentsByIds.addAll(departmentsById);
                }
            }

            if (CollectionUtils.isNotEmpty(departmentsByIds)) {
                filterDeparts.addAll(departmentsByIds);
            }
        }

        // 查询分部信息
        Set<DepartmentPO> builderDeparts = new HashSet<>();
        for (DepartmentPO departmentPO : filterDeparts) {
            buildParentDepts(departmentPO, builderDeparts);
        }
        return SearchTreeUtil.builderTreeMode(DepartmentBO.buildSetToSearchTree(builderDeparts), jobTrees);
    }

    private void buildParentJobs(JobPO jobPO, Set<JobPO> builderJobs) {
        builderJobs.add(jobPO);
        if (SearchTreeUtil.isTop(jobPO.getParentJob())) {
            return;
        }
        JobPO parentJob = getJobMapper().getJobById(jobPO.getParentJob());
        if (null != parentJob) {
            buildParentJobs(parentJob, builderJobs);
        }
    }

    /**
     * 添加查询元素的父级元素
     *
     * @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) {
            buildParentDepts(parentDept, builderDeparts);
        }
    }

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

    private void completeParams(Map<String, Object> params) {
        String jobId = Util.null2String(params.get("job_title"));
        if (StringUtils.isNotBlank(jobId)) {
            JobPO jobById = getJobMapper().getJobById(Long.parseLong(jobId));
            params.put("department_id", jobById.getParentDept());
            params.put("company_id", jobById.getParentComp());
            params.put("ec_department", jobById.getEcDepartment());
            params.put("ec_company", jobById.getEcCompany());
            // 等级方案、岗位序列、职等、职级
            params.put("scheme_id", jobById.getSchemeId());
            params.put("sequence_id", jobById.getSequenceId());
            params.put("job_level", jobById.getLevelId());
            params.put("job_grade", jobById.getGradeId());
            String showOrder = Util.null2String(params.get("show_order"));
            // 初始化排序字段
            if (StringUtils.isBlank(showOrder)) {
                Long orderNum = getHrmResourceMapper().getMaxShowOrder();
                params.put("show_order", null == orderNum ? 1 : orderNum + 1);
            }

            // 人员状态
            String status = Util.null2String(params.get("status"));
            if (StringUtils.isBlank(status)) {
                params.put("status", "0");
            }
        }
    }

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

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