package com.engine.organization.service.impl;

import com.api.browser.bean.SearchConditionGroup;
import com.api.browser.bean.SearchConditionItem;
import com.api.browser.bean.SearchConditionOption;
import com.api.hrm.bean.HrmFieldBean;
import com.api.hrm.util.HrmFieldSearchConditionComInfo;
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.hrm.service.impl.OrganizationServiceImpl;
import com.engine.organization.component.OrganizationWeaTable;
import com.engine.organization.entity.TopTab;
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.dto.DepartmentListDTO;
import com.engine.organization.entity.department.param.*;
import com.engine.organization.entity.department.po.DepartmentPO;
import com.engine.organization.entity.department.vo.SingleDeptTreeVO;
import com.engine.organization.entity.job.bo.JobBO;
import com.engine.organization.entity.job.po.JobPO;
import com.engine.organization.entity.job.vo.SingleJobTreeVO;
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.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.job.JobMapper;
import com.engine.organization.service.DepartmentService;
import com.engine.organization.thread.OrganizationSyncEc;
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 com.google.common.collect.Lists;
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.HrmUserVarify;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.definedfield.HrmDeptFieldManagerE9;
import weaver.hrm.definedfield.HrmFieldComInfo;
import weaver.hrm.definedfield.HrmFieldGroupComInfo;
import weaver.hrm.moduledetach.ManageDetachComInfo;
import weaver.systeminfo.SystemEnv;
import weaver.systeminfo.systemright.CheckSubCompanyRight;

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

/**
 * @Author weaver_cl
 * @description:
 * @Date 2022/5/20
 * @Version V1.0
 **/
public class DepartmentServiceImpl extends Service implements DepartmentService {

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

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

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

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


    @Override
    public PageInfo<SingleDeptTreeVO> getDeptListByPid(QuerySingleDeptListParam param) {
        //1.查询分部下所有部门
        List<DepartmentPO> departmentPOS = MapperProxyFactory.getProxy(DepartmentMapper.class).listAll("showOrder");
        PageInfo<DepartmentPO> pageInfo = new PageInfo<>(departmentPOS);
        List<SingleDeptTreeVO> singleDeptTreeVOS = DepartmentBO.buildSingleDeptTreeVOS(departmentPOS, param.getParentComp());
        PageInfo<SingleDeptTreeVO> pageInfos = new PageInfo<>(singleDeptTreeVOS, SingleDeptTreeVO.class);
        pageInfos.setTotal(pageInfo.getTotal());
        pageInfos.setPageNum(param.getCurrent());
        pageInfos.setPageSize(param.getPageSize());

        return pageInfos;
    }

    @Override
    public PageInfo<SingleJobTreeVO> getJobListByPid(QuerySingleDeptListParam param) {
        List<JobPO> jobPOS = MapperProxyFactory.getProxy(JobMapper.class).listAll();
        PageInfo<JobPO> pageInfo = new PageInfo<>(jobPOS);
        List<SingleJobTreeVO> singleDeptTreeVOS = JobBO.buildSingleJobTreeVOS(jobPOS, param.getParentDept());
        PageInfo<SingleJobTreeVO> pageInfos = new PageInfo<>(singleDeptTreeVOS, SingleJobTreeVO.class);
        pageInfos.setTotal(pageInfo.getTotal());
        pageInfos.setPageNum(param.getCurrent());
        pageInfos.setPageSize(param.getPageSize());
        return pageInfos;
    }


    @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, keyword);
        return SearchTreeUtil.getSearchTree(type, treeList);
    }

    @Override
    public Map<String, Object> listPage(DeptSearchParam param) {
        Map<String, Object> datas = new HashMap<>();
        boolean hasRight = HasRightUtil.hasRight(user, RIGHT_NAME, true);
        datas.put("hasRight", hasRight);
        if (!hasRight) {
            return datas;
        }
        DepartmentPO departmentPO = DepartmentBO.convertParamsToPO(param, user.getUID());
        boolean filter = isFilter(departmentPO);
        PageInfo<DepartmentListDTO> pageInfos;
        String orderSql = PageInfoSortUtil.getSortSql(param.getSortParams(), " showorder ");
        List<DepartmentPO> allList = getDepartmentMapper().listAll(orderSql);
        new DetachUtil(user).filterDepartmentList(allList);
        // 通过子级遍历父级元素
        if (filter) {
            // 根据条件获取元素
            List<DepartmentPO> filterDeptPOs = getDepartmentMapper().listByFilter(departmentPO, orderSql);
            new DetachUtil(user).filterDepartmentList(filterDeptPOs);
            // 添加父级元素
            List<DepartmentListDTO> compListDTOS = DepartmentBO.buildDeptDTOList(allList, filterDeptPOs);
            List<DepartmentListDTO> subList = PageUtil.subList(param.getCurrent(), param.getPageSize(), compListDTOS);
            pageInfos = new PageInfo<>(subList, DepartmentListDTO.class);
            pageInfos.setTotal(compListDTOS.size());
        } else {
            // 组合list
            List<DepartmentListDTO> compListDTOS = DepartmentBO.buildDeptDTOList(allList);
            List<DepartmentListDTO> subList = PageUtil.subList(param.getCurrent(), param.getPageSize(), compListDTOS);
            pageInfos = new PageInfo<>(subList, DepartmentListDTO.class);
            pageInfos.setTotal(compListDTOS.size());
        }

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

        OrganizationWeaTable<DepartmentListDTO> table = new OrganizationWeaTable<>(user, DepartmentListDTO.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 Long saveBaseForm(Map<String, Object> params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        Map<String, Object> syncMap = new OrganizationSyncEc(user, LogModuleNameEnum.DEPARTMENT, OperateTypeEnum.ADD, params).sync();
        String ecCompanyID = Util.null2String(syncMap.get("id"));
        OrganizationAssert.isTrue(StringUtils.isNotBlank(ecCompanyID), syncMap.get("message").toString());
        return Long.parseLong(ecCompanyID);
    }

    @Override
    public int updateForbiddenTagById(DeptSearchParam params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        DepartmentPO departmentPO = DepartmentPO.builder().id(params.getId()).canceled(params.getForbiddenTag() ? 0 : 1).build();
        Map<String, Object> map = new HashMap<>();
        map.put("id", Util.null2String(departmentPO.getId()));
        map.put("forbiddenTag", Util.null2String(departmentPO.getCanceled()));
        new OrganizationSyncEc(user, LogModuleNameEnum.DEPARTMENT, OperateTypeEnum.CANCELED, map).sync();
        return 1;
    }

    @Override
    public Long updateForm(Map<String, Object> params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        Integer ecDepartmentId = Integer.parseInt(Util.null2String(params.get("id")));
        String supDepId = Util.null2String(params.get("supdepid"));
        if (StringUtils.isNotBlank(supDepId)) {
            // 不可选择合并的数据，本身及子部门
            Set<Integer> disableIds = new HashSet<>();
            // 添加选择部门本身
            disableIds.add(ecDepartmentId);
            List<DepartmentPO> deptListByPId = getDepartmentMapper().getDeptListByPId(ecDepartmentId);
            if (CollectionUtils.isNotEmpty(deptListByPId)) {
                addDisableIds(disableIds, deptListByPId);
            }
            OrganizationAssert.isFalse(disableIds.contains(Integer.parseInt(supDepId)), "上级部门不能选择部门本身及其下级部门");
        }

        new OrganizationSyncEc(user, LogModuleNameEnum.DEPARTMENT, OperateTypeEnum.UPDATE, params).sync();
        return (long) ecDepartmentId;
    }

    @Override
    public Map<String, Object> deleteByIds(Map<String, Object> params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        return ServiceUtil.getService(OrganizationServiceImpl.class, user).delDepartment(params, user);
    }

    @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 departmentCodeItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "编号", "departmentCode");
        // 名称
        SearchConditionItem departmentNameItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "名称", "departmentName");
        // 所属分部
        SearchConditionItem subCompanyId1Item = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "所属分部", "164", "subCompanyId1", "");
        // 上级部门
        SearchConditionItem supDepIdItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "上级部门", "4", "supDepId", "");

        conditionItems.add(departmentCodeItem);
        conditionItems.add(departmentNameItem);
        conditionItems.add(subCompanyId1Item);
        conditionItems.add(supDepIdItem);

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

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

    @Override
    public Map<String, Object> getDeptBaseForm(Map<String, Object> params) {
        OrganizationAssert.notNull(params.get("viewAttr"), "请标识操作类型");
        // 2编辑 1查看
        int viewAttr = Integer.parseInt((String) params.get("viewAttr"));

        List<SearchConditionGroup> groupList = new ArrayList<>();
        List<SearchConditionItem> itemList;
        String id = Util.null2String(params.get("id"));
        if (2 == viewAttr) {
            params.put("viewattr", viewAttr);
            groupList = getDepartmentConditionGroups(true, params);
        } else {

            HrmFieldGroupComInfo HrmFieldGroupComInfo = new HrmFieldGroupComInfo();
            HrmFieldComInfo HrmFieldComInfo = new HrmFieldComInfo();
            HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo();
            SearchConditionItem searchConditionItem;
            HrmFieldBean hrmFieldBean;
            HrmDeptFieldManagerE9 hfm;
            try {
                hfm = new HrmDeptFieldManagerE9(5);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            hfm.getCustomData(Util.getIntValue(id));
            List lsGroup = hfm.getLsGroup();
            for (int tmp = 0; lsGroup != null && tmp < lsGroup.size(); tmp++) {
                String groupId = (String) lsGroup.get(tmp);
                List lsField = hfm.getLsField(groupId);
                if (lsField.size() == 0) {
                    continue;
                }
                if (hfm.getGroupCount(lsField) == 0) {
                    continue;
                }
                if (!"1".equals(Util.null2String(HrmFieldGroupComInfo.getIsShow(groupId)))) {
                    continue;
                }
                String groupLabel = HrmFieldGroupComInfo.getLabel(groupId);
                itemList = new ArrayList<>();
                for (Object o : lsField) {
                    String fieldId = (String) o;
                    String isUse = HrmFieldComInfo.getIsused(fieldId);
                    if (!"1".equals(isUse)) {
                        continue;
                    }
                    String fieldName = HrmFieldComInfo.getFieldname(fieldId);
                    String fieldLabel = HrmFieldComInfo.getLabel(fieldId);
                    String fieldHtmlType = HrmFieldComInfo.getFieldhtmltype(fieldId);
                    String type = HrmFieldComInfo.getFieldType(fieldId);
                    String dmlUrl = Util.null2String(HrmFieldComInfo.getFieldDmlurl(fieldId));
                    String isSystem = HrmFieldComInfo.getIssystem(fieldId);
                    String fieldValue;
                    if ("1".equals(isSystem)) {
                        fieldValue = hfm.getData(fieldName);
                    } else {
                        fieldValue = hfm.getData("hrmdepartmentdefined", fieldName);
                    }

                    if (id.length() > 0 && "showid".equals(fieldName)) {
                        fieldValue = id;
                    }

                    hrmFieldBean = new HrmFieldBean();
                    hrmFieldBean.setFieldid(fieldId);
                    hrmFieldBean.setFieldname(fieldName);
                    hrmFieldBean.setFieldlabel(fieldLabel);
                    hrmFieldBean.setFieldhtmltype(fieldHtmlType);
                    hrmFieldBean.setType(type);
                    hrmFieldBean.setIsFormField(true);
                    hrmFieldBean.setFieldvalue(fieldValue);
                    hrmFieldBean.setDmlurl(dmlUrl);
                    hrmFieldBean.setIssystem("1");
                    searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user);
                    if (searchConditionItem.getBrowserConditionParam() != null) {
                        searchConditionItem.getBrowserConditionParam().setViewAttr(viewAttr);
                    }
                    if ("showorder".equals(fieldName)) {
                        searchConditionItem.setPrecision(2);
                    }

                    if ("6".equals(fieldHtmlType)) {//附件
                        Map<String, Object> otherParams1 = new HashMap<>();
                        otherParams1.put("showOrder", false);
                        searchConditionItem.setOtherParams(otherParams1);
                    }

                    searchConditionItem.setViewAttr(viewAttr);
                    itemList.add(searchConditionItem);

                }

                int operateLevel;
                ManageDetachComInfo manageDetachComInfo = new ManageDetachComInfo();
                boolean hrmDetachAble = manageDetachComInfo.isUseHrmManageDetach();
                if (hrmDetachAble) {
                    CheckSubCompanyRight checkSubCompanyRight = new CheckSubCompanyRight();
                    DepartmentComInfo departmentComInfo = new DepartmentComInfo();
                    operateLevel = checkSubCompanyRight.ChkComRightByUserRightCompanyId(user.getUID(), "HrmDepartmentEdit:Edit", Integer.parseInt(departmentComInfo.getSubcompanyid1(id)));
                } else {
                    operateLevel = 2;
                }

                if (tmp == 0 && HrmUserVarify.checkUserRight("HrmDepartmentEdit:Edit", user) && operateLevel > 0) {
                    int resourceNum = 0;
                    RecordSet rs = new RecordSet();

                    String sql = "SELECT COUNT(*) FROM hrmresource WHERE departmentid = " + id + " and ( status =0 or status = 1 or status = 2 or status = 3)";
                    rs.execute(sql);
                    if (rs.next()) {
                        resourceNum = rs.getInt(1);
                    }

                    //4:解聘 5:离职 6:退休 7:无效
                    int resourceNum1 = 0;
                    sql = "SELECT COUNT(*) FROM hrmresource WHERE departmentid = " + id + " and status in(4,5,6,7)";
                    rs.execute(sql);
                    if (rs.next()) {
                        resourceNum1 = rs.getInt(1);
                    }
                    hrmFieldBean = new HrmFieldBean();
                    hrmFieldBean.setFieldname("deptResourceInfo");
                    hrmFieldBean.setFieldlabel("382428");
                    hrmFieldBean.setFieldhtmltype("1");
                    hrmFieldBean.setType("1");
                    hrmFieldBean.setIsFormField(true);
                    hrmFieldBean.setFieldvalue(resourceNum + "/" + resourceNum1);
                    hrmFieldBean.setDmlurl("");
                    searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user);
                    searchConditionItem.setViewAttr(viewAttr);
                    itemList.add(searchConditionItem);
                }
                groupList.add(new SearchConditionGroup(SystemEnv.getHtmlLabelNames(groupLabel, user.getLanguage()), true, itemList));

            }
        }

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

        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("buttons", buttonsMap);
        resultMap.put("conditions", groupList);
        resultMap.put("id", id);
        List<TopTab> topTabs = new ArrayList<>();
        topTabs.add(TopTab.builder().color("#000000").groupId("4").showcount(false).title("部门信息").viewCondition("4").build());
        resultMap.put("tabInfo", topTabs);

        Map<String, Object> apiDatas = new HashMap<>();
        apiDatas.put("result", resultMap);
        return apiDatas;
    }

    @Override
    public Map<String, Object> getSaveForm(Map<String, Object> params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        Map<String, Object> apiDatas = new HashMap<>();
        apiDatas.put("condition", getDepartmentConditionGroups(false, params));
        return apiDatas;
    }

    /**
     * 复制表单
     *
     * @return
     */
    @Override
    public List<SearchConditionGroup> getCopyForm() {
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<SearchConditionItem> condition = new ArrayList<>();
        SearchConditionItem compBrowserItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 3, false, "复制到", "164", "company", "");
        compBrowserItem.setRules("required|string");
        SearchConditionItem copySubDeptItem = OrganizationFormItemUtil.selectItem(user, Lists.newArrayList(new SearchConditionOption("1", "")), 2, 5, 10, false, "复制子部门信息", "copySubDept");
        copySubDeptItem.setDetailtype(2);
        condition.add(compBrowserItem);
        condition.add(copySubDeptItem);
        addGroups.add(new SearchConditionGroup("", true, condition));
        return addGroups;
    }

    /**
     * 复制岗位到指定部门
     *
     * @param copyParam
     * @return
     */
    @Override
    public int copyDepartment(DeptCopyParam copyParam) {
        // 批量复制，后续优化
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        OrganizationAssert.notBlank(copyParam.getCompany(), "请指定需要复制的公司/分部");
        int insertCount = 0;
        // 需复制的部门
        List<Integer> idList = Arrays.stream(copyParam.getIds().split(",")).map(Integer::parseInt).collect(Collectors.toList());
        Double maxShowOrder = getDepartmentMapper().getMaxShowOrder();
        maxShowOrder = null == maxShowOrder ? 0 : maxShowOrder;
        for (Integer departmentId : idList) {
            // 复制当前部门
            recursionCopyDept(departmentId, null, Integer.parseInt(copyParam.getCompany()), maxShowOrder, copyParam.getCopyJob(), copyParam.getCopySubDept(), copyParam.getCopySubJob());
        }
        return insertCount;
    }

    private void recursionCopyDept(Integer originalDeptId, Integer parentDepartmentId, Integer companyId, Double maxShowOrder, String copyJob, String copySubDept, String copySubJob) {
        // 源部门
        DepartmentPO deptById = getDepartmentMapper().getDeptById(originalDeptId);
        long timeMillis = System.currentTimeMillis();
        // 处理自动编号
        deptById.setDepartmentCode(null);
        // 设置上级分部
        deptById.setSubCompanyId1(companyId);
        deptById.setSupDepId(parentDepartmentId);
        // 显示顺序字段
        deptById.setShowOrder(++maxShowOrder);
        deptById.setUuid(null);

        // 新增EC表部门
        Map<String, Object> syncMap = addEcDepartment(deptById);
        String ecDepartmentID = Util.null2String(syncMap.get("id"));
        OrganizationAssert.isTrue(StringUtils.isNotBlank(ecDepartmentID), syncMap.get("message").toString());
        // 更新组织架构图
        //TODO new DepartmentTriggerRunnable(deptById.getId()).run();

        //  复制当前部门岗位信息
        //if ("1".equals(copyJob)) {
        //    List<JobPO> jobPOS = MapperProxyFactory.getProxy(JobMapper.class).listJobsByDepartmentId(originalDeptId);
        //    jobPOS = jobPOS.stream().filter(item -> null == item.getParentJob() || 0 == item.getParentJob()).collect(Collectors.toList());
        //    Integer maxJobOrder = MapperProxyFactory.getProxy(JobMapper.class).getMaxShowOrder();
        //    if (maxJobOrder == null) {
        //        maxJobOrder = 0;
        //    }
        //    recursionCopyJob(jobPOS, companyId, Integer.parseInt(ecDepartmentID), null, maxJobOrder, timeMillis);
        //}

        // 是否复制子部门信息
        if ("1".equals(copySubDept)) {
            // 查询当前部门的子部门
            List<DepartmentPO> deptListByPId = getDepartmentMapper().getDeptListByPId(originalDeptId);
            for (DepartmentPO departmentPO : deptListByPId) {
                // 复制子部门信息、子部门岗位信息
                recursionCopyDept(departmentPO.getId(), Integer.parseInt(ecDepartmentID), companyId, maxShowOrder, copySubJob, copySubDept, copySubJob);
            }
        }
    }

    @Override
    public List<SearchConditionGroup> getMergeForm() {
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<SearchConditionItem> condition = new ArrayList<>();
        SearchConditionItem deptBrowserItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 3, false, "合并到部门", "4", "department", "");
        deptBrowserItem.setRules("required|string");
        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 mergeDepartment(DepartmentMergeParam mergeParam) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        // 被合并部门
        Integer ecParamDepartment = mergeParam.getDepartment();
        DepartmentPO targetDepartment = getDepartmentMapper().getDeptById(ecParamDepartment);


        // 断言判断
        OrganizationAssert.isFalse(null == targetDepartment, "被合并部门数据有误，暂时无法合并");
        OrganizationAssert.isFalse(mergeParam.getId().equals(targetDepartment.getId()), "所选部门与待合并部门一致，无需操作");
        OrganizationAssert.notNull(mergeParam.getDepartment(), "请选择需要合并的部门");
        OrganizationAssert.notBlank(mergeParam.getMergeName(), "请输入合并后的名称");

        // 不可选择合并的数据，本身及子部门
        Set<Integer> disableIds = new HashSet<>();
        // 添加选择部门本身
        disableIds.add(mergeParam.getId());
        List<DepartmentPO> deptListByPId = getDepartmentMapper().getDeptListByPId(mergeParam.getId());
        if (CollectionUtils.isNotEmpty(deptListByPId)) {
            addDisableIds(disableIds, deptListByPId);
        }
        OrganizationAssert.isFalse(disableIds.contains(targetDepartment.getId()), "请勿选择当前部门本身及其子部门");

        // 查询该部门下一级部门
        List<DepartmentPO> firstChildDeptList = getDepartmentMapper().getDeptListByPId(mergeParam.getId());
        // 更新所属部门、所属分部
        for (DepartmentPO departmentPO : firstChildDeptList) {
            departmentPO.setSupDepId(targetDepartment.getId());
            departmentPO.setSubCompanyId1(targetDepartment.getSubCompanyId1());
            updateEcDepartment(departmentPO);
            // 更新组织架构图
            //TODO new DepartmentTriggerRunnable(departmentPO.getId()).run();
        }
        // 查询该部门一级岗位、更新岗位所属分部、所属部门
        //List<JobPO> firstChildJobList = getJobMapper().listJobsByDepartmentId(mergeParam.getId());
        //firstChildJobList = firstChildJobList.stream().filter(item -> null == item.getParentJob() || 0 == item.getParentJob()).collect(Collectors.toList());
        // 批量更新部门、所属分部
        RecordSet rs = new RecordSet();
        String targetEcDeptId = targetDepartment.getId().toString();
        String mergeEcDeptId = mergeParam.getId().toString();
        //rs.executeUpdate("update jcl_org_job set parent_comp =?,ec_company =?,parent_dept =?,ec_department =? where ec_department =?", targetDepartment.getSubCompanyId1(), targetDepartment.getSubCompanyId1(), targetDepartment.getId(), targetEcDeptId, mergeParam.getId());
        // 更新岗位组织架构图
        //for (JobPO jobPO : firstChildJobList) {
        //    // 刷新组织架构图
        //    TODO new JobTriggerRunnable(jobPO.getId()).run();
        //}
        // 更新当前部门下的人员
        rs.executeUpdate("update hrmresource set SUBCOMPANYID1 =?,DEPARTMENTID =? where DEPARTMENTID =?", targetDepartment.getSubCompanyId1(), targetEcDeptId, mergeEcDeptId);
        //new RecordSet().executeUpdate("update jcl_org_hrmresource set company_id =? ,ec_company = ? ,department_id = ?, ec_department = ?where department_id =?", targetDepartment.getParentComp(), targetDepartment.getEcCompany(), targetDepartment.getId(), targetEcDeptId, mergeParam.getId());
        //List<Long> hrmResourceIds = getSystemDataMapper().getHrmResourceIdsByDept(mergeParam.getId().toString());
        //// 更新人员组织架构图
        //for (Long hrmResourceId : hrmResourceIds) {
        //TODO   new HrmResourceTriggerRunnable(hrmResourceId).run();
        //}
        // 更新子部门下岗位的所属分部
        for (DepartmentPO departmentPO : firstChildDeptList) {
            List<DepartmentPO> deptList = getDepartmentMapper().getDeptListByPId(departmentPO.getId());
            forbiddenChildTag(targetDepartment.getSubCompanyId1(), deptList);
        }
        // 原部门删除
        // DepartmentPO mergeDepartment = getDepartmentMapper().getDeptById(mergeParam.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("id", Util.null2String(mergeParam.getId()));
        // 删除部门
        ServiceUtil.getService(OrganizationServiceImpl.class, user).doDepartmentCancel(map, user);
        // 更新组织架构图
        // TODO new DepartmentTriggerRunnable(mergeDepartment).run();
        // 更新部门合并后名称
        targetDepartment.setDepartmentName(mergeParam.getMergeName());
        targetDepartment.setDepartmentMark(mergeParam.getMergeName());
        updateEcDepartment(targetDepartment);
        // 更新组织架构图
        // TODO new DepartmentTriggerRunnable(oldFParentId, targetDepartment.getId()).run();
        return 0;
    }

    @Override
    public List<SearchConditionGroup> getMoveForm() {
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<SearchConditionItem> condition = new ArrayList<>();
        SearchConditionItem compBrowserItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "选择分部", "164", "company", "");
        SearchConditionItem deptBrowserItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "选择部门", "4", "department", "");


        List<SearchConditionOption> selectOptions = new ArrayList<>();
        SearchConditionOption compOption = new SearchConditionOption("0", "分部");
        SearchConditionOption deptOption = new SearchConditionOption("1", "部门");
        selectOptions.add(compOption);
        selectOptions.add(deptOption);
        SearchConditionItem moveTypeItem = OrganizationFormItemUtil.selectItem(user, selectOptions, 2, 16, 6, false, "转移到", "moveType");
        moveTypeItem.setDetailtype(3);
        moveTypeItem.setValue("0");

        condition.add(moveTypeItem);
        condition.add(compBrowserItem);
        condition.add(deptBrowserItem);
        addGroups.add(new SearchConditionGroup("", true, condition));
        return addGroups;
    }

    @Override
    public int moveDepartment(DepartmentMoveParam moveParam) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        OrganizationAssert.notBlank(moveParam.getMoveType(), "请选择转移类型");
        DepartmentPO deptById = getDepartmentMapper().getDeptById(moveParam.getId());
        // 0：公司/分部 1：部门
        if ("0".equals(moveParam.getMoveType())) {
            Integer company = moveParam.getCompany();
            OrganizationAssert.notNull(company, "请选择要转移到的分部");
            deptById.setSubCompanyId1(company);
            deptById.setSupDepId(null);

            // 更新组织架构图
            //TODO new DepartmentTriggerRunnable(company.toString(), deptById).run();
        } else if ("1".equals(moveParam.getMoveType())) {
            Integer departmentId = moveParam.getDepartment();
            OrganizationAssert.notNull(departmentId, "请选择要转移到的部门");
            List<DepartmentPO> deptListByPId = getDepartmentMapper().getDeptListByPId(moveParam.getId());
            Set<Integer> disableIds = new HashSet<>();
            disableIds.add(moveParam.getId());
            if (CollectionUtils.isNotEmpty(deptListByPId)) {
                addDisableIds(disableIds, deptListByPId);
            }
            OrganizationAssert.isFalse(disableIds.contains(departmentId), "请勿选择当前部门本身及其子部门");
            deptById.setSupDepId(departmentId);
            DepartmentPO parentDepartment = getDepartmentMapper().getDeptById(departmentId);
            deptById.setSubCompanyId1(parentDepartment.getSubCompanyId1());

            // 更新组织架构图
            // TODO new DepartmentTriggerRunnable(Integer.toString(100000000 + department.intValue()), deptById).run();
        }
        // 更新EC部门
        updateEcDepartment(deptById);

        // 刷新岗位分部
        //refreshJobComp(deptById.getId(), deptById.getSubCompanyId1());
        List<DepartmentPO> deptList = getDepartmentMapper().getDeptListByPId(deptById.getId());
        // 更新当前部门下的人员
        // new RecordSet().executeUpdate("update hrmresource set SUBCOMPANYID1 =?  where DEPARTMENTID = ?", deptById.getSubCompanyId1(), deptById.getId());
        //// 更新人员组织架构图
        //List<Long> hrmResourceIds = getSystemDataMapper().getHrmResourceIdsByDept(deptById.getId().toString());
        //for (Long hrmResourceId : hrmResourceIds) {
        //TODO    new HrmResourceTriggerRunnable(hrmResourceId).run();
        //}
        forbiddenChildTag(deptById.getSubCompanyId1(), deptList);
        // 递归更新下级部门、岗位
        return 1;
    }

    /**
     * 获取所有子部门id
     *
     * @param subCompanyId1
     * @param deptList
     */
    void forbiddenChildTag(Integer subCompanyId1, List<DepartmentPO> deptList) {
        if (CollectionUtils.isNotEmpty(deptList)) {
            for (DepartmentPO departmentPO : deptList) {
                departmentPO.setSubCompanyId1(subCompanyId1);
                // 更新EC表部门
                updateEcDepartment(departmentPO);

                // 更新组织架构图
                // TODO new DepartmentTriggerRunnable(departmentPO.getId()).run();
                // 刷新岗位所属分部
                //refreshJobComp(departmentPO.getId(), subCompanyId1);
                // 更新当前部门下的人员
                // String ecDepartmentId = EcHrmRelationUtil.getEcDepartmentId(departmentPO.getId().toString());
                //new RecordSet().executeUpdate("update hrmresource set SUBCOMPANYID1 =?  where DEPARTMENTID = ?", ecCompanyId, ecDepartmentId);
                //new RecordSet().executeUpdate("update jcl_org_hrmresource set company_id =? ,ec_company = ? where department_id =?", parentComp, ecCompanyId, departmentPO.getId());
                //List<Long> hrmResourceIds = getSystemDataMapper().getHrmResourceIdsByDept(departmentPO.getId().toString());
                //// 更新人员组织架构图
                //for (Long hrmResourceId : hrmResourceIds) {
                //TODO    new HrmResourceTriggerRunnable(hrmResourceId).run();
                //}
                List<DepartmentPO> childList = getDepartmentMapper().getDeptListByPId(departmentPO.getId());
                forbiddenChildTag(subCompanyId1, childList);
            }
        }
    }

    /**
     * 是否为搜索查询
     *
     * @param departmentPO
     * @return
     */
    private boolean isFilter(DepartmentPO departmentPO) {
        return !(StringUtil.isEmpty(departmentPO.getDepartmentCode())
                && StringUtil.isEmpty(departmentPO.getDepartmentName())
                && null == departmentPO.getSubCompanyId1()
                && null == departmentPO.getSupDepId()
                && null == departmentPO.getDepartmentId());
    }


    /**
     * 根据keyword查询数据
     *
     * @param id
     * @param keyword
     * @return
     */
    private List<SearchTree> getFilterCompany(String id, String keyword) {
        // 查询部门信息
        Integer parentCompId = StringUtil.isEmpty(id) ? null : Integer.parseInt(id);
        CompPO compBuild = CompPO.builder().subCompanyName(keyword).supSubComId(parentCompId).canceled(0).build();
        List<CompPO> allCompanys = getCompMapper().listAll("showOrder");
        new DetachUtil(user).filterCompanyList(allCompanys);
        List<CompPO> filterComps = getCompMapper().listByFilter(compBuild, "showOrder");
        new DetachUtil(user).filterCompanyList(filterComps);

        Map<Integer, CompPO> allMaps = allCompanys.stream().collect(Collectors.toMap(CompPO::getId, item -> item, (k1, k2) -> k1));

        Set<CompPO> builderComps = new HashSet<>();
        for (CompPO companyPO : filterComps) {
            buildParentComps(companyPO, builderComps, allMaps);
        }
        return SearchTreeUtil.builderTreeMode(CompBO.buildSetToSearchTree(builderComps));

    }

    /**
     * 添加查询元素的父级元素
     *
     * @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);
        }
    }

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

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

    /**
     * 更新EC表部门
     *
     * @param departmentPO
     */
    private void updateEcDepartment(DepartmentPO departmentPO) {
        Map<String, Object> map = new HashMap<>();
        map.put("departmentmark", departmentPO.getDepartmentMark());
        map.put("departmentname", departmentPO.getDepartmentName());
        map.put("subcompanyid1", Util.null2String(departmentPO.getSubCompanyId1()));
        map.put("supdepid", Util.null2String(departmentPO.getSupDepId()));
        map.put("showorder", Util.null2String(departmentPO.getShowOrder()));
        map.put("departmentcode", departmentPO.getDepartmentCode());
        map.put("coadjutant", Util.null2String(departmentPO.getCoadjutant()));
        map.put("id", Util.null2String(departmentPO.getId()));
        new OrganizationSyncEc(user, LogModuleNameEnum.DEPARTMENT, OperateTypeEnum.UPDATE, map).sync();
    }

    /**
     * 新增EC表部门
     *
     * @param departmentPO
     * @return
     */
    private Map<String, Object> addEcDepartment(DepartmentPO departmentPO) {
        Map<String, Object> map = new HashMap<>();
        map.put("departmentmark", departmentPO.getDepartmentMark());
        map.put("departmentname", departmentPO.getDepartmentName());
        map.put("subcompanyid1", Util.null2String(departmentPO.getSubCompanyId1()));
        map.put("supdepid", Util.null2String(departmentPO.getSupDepId()));
        map.put("showorder", Util.null2String(departmentPO.getShowOrder()));
        map.put("departmentcode", departmentPO.getDepartmentCode());
        return new OrganizationSyncEc(user, LogModuleNameEnum.DEPARTMENT, OperateTypeEnum.ADD, map).sync();
    }


    private void addDisableIds(Set<Integer> disableIds, List<DepartmentPO> deptListByPId) {
        for (DepartmentPO departmentPO : deptListByPId) {
            disableIds.add(departmentPO.getId());
            List<DepartmentPO> childDeptPOS = getDepartmentMapper().getDeptListByPId(departmentPO.getId());
            addDisableIds(disableIds, childDeptPOS);
        }
    }

    /**
     * 更新岗位的所属分部
     *
     * @param parentDepartment
     * @param parentComp
     */
    private void refreshJobComp(Integer parentDepartment, Integer parentComp) {
        List<JobPO> jobPOS = getJobMapper().listJobsByDepartmentId(parentDepartment);
        jobPOS = jobPOS.stream().filter(item -> null == item.getParentJob() || 0 == item.getParentJob()).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(jobPOS)) {
            getJobMapper().updateJobCompany(jobPOS.stream().map(JobPO::getId).collect(Collectors.toList()), parentComp, parentComp);
        }
    }

    private List<SearchConditionGroup> getDepartmentConditionGroups(Boolean showAll, Map<String, Object> params) {
        List<SearchConditionGroup> groupList = new ArrayList<>();
        List<SearchConditionItem> itemList;

        String id = Util.null2String(params.get("id"));
        int viewAttr = Util.getIntValue(Util.null2String(params.get("viewattr")), 1);
        String addType = Util.null2String(params.get("addType"));
        String subcompanyid1 = Util.null2String(params.get("subcompanyid1"));
        String supDepId = Util.null2String(params.get("departmentid"));
        if (StringUtils.isNotBlank(supDepId)) {
            subcompanyid1 = new DepartmentComInfo().getSubcompanyid1(supDepId);
        }


        HrmFieldGroupComInfo HrmFieldGroupComInfo = new HrmFieldGroupComInfo();
        HrmFieldComInfo HrmFieldComInfo = new HrmFieldComInfo();
        HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo();
        SearchConditionItem searchConditionItem;
        HrmFieldBean hrmFieldBean;
        HrmDeptFieldManagerE9 hfm;
        try {
            hfm = new HrmDeptFieldManagerE9(5);
        } catch (Exception e) {
            throw new OrganizationRunTimeException("");
        }
        hfm.isReturnDecryptData(true);
        hfm.getCustomData(Util.getIntValue(id));
        List lsGroup = hfm.getLsGroup();
        int lsSize = 1;
        if (showAll && lsGroup != null) {
            lsSize = lsGroup.size();
        }
        for (int tmp = 0; tmp < lsSize; tmp++) {
            String groupId = (String) lsGroup.get(tmp);
            List lsField = hfm.getLsField(groupId);

            boolean groupHide = lsField.size() == 0 || hfm.getGroupCount(lsField) == 0 || !"1".equals(Util.null2String(HrmFieldGroupComInfo.getIsShow(groupId)));
            String grouplabel = HrmFieldGroupComInfo.getLabel(groupId);
            itemList = new ArrayList<>();
            for (Object o : lsField) {
                String fieldId = (String) o;
                String fieldName = HrmFieldComInfo.getFieldname(fieldId);
                String isUse = HrmFieldComInfo.getIsused(fieldId);
                if (!"1".equals(isUse)) {
                    continue;
                }
                int tmpViewAttr = viewAttr;
                String rules = "";
                String fieldLabel = HrmFieldComInfo.getLabel(fieldId);
                String fieldHtmlType = HrmFieldComInfo.getFieldhtmltype(fieldId);
                String type = HrmFieldComInfo.getFieldType(fieldId);
                String dmlUrl = Util.null2String(HrmFieldComInfo.getFieldDmlurl(fieldId));
                String isSystem = HrmFieldComInfo.getIssystem(fieldId);
                String fieldValue = "";
                if (StringUtils.isBlank(addType)) {
                    if ("1".equals(isSystem)) {
                        fieldValue = hfm.getData(fieldName);
                    } else {
                        fieldValue = hfm.getData("hrmdepartmentdefined", fieldName);
                    }
                }

                if (!groupHide && tmpViewAttr == 2 && "1".equals(HrmFieldComInfo.getIsmand(fieldId))) {
                    tmpViewAttr = 3;
                    if ("1".equals(fieldHtmlType) && "2".equals(type)) {
                        rules = "required|integer";
                    } else {
                        rules = "required|string";
                    }
                }

                if (subcompanyid1.length() > 0 && "subcompanyid1".equals(fieldName)) {
                    fieldValue = subcompanyid1;
                }

                if (supDepId.length() > 0 && "supdepid".equals(fieldName)) {
                    fieldValue = supDepId;
                }

                if ("showid".equals(fieldName)) {
                    if (addType.length() > 0) {
                        continue;
                    } else {
                        fieldValue = id;
                        tmpViewAttr = 1;
                    }
                }

                hrmFieldBean = new HrmFieldBean();
                hrmFieldBean.setFieldid(fieldId);
                hrmFieldBean.setFieldname(fieldName);
                hrmFieldBean.setFieldlabel(fieldLabel);
                hrmFieldBean.setFieldhtmltype(fieldHtmlType);
                hrmFieldBean.setType(type);
                hrmFieldBean.setIsFormField(true);
                hrmFieldBean.setIssystem("1");
                hrmFieldBean.setFieldvalue(fieldValue);
                hrmFieldBean.setDmlurl(dmlUrl);
                hrmFieldBean.setViewAttr(tmpViewAttr);
                hrmFieldBean.setRules(rules);
                if ("subcompanyid1".equals(hrmFieldBean.getFieldname()) || "supdepid".equals(hrmFieldBean.getFieldname())) {
                    hrmFieldBean.setHideVirtualOrg(true);
                }
                if ("departmentcode".equals(hrmFieldBean.getFieldname())) {
                    hrmFieldBean.setMultilang(false);
                }
                searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user);
                if (searchConditionItem != null) {
                    searchConditionItem.setLabelcol(8);
                    searchConditionItem.setFieldcol(16);
                    if ("showorder".equals(fieldName)) {
                        searchConditionItem.setPrecision(2);
                    }
                    if ("showid".equals(fieldName)) {
                        Map<String, Object> otherParams = new HashMap<>();
                        otherParams.put("hasBorder", true);
                        searchConditionItem.setOtherParams(otherParams);
                    }
                    if ("6".equals(fieldHtmlType)) {//附件
                        Map<String, Object> otherParams1 = new HashMap<>();
                        otherParams1.put("showOrder", false);
                        searchConditionItem.setOtherParams(otherParams1);
                    }
                    itemList.add(searchConditionItem);

                }
            }
            groupList.add(new SearchConditionGroup(SystemEnv.getHtmlLabelNames(grouplabel, user.getLanguage()), true, itemList));

        }
        return groupList;
    }

}
