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.browser.util.ConditionType;
import com.api.hrm.bean.HrmFieldBean;
import com.api.hrm.util.HrmFieldSearchConditionComInfo;
import com.cloudstore.eccom.constant.WeaBoolAttr;
import com.cloudstore.eccom.pc.table.WeaTableColumn;
import com.cloudstore.eccom.result.WeaResultMsg;
import com.engine.core.impl.Service;
import com.engine.hrm.util.face.HrmFaceCheckManager;
import com.engine.organization.component.OrganizationWeaTable;
import com.engine.organization.entity.DeleteParam;
import com.engine.organization.entity.chart.ResourceListColumns;
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.bo.ExtendInfoBO;
import com.engine.organization.entity.extend.po.ExtendInfoPO;
import com.engine.organization.entity.hrmresource.bo.HrmRelationBO;
import com.engine.organization.entity.hrmresource.bo.ResourceChartBO;
import com.engine.organization.entity.hrmresource.param.HrmRelationSaveParam;
import com.engine.organization.entity.hrmresource.param.SearchTemplateParam;
import com.engine.organization.entity.hrmresource.po.*;
import com.engine.organization.entity.hrmresource.vo.HrmResourceVO;
import com.engine.organization.entity.hrmresource.vo.ResourceChartVO;
import com.engine.organization.entity.jclimport.po.CusFormFieldPO;
import com.engine.organization.entity.job.bo.JobBO;
import com.engine.organization.entity.job.po.JobPO;
import com.engine.organization.entity.search.QuickSearchDetail;
import com.engine.organization.entity.searchtree.SearchTree;
import com.engine.organization.entity.searchtree.SearchTreeParams;
import com.engine.organization.enums.HrmGroupEnum;
import com.engine.organization.mapper.comp.CompMapper;
import com.engine.organization.mapper.condition.QuickSearchMapper;
import com.engine.organization.mapper.department.DepartmentMapper;
import com.engine.organization.mapper.hrmresource.HrmRelationMapper;
import com.engine.organization.mapper.hrmresource.SystemDataMapper;
import com.engine.organization.mapper.job.JobMapper;
import com.engine.organization.mapper.resource.HrmResourceMapper;
import com.engine.organization.mapper.resource.JclOrgCustomTemplateMapper;
import com.engine.organization.service.HrmResourceService;
import com.engine.organization.util.HasRightUtil;
import com.engine.organization.util.MenuBtn;
import com.engine.organization.util.OrganizationAssert;
import com.engine.organization.util.OrganizationDateUtil;
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 org.json.JSONException;
import org.json.JSONObject;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.StringUtil;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.definedfield.HrmFieldManager;
import weaver.systeminfo.SystemEnv;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static weaver.general.Util.getIntValue;

/**
 * @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 String RIGHT_NAME = "Roster:All";


    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 SystemDataMapper getSystemDataMapper() {
        return MapperProxyFactory.getProxy(SystemDataMapper.class);
    }

    private JclOrgCustomTemplateMapper getJclOrgCustomTemplateMapper() {
        return MapperProxyFactory.getProxy(JclOrgCustomTemplateMapper.class);
    }

    private QuickSearchMapper getQuickSearchMapper() {
        return MapperProxyFactory.getProxy(QuickSearchMapper.class);
    }


    // 所有满足条件的岗位ID
    private List<Integer> jobTitleList = null;
    // 是否
    boolean searchJobTitle = false;


    @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(Map<String, Object> params) {
        OrganizationWeaTable<HrmResourceVO> table = new OrganizationWeaTable<>(user, HrmResourceVO.class);
        String sqlWhere = buildSqlWhere(params);
        table.setSqlwhere(sqlWhere);
        List<WeaTableColumn> weaTableColumnList = new ArrayList<>();
        JclOrgCustomTemplatePO jclOrgCustomTemplatePO = MapperProxyFactory.getProxy(JclOrgCustomTemplateMapper.class).queryIsusedTemp("1", String.valueOf(user.getUID()));
        String columns = "";
        List<String> fields = new ArrayList<>();
        List<SearchConditionGroup> allConditions = getAllConditions();

        if (jclOrgCustomTemplatePO != null) {
            if (StringUtils.isNotBlank(jclOrgCustomTemplatePO.getBasicFields())) {
                columns = jclOrgCustomTemplatePO.getBasicFields();
            }
            if (StringUtils.isNotBlank(jclOrgCustomTemplatePO.getPersonalFields())) {
                columns = columns + "," + jclOrgCustomTemplatePO.getPersonalFields();
            }
            if (StringUtils.isNotBlank(jclOrgCustomTemplatePO.getWorkFields())) {
                columns = columns + "," + jclOrgCustomTemplatePO.getWorkFields();
            }
        } else {
            //初次使用，无模板初始值
            columns = "-1_hrm_lastname,-1_hrm_departmentid,-1_hrm_subcompanyid1,-1_hrm_jobtitle,-1_hrm_mobile,-1_hrm_telephone,-1_hrm_managerid,-1_hrm_sporder";
        }

        List<String> columnList = Arrays.asList(columns.split(","));
        BigDecimal decimal = new BigDecimal(100 / columnList.size());
        List<SearchConditionItem> all = new ArrayList<>();
        for (SearchConditionGroup allCondition : allConditions) {
            all.addAll(allCondition.getItems());

        }
        List<SearchConditionItem> items = filterByDomkey(all, columnList);
        for (SearchConditionItem item : items) {
            String columnName = item.getDomkey()[0];
            fields.add(buildTableSql(columnName) + " as " + buildTableSql(columnName).replace(".", "_"));

            String scopeId = columnName.split("_")[0];
            String fieldName = columnName.substring(columnName.lastIndexOf("_") + 1);
            WeaTableColumn weaTableColumn = new WeaTableColumn();
            weaTableColumn.setText(getHrmResourceMapper().queryLabelName(fieldName, scopeId,user.getLanguage()));
            weaTableColumn.setColumn(buildTableSql(columnName).replace(".", "_"));

            weaTableColumn.setDisplay(columnList.contains(columnName) ? WeaBoolAttr.TRUE : WeaBoolAttr.FALSE);
            weaTableColumn.setTransmethod("com.engine.organization.transmethod.HrmResourceTransMethod.getFieldTrueValue");
            weaTableColumn.setOtherpara(columnName);
            weaTableColumn.setWidth(decimal.setScale(2, RoundingMode.HALF_UP).doubleValue() + "%");
            weaTableColumnList.add(weaTableColumn);
        }

        // 增加id字段,跳转人员卡片
        WeaTableColumn weaTableColumn = new WeaTableColumn();
        weaTableColumn.setColumn("id");
        weaTableColumn.setDisplay(WeaBoolAttr.FALSE);

        weaTableColumnList.add(weaTableColumn);
        fields.add("t.id");
        table.setBackfields(StringUtils.join(fields, ","));
        table.setColumns(weaTableColumnList);
        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<>();
        apiDatas.put("condition", addGroups);
        return apiDatas;
    }

    private List<SearchConditionItem> filterByDomkey(List<SearchConditionItem> items, List<String> domkeys) {
        List<SearchConditionItem> tempResult = items.stream()
                .filter(item -> domkeys.contains(item.getDomkey()[0]))
                .collect(Collectors.toList());

        Map<String, SearchConditionItem> hashMap = new HashMap<>();
        for (SearchConditionItem item : tempResult) {
            String domkeyElement = item.getDomkey()[0];
            hashMap.put(domkeyElement, item);
        }
        List<SearchConditionItem> resultList = new ArrayList<>();

        for (String domkeyElement : domkeys) {
            SearchConditionItem item = hashMap.get(domkeyElement);
            if (item != null) {
                resultList.add(item);
            }
        }

        return resultList;
    }

    @Override
    public Long saveBaseForm(Map<String, Object> params) {
        return 0L;
    }

    @Override
    public Map<String, Object> getBaseForm(Map<String, Object> params) {
        return new HashMap<>();
    }

    @Override
    public int updateForm(Map<String, Object> params) {
        return 0;
    }

    @Override
    public Integer saveSearchTemplate(SearchTemplateParam params) {
        // 重复名称校验
        SearchTemplatePO searchTemplateByName = getHrmResourceMapper().getSearchTemplateByName(user.getUID(), params.getShowname());
        OrganizationAssert.isFalse("默认模板".equals(params.getShowname()) || null != searchTemplateByName, SystemEnv.getHtmlLabelName(547439,user.getLanguage()));
        SearchTemplatePO templatePO = buildSearchTemplateByFields(params.getFields());
        if (null == templatePO) {
            return -1;
        }
        templatePO.setName(params.getShowname());
        templatePO.setCreator(user.getUID());
        templatePO.setCreateTime(new Date());
        templatePO.setUpdateTime(new Date());
        getHrmResourceMapper().insertSearchTemplate(templatePO);
        return templatePO.getId();
    }

    @Override
    public void deleteSearchTemplate(Integer id) {
        getHrmResourceMapper().deleteSearchTemplate(id, user.getUID());
    }

    @Override
    public String getTemplateSelectKeys(Map<String, Object> params) {
        String templateId = Util.null2String(params.get("templateId"));
        templateId = StringUtils.isBlank(templateId) ? "-1" : templateId;
        String type = Util.null2String(params.get("type"));
        OrganizationAssert.isTrue(StringUtils.isNotBlank(templateId), SystemEnv.getHtmlLabelName(547440, user.getLanguage()));
        // 判断是否为搜索模板
        SearchTemplatePO searchTemplateById;
        List<String> selectKeys;
        if ("custom".equals(type)) {
            if ("-1".equals(templateId)) {
                selectKeys = Arrays.asList("-1_hrm_lastname,-1_hrm_departmentid,-1_hrm_jobtitle,-1_hrm_mobile,-1_hrm_telephone,-1_hrm_managerid".split(","));
            } else {
                searchTemplateById = getHrmResourceMapper().getCustomTemplateById(templateId);
                selectKeys = getSelectKeys(searchTemplateById);
            }
        } else {
            if ("-1".equals(templateId)) {
                selectKeys = getAllConditions().get(0).getItems().stream().map(item -> item.getDomkey()[0]).collect(Collectors.toList());
            } else {
                searchTemplateById = getHrmResourceMapper().getSearchTemplateById(templateId);
                selectKeys = getSelectKeys(searchTemplateById);
            }
        }

        return StringUtils.join(selectKeys, ",");
    }

    @Override
    public Map<String, Object> getSearchTemplate(Map<String, Object> params) {
        Map<String, Object> returnMap = new HashMap<>();
        String type = Util.null2String(params.get("type"));
        int userUID = user.getUID();
        // 根据ID查询所存储的模板
        List<SearchTemplateParam> templates;
        if ("custom".equals(type)) {
            templates = getHrmResourceMapper().getCustomTemplatesByUser(userUID);
            SearchTemplatePO usedCustomTemplate = getHrmResourceMapper().getUsedCustomTemplateByUser(user.getUID());
            if (null != usedCustomTemplate) {
                returnMap.put("templateId", usedCustomTemplate.getId().toString());
            } else {
                returnMap.put("templateId", "-1");
            }
        } else {
            templates = getHrmResourceMapper().getSearchTemplatesByUser(userUID);
        }
        templates.add(0, SearchTemplateParam.builder().key("-1").showname("默认模板").build());
        returnMap.put("templates", templates);
        return returnMap;
    }

    @Override
    public Integer saveCustomTemplate(SearchTemplateParam params) {
        // 重复名称校验
        SearchTemplatePO searchTemplateByName = getHrmResourceMapper().getCustomTemplateByName(user.getUID(), params.getShowname());
        OrganizationAssert.isFalse("默认模板".equals(params.getShowname()) || null != searchTemplateByName, SystemEnv.getHtmlLabelName(547439,user.getLanguage()));
        SearchTemplatePO templatePO = buildSearchTemplateByFields(params.getFields());
        if (null == templatePO) {
            return -1;
        }
        templatePO.setName(params.getShowname());
        templatePO.setCreator(user.getUID());
        templatePO.setIsused("0");
        templatePO.setCreateTime(new Date());
        templatePO.setUpdateTime(new Date());
        getHrmResourceMapper().insertCustomTemplate(templatePO);
        return templatePO.getId();
    }

    @Override
    public Integer updateCustomTemplate(Map<String, Object> params) {
        int rowNum = getIntValue((String) params.get("rownum"));
        int count = 0;
        List<Long> allIds = getJclOrgCustomTemplateMapper().listAllId();
        String currentDate = OrganizationDateUtil.getFormatLocalDate(new java.util.Date());
        List<String> nameList = new ArrayList<>();
        for (int i = 0; i < rowNum; i++) {
            String recordIndex = "_" + i;
            String name = Util.null2String(params.get("name" + recordIndex));
            if (StringUtils.isNotBlank(name)) {
                nameList.add(name);
            }
        }

        OrganizationAssert.isFalse(new HashSet<>(nameList).size() < nameList.size(), "模板名称不能重复");
        for (int i = 0; i < rowNum; i++) {
            String recordIndex = "_" + i;
            String id = Util.null2String(params.get("id" + recordIndex));
            String name = Util.null2String(params.get("name" + recordIndex));
            JclOrgCustomTemplatePO jclOrgCustomTemplatePO = new JclOrgCustomTemplatePO();
            if (StringUtils.isNotBlank(id)) {
                // 更新
                long jclId = Long.parseLong(id);
                jclOrgCustomTemplatePO = MapperProxyFactory.getProxy(JclOrgCustomTemplateMapper.class).selectByPrimaryKey(jclId);
                jclOrgCustomTemplatePO.setName(name);
                jclOrgCustomTemplatePO.setUpdateTime(new java.sql.Date(OrganizationDateUtil.stringToDate(currentDate).getTime()));
                count += MapperProxyFactory.getProxy(JclOrgCustomTemplateMapper.class).updateByPrimaryKey(jclOrgCustomTemplatePO);
                allIds.remove(jclId);
            } else {
                //插入
                OrganizationAssert.isFalse("".equals(name), SystemEnv.getHtmlLabelName(547442,user.getLanguage()));
                jclOrgCustomTemplatePO.setName(name);
                jclOrgCustomTemplatePO.setCreator(user.getUID());
                jclOrgCustomTemplatePO.setCreateTime(new java.sql.Date(OrganizationDateUtil.stringToDate(currentDate).getTime()));
                jclOrgCustomTemplatePO.setUpdateTime(new java.sql.Date(OrganizationDateUtil.stringToDate(currentDate).getTime()));
                count += MapperProxyFactory.getProxy(JclOrgCustomTemplateMapper.class).insert(jclOrgCustomTemplatePO);
            }
        }
        if (CollectionUtils.isNotEmpty(allIds)) {
            count += MapperProxyFactory.getProxy(JclOrgCustomTemplateMapper.class).deleteByIds(allIds);
        }
        return count;
    }

    @Override
    public void deleteCustomTemplate(Integer id) {
        getHrmResourceMapper().deleteCustomTemplate(id, user.getUID());
    }

    @Override
    public Map<String, Object> getCustomTransferData(Map<String, Object> params) {
        Map<String, Object> resultMap = new HashMap<>();
        String templateId = StringUtils.isNotBlank(Util.null2String(params.get("templateId"))) ? Util.null2String(params.get("templateId")) : "-1";
        List<TransferDataPO> transferDatas = new ArrayList<>();
        List<String> transferKeys;
        List<SearchTemplateParam> transferOptions = new ArrayList<>();
        List<SearchConditionGroup> allConditions = getAllConditions();
        AtomicInteger idx = new AtomicInteger(0);
        for (SearchConditionGroup allCondition : allConditions) {
            List<SearchConditionItem> items = allCondition.getItems();
            List<TransferDataPO> collect = items.stream().map(item -> TransferDataPO.builder().id(item.getDomkey()[0]).label(item.getLabel()).title(allCondition.getTitle()).idx(Integer.toString(idx.get())).build()).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                transferDatas.addAll(collect);
            }
            transferOptions.add(SearchTemplateParam.builder().key(Integer.toString(idx.getAndIncrement())).showname(allCondition.getTitle()).build());
        }
        if ("-1".equals(templateId)) {
            // 查询当前使用的模板，没有使用的，则展示默认模板
            SearchTemplatePO usedCustomTemplate = getHrmResourceMapper().getUsedCustomTemplateByUser(user.getUID());
            if (null == usedCustomTemplate) {
                String selectKeys = "-1_hrm_lastname,-1_hrm_departmentid,-1_hrm_jobtitle,-1_hrm_mobile,-1_hrm_telephone,-1_hrm_managerid";
                transferKeys = Arrays.asList(selectKeys.split(","));
            } else {
                transferKeys = getSelectKeys(usedCustomTemplate);
                templateId = usedCustomTemplate.getId().toString();
            }
        } else {
            SearchTemplatePO searchTemplateById = getHrmResourceMapper().getCustomTemplateById(templateId);
            transferKeys = getSelectKeys(searchTemplateById);
        }
        transferOptions.add(0, SearchTemplateParam.builder().key("").showname("").build());
        resultMap.put("transferDatas", transferDatas);
        resultMap.put("transferKeys", transferKeys);
        resultMap.put("transferOptions", transferOptions);
        resultMap.put("templateId", templateId);

        return resultMap;
    }

    @Override
    public Integer saveColumnsCustomTemplate(Map<String, Object> params) {
        String columns = Util.null2String(params.get("columns"));
        String templateId = Util.null2String(params.get("templateId"));
        SearchTemplatePO templatePO = buildSearchTemplateByFields(columns);
        JclOrgCustomTemplatePO jclOrgCustomTemplatePO = new JclOrgCustomTemplatePO();
        if (StringUtils.isNotBlank(templateId)) {
            if (templateId.equals("-1")) {
                getJclOrgCustomTemplateMapper().updateUsed("0", null, String.valueOf(user.getUID()));
            } else {
                jclOrgCustomTemplatePO = getJclOrgCustomTemplateMapper().selectByPrimaryKey(Long.parseLong(templateId));
                if (jclOrgCustomTemplatePO != null) {
                    jclOrgCustomTemplatePO.setId(Integer.valueOf(templateId));
                    jclOrgCustomTemplatePO.setBasicFields(templatePO.getBasicFields());
                    jclOrgCustomTemplatePO.setPersonalFields(templatePO.getPersonalFields());
                    jclOrgCustomTemplatePO.setWorkFields(templatePO.getWorkFields());
                    jclOrgCustomTemplatePO.setIsused(1);
                    //取消已启用模板
                    getJclOrgCustomTemplateMapper().updateUsed("0", null, String.valueOf(user.getUID()));
                    //启用当前模板
                    getJclOrgCustomTemplateMapper().updateByPrimaryKeySelective(jclOrgCustomTemplatePO);
                }
            }
        }
        return jclOrgCustomTemplatePO.getId();
    }

    @Override
    public Map<String, Object> chartResourceList(Integer departmentId, String versionId, String dimension) {
        Map<String, Object> dataMap = new HashMap<>();
        List<ResourceListColumns> resourceListColumns = getTableColumns();
        List<ResourceChartPO> resourceChartPOS = new ArrayList<>();
        List<ResourceChartVO> resourceChartVOS = new ArrayList<>();
        RecordSet rs = new RecordSet();
        if ("0".equals(dimension)) {
            if ("0".equals(versionId)) {
                //当前数据
                resourceChartPOS = getHrmResourceMapper().selectByDepartmentId(departmentId);
                resourceChartVOS = ResourceChartBO.convertToVO(resourceChartPOS);
            } else {
                rs.executeQuery("select resourceid,workcode,lastname,sex,department,subcompany,jobtitle,mobile from jcl_chart_resource where departmentid = ? and versionid = ?", departmentId, versionId);
                while (rs.next()) {
                    ResourceChartVO build = ResourceChartVO.builder()
                            .id((long) Util.getIntValue(rs.getString("resourceid")))
                            .workCode(Util.null2String(rs.getString("workcode")))
                            .lastName(Util.null2String(rs.getString("lastname")))
                            .sex("1".equals(Util.null2String(rs.getString("workcode"))) ? "女" : "男")
                            .departmentName(Util.null2String(rs.getString("department")))
                            .subcompanyName(Util.null2String(rs.getString("subcompany")))
                            .jobTitle(Util.null2String(rs.getString("jobtitle")))
                            .mobile(Util.null2String(rs.getString("mobile")))
                            .build();

                    resourceChartVOS.add(build);
                }
            }
        } else {
            rs.executeQuery("select h.id,h.workcode,h.lastname,h.sex,h.departmentid,h.subcompanyid1,h.jobtitle,h.status,h.mobile " +
                    "  from hrmresourcevirtual v inner join hrmresource h  on v.resourceid = h.id and v.virtualtype = ? and v.departmentid = ?", dimension, departmentId);
            while (rs.next()) {
                ResourceChartPO build = ResourceChartPO.builder()
                        .id((long) Util.getIntValue(rs.getString("id")))
                        .workCode(Util.null2String(rs.getString("workcode")))
                        .lastName(Util.null2String(rs.getString("lastname")))
                        .sex(Util.null2String(rs.getString("sex")))
                        .departmentId(Util.getIntValue(rs.getString("departmentid")))
                        .subcompanyid1(Util.getIntValue(rs.getString("subcompanyid1")))
                        .jobTitle(Util.getIntValue(rs.getString("jobtitle")))
                        .status(Util.getIntValue(rs.getString("status")))
                        .mobile(Util.null2String(rs.getString("mobile")))
                        .build();
                resourceChartPOS.add(build);
            }
            resourceChartVOS = ResourceChartBO.convertToVO(resourceChartPOS);
        }

        dataMap.put("columns", resourceListColumns);
        dataMap.put("dataSource", resourceChartVOS);
        return dataMap;
    }

    private List<ResourceListColumns> getTableColumns() {
        List<ResourceListColumns> list = new ArrayList<>();
        list.add(ResourceListColumns.builder().title("序号").dataIndex("id").key("id").build());
        list.add(ResourceListColumns.builder().title("工号").dataIndex("workCode").key("workCode").build());
        list.add(ResourceListColumns.builder().title("姓名").dataIndex("lastName").key("lastName").build());
        list.add(ResourceListColumns.builder().title("性别").dataIndex("sex").key("sex").build());
        list.add(ResourceListColumns.builder().title("部门").dataIndex("departmentName").key("departmentName").build());
        list.add(ResourceListColumns.builder().title("分部").dataIndex("subcompanyName").key("subcompanyName").build());
        list.add(ResourceListColumns.builder().title("岗位").dataIndex("jobTitle").key("jobTitle").build());
        //list.add(ResourceListColumns.builder().title("状态").dataIndex("status").key("status").build());
        list.add(ResourceListColumns.builder().title("手机号").dataIndex("mobile").key("mobile").build());

        return list;

    }

    @Override
    public Map<String, Object> getSearchCondition(Map<String, Object> params) {
        String templateId = Util.null2String(params.get("templateId"));
        String selectKeys = Util.null2String(params.get("selectKeys"));
        if (StringUtils.isBlank(templateId)) {
            templateId = "-1";
        }
        Map<String, Object> apiDatas = new HashMap<>();
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<SearchConditionGroup> allConditions = getAllConditions();
        // 穿梭框ID，展示所选字段信息
        HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo();
        if ("-1".equals(templateId)) {
            if (StringUtils.isNotBlank(selectKeys)) {
                SearchTemplatePO templatePO = buildSearchTemplateByFields(selectKeys);
                if (null != templatePO) {
                    buildSearchConditionGroup(templatePO, hrmFieldSearchConditionComInfo, addGroups);
                }
            } else {
                // 未选择模板展示默认模板搜索条件
                if (CollectionUtils.isNotEmpty(allConditions)) {
                    addGroups.add(allConditions.get(0));
                }
            }
        } else {
            // 选择模板则遍历所选模板所选字段
            SearchTemplatePO searchTemplateById = getHrmResourceMapper().getSearchTemplateById(templateId);
            buildSearchConditionGroup(searchTemplateById, hrmFieldSearchConditionComInfo, addGroups);
        }
        apiDatas.put("defaultcondition", addGroups);
        apiDatas.put("conditions", allConditions);
        return apiDatas;
    }

    @Override
    public Map<String, Object> getHasRight() {
        Map<String, Object> btnDatas = new HashMap<>();
        ArrayList<MenuBtn> topMenuList = new ArrayList<>();
        ArrayList<MenuBtn> rightMenuList = new ArrayList<>();
        if (HasRightUtil.hasRight(user, RIGHT_NAME, true)) {
            topMenuList.add(MenuBtn.builder().isBatch("1").isTop("1").menuFun("new").menuIcon("icon-coms-New-Flow").menuName(SystemEnv.getHtmlLabelName(547443,user.getLanguage())).type("BTN_Addnew").build());
            rightMenuList.add(MenuBtn.builder().isBatch("1").isTop("1").menuFun("new").menuIcon("icon-coms-New-Flow").menuName(SystemEnv.getHtmlLabelName(547443,user.getLanguage())).type("BTN_Addnew").build());
        }
        topMenuList.add(MenuBtn.builder().isBatch("1").isTop("1").menuFun("customization").menuIcon("icon-coms-task-list").menuName(SystemEnv.getHtmlLabelName(547136,user.getLanguage())).type("BTN_COLUMN").build());
        rightMenuList.add(MenuBtn.rightMenu_btnLog(user.getLanguage()));
        btnDatas.put("topMenu", topMenuList);
        btnDatas.put("rightMenu", rightMenuList);
        btnDatas.put("hasRight", true);
        return btnDatas;
    }

    @Override
    public Map<String, Object> getTabForm(Map<String, Object> params) {
        Map<String, Object> apiDatas = new HashMap<>();
        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();
    }

    @Override
    public Map<String, Object> getCustomTemplate(Map<String, Object> params) {
        List<ExtendInfoPO> infoPOList = new ArrayList<>();
        infoPOList.add(ExtendInfoPO.builder().viewAttr(2).id(null).fieldName("name").fieldNameDesc(SystemEnv.getHtmlLabelName(547580,user.getLanguage())).fieldType("varchar(255)").controlType(1).browserType("1").customValue("[\"input\",\"text\",\"50\"]").showOrder(1).isrequired(0).isSystemDefault(0).build());
        infoPOList.add(ExtendInfoPO.builder().viewAttr(1).id(null).fieldName("createTime").fieldNameDesc(SystemEnv.getHtmlLabelName(547521,user.getLanguage())).fieldType("date").controlType(1).browserType("1").customValue("[\"input\",\"text\",\"50\"]").showOrder(2).isrequired(0).isSystemDefault(0).build());
        Map<String, Object> tabInfoMap = new HashMap<>();
        tabInfoMap.put("columns", ExtendInfoBO.convertInfoListToTable(user, infoPOList, false, true));
        List<JclOrgCustomTemplatePO> jclOrgCustomTemplatePOS = MapperProxyFactory.getProxy(JclOrgCustomTemplateMapper.class).listAllByCreator(user.getUID());
        List<Integer> isUsed = new ArrayList<>();
        AtomicInteger index = new AtomicInteger(0);
        List<Map<String, Object>> collect = jclOrgCustomTemplatePOS.stream().map(item -> {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("id", item.getId());
            resultMap.put("name", item.getName());
            resultMap.put("createTime", DateUtil.getDate(item.getCreateTime(), "yyyy-MM-dd"));

            if (item.getIsused() != null) {

                if (1 == item.getIsused()) {
                    isUsed.add(index.get());
                }
                index.getAndIncrement();
            }

            return resultMap;
        }).collect(Collectors.toList());

        tabInfoMap.put("datas", collect);
        tabInfoMap.put("api_status", true);
        Map<String, List<Integer>> isUsedMap = new HashMap<>();
        isUsedMap.put("status", isUsed);
        tabInfoMap.put("selectedData", isUsedMap);
        tabInfoMap.put("isModalEdit", false);
        return tabInfoMap;
    }

    /**
     * 查询条件
     *
     * @param params
     * @return
     */
    private String buildSqlWhere(Map<String, Object> params) {
        HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo();
        List<SearchConditionItem> conditionItems = new ArrayList<>();
        List<CusFormFieldPO> hrmFieldsByScopeId = getSystemDataMapper().getHrmFieldsByScopeId(HrmGroupEnum.HRM_BASIC.getGroupType().toString());
        createConditionItems(hrmFieldSearchConditionComInfo, hrmFieldsByScopeId, conditionItems);
        hrmFieldsByScopeId = getSystemDataMapper().getHrmFieldsByScopeId(HrmGroupEnum.HRM_PERSONAL.getGroupType().toString());
        createConditionItems(hrmFieldSearchConditionComInfo, hrmFieldsByScopeId, conditionItems);
        hrmFieldsByScopeId = getSystemDataMapper().getHrmFieldsByScopeId(HrmGroupEnum.HRM_WORK.getGroupType().toString());
        createConditionItems(hrmFieldSearchConditionComInfo, hrmFieldsByScopeId, conditionItems);
        Map<String, SearchConditionItem> allFieldsMap = conditionItems.stream().collect(Collectors.toMap(item -> item.getDomkey()[0], item -> item, (k1, k2) -> k1));
        boolean isQuickSearch = "true".equals(Util.null2String(params.get("isQuickSearch")));

        DBType dbType = DBType.get(new RecordSet().getDBType());
        StringBuilder sb = new StringBuilder(" where 1=1 ");
        if (params.containsKey("lastName") || !params.containsKey("-1_hrm_status")) {
            // sb.append(" and t.status = 1");
            sb.append(" and t.status < 4");
        }
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = Util.null2String(entry.getValue());
            if (StringUtils.isBlank(value)) {
                continue;
            }
            if ("lastName".equals(key)) {
                sb.append(" and t.lastname ").append(dbType.like(value));
            }
            if ("companyId".equals(key)) {
                sb.append(" and t.subcompanyid1 ='").append(value).append("'");
            }
            if ("departmentId".equals(key)) {
                sb.append(" and t.departmentId ='").append(value).append("'");
            }
            if ("jobTitle".equals(key)) {
                JobPO jobById = getJobMapper().getJobById(Long.parseLong(value));
                if (null != jobById) {
                    sb.append(" and t.jobtitle ='").append(Util.null2String(jobById.getEcJobTitle())).append("' and t.subcompanyid1 = '").append(Util.null2String(jobById.getEcCompany())).append("' and t.departmentId ='").append(Util.null2String(jobById.getEcDepartment())).append("'");
                } else {
                    sb = new StringBuilder(" where 1 = 2 ");
                    break;
                }
            }

            SearchConditionItem searchConditionItem = allFieldsMap.get(key);
            // 根据不同的类型,不同的查询方式
            buildDynamicSql(searchConditionItem, key, value, sb, dbType, isQuickSearch, params);
        }
        if (searchJobTitle) {
            String jobTitleIds = StringUtils.join(jobTitleList, ",");
            sb.append(" and t.jobtitle in (").append(StringUtils.isNotBlank(jobTitleIds) ? jobTitleIds : "''").append(") ");
        }

        // 分权查询
        DetachUtil detachUtil = new DetachUtil(user);
        String parentCompanyIds = detachUtil.getJclRoleLevels();
        if (detachUtil.isDETACH()) {
            sb.append(" and t.subcompanyid1 in(").append(parentCompanyIds).append(")");
        }

        return sb.toString();
    }

    public 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();
            // 所属分部下的岗位
            JobPO jobBuild = JobPO.builder().jobTitleName(keyword).ecCompany(parentCompId).forbiddenTag(0).build();
            searchTree = buildTreeByCompAndDept(departmentBuild, compBuild, jobBuild);
        } else if (TYPE_DEPT.equals(type)) {
            Integer parentDeptId = Integer.parseInt(id);
            DepartmentPO departmentBuild = DepartmentPO.builder().departmentName(keyword).supDepId(parentDeptId).canceled(0).build();
            // 所属分部下的岗位
            JobPO jobBuild = JobPO.builder().jobTitleName(keyword).ecDepartment(parentDeptId).forbiddenTag(0).build();
            searchTree = buildTreeByDeptAndJob(departmentBuild, jobBuild);

        } else if (TYPE_JOB.equals(type)) {
            // 查询部门信息
            List<JobPO> filterJobs = getJobMapper().listPOsByFilter(JobPO.builder().jobTitleName(keyword).parentJob(Long.parseLong(id)).forbiddenTag(0).build());
            searchTree = SearchTreeUtil.builderTreeMode(JobBO.buildSetToSearchTree(filterJobs));
        }
        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).filterJobList(jobPOS);
        List<DepartmentPO> filterDeparts = getDepartmentMapper().listByFilter(departmentBuild, "showorder");
        new DetachUtil(user).filterDepartmentList(filterDeparts);
        // 添加岗位的上级部门或分部
        List<SearchTree> jobTrees = SearchTreeUtil.builderTreeMode(JobBO.buildSetToSearchTree(jobPOS));
        String parentDeptS = jobTrees.stream().map(SearchTree::getParentComp).collect(Collectors.joining(","));
        if (!StringUtil.isEmpty(parentDeptS)) {
            // 兼容SQLServer每次最多in,2100条数据
            List<Long> ids = 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, "showorder");
        new DetachUtil(user).filterCompanyList(filterComps);
        Set<DepartmentPO> builderDeparts = new HashSet<>();

        Map<Integer, DepartmentPO> departmentPOMap = getDepartmentMapper().listAll("showorder").stream().collect(Collectors.toMap(DepartmentPO::getId, item -> item));
        for (DepartmentPO departmentPO : filterDeparts) {
            buildParentDepts(departmentPO, builderDeparts, departmentPOMap);
        }
        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().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), searchTrees);
    }

    private List<SearchTree> buildTreeByDeptAndJob(DepartmentPO departmentBuild, JobPO jobBuild) {
        List<JobPO> jobPOS = getJobMapper().listPOsByFilter(jobBuild);
        List<DepartmentPO> filterDeparts = getDepartmentMapper().listByFilter(departmentBuild, "showorder");
        // 添加岗位的上级部门或分部
        List<SearchTree> jobTrees = SearchTreeUtil.builderTreeMode(JobBO.buildSetToSearchTree(jobPOS));
        String parentDeptS = jobTrees.stream().map(SearchTree::getParentComp).collect(Collectors.joining(","));
        if (!StringUtil.isEmpty(parentDeptS)) {
            // 兼容SQLServer每次最多in,2100条数据
            List<Long> ids = 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);
            }
        }
        Map<Integer, DepartmentPO> departmentPOMap = getDepartmentMapper().listAll("showorder").stream().collect(Collectors.toMap(DepartmentPO::getId, item -> item));

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

    /**
     * 添加查询元素的父级元素
     *
     * @param departmentPO
     * @param builderDeparts
     */
    private void buildParentDepts(DepartmentPO departmentPO, Set<DepartmentPO> builderDeparts, Map<Integer, DepartmentPO> departmentPOMap) {
        builderDeparts.add(departmentPO);
        if (SearchTreeUtil.isTop(departmentPO.getSupDepId())) {
            return;
        }
        DepartmentPO parentDept = departmentPOMap.get(departmentPO.getSupDepId());
        if (null != parentDept) {
            buildParentDepts(parentDept, builderDeparts, departmentPOMap);
        }
    }

    /**
     * 添加查询元素的父级元素
     *
     * @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) {
            buildParentComps(parentComp, builderComps, allMaps);
        }
    }


    /**
     * 获取所有搜索字段信息构建的高级搜索表单
     *
     * @return
     */
    public List<SearchConditionGroup> getAllConditions() {
        HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo();
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<SearchConditionItem> basicConditionItems = new ArrayList<>();
        List<SearchConditionItem> personalConditionItems = new ArrayList<>();
        List<SearchConditionItem> workConditionItems = new ArrayList<>();

        // 基本信息：-1
        List<CusFormFieldPO> hrmFieldsByScopeId = getSystemDataMapper().getHrmFieldsByScopeId(HrmGroupEnum.HRM_BASIC.getGroupType().toString());
        createConditionItems(hrmFieldSearchConditionComInfo, hrmFieldsByScopeId, basicConditionItems);
        if (CollectionUtils.isNotEmpty(basicConditionItems)) {
            addGroups.add(new SearchConditionGroup(SystemEnv.getHtmlLabelName(547175,user.getLanguage()), true, basicConditionItems));
        }

        // 个人信息：1
        hrmFieldsByScopeId = getSystemDataMapper().getHrmFieldsByScopeId(HrmGroupEnum.HRM_PERSONAL.getGroupType().toString());
        createConditionItems(hrmFieldSearchConditionComInfo, hrmFieldsByScopeId, personalConditionItems);
        if (CollectionUtils.isNotEmpty(personalConditionItems)) {
            addGroups.add(new SearchConditionGroup(SystemEnv.getHtmlLabelName(547578,user.getLanguage()), true, personalConditionItems));
        }

        // 工作信息：3
        hrmFieldsByScopeId = getSystemDataMapper().getHrmFieldsByScopeId(HrmGroupEnum.HRM_WORK.getGroupType().toString());
        createConditionItems(hrmFieldSearchConditionComInfo, hrmFieldsByScopeId, workConditionItems);
        if (CollectionUtils.isNotEmpty(workConditionItems)) {
            addGroups.add(new SearchConditionGroup(SystemEnv.getHtmlLabelName(547579,user.getLanguage()), true, workConditionItems));
        }
        return addGroups;
    }

    /**
     * 构建查询条件Item
     *
     * @param hrmFieldSearchConditionComInfo
     * @param formFields
     * @param conditionItems
     */
    private void createConditionItems(HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo, List<CusFormFieldPO> formFields, List<SearchConditionItem> conditionItems) {
        for (CusFormFieldPO cusFormFieldPO : formFields) {
            if ("jobactivity".equals(cusFormFieldPO.getFieldName())) {
                // 职务：282
                cusFormFieldPO.setType("282");
            }
            HrmFieldBean hrmFieldBean = new HrmFieldBean();
            hrmFieldBean.setFieldid(Util.null2String(cusFormFieldPO.getFieldId()));
            hrmFieldBean.setFieldname(cusFormFieldPO.getScopeId() + "_" + cusFormFieldPO.getTableName() + "_" + cusFormFieldPO.getFieldName());
            hrmFieldBean.setFieldlabel(cusFormFieldPO.getFieldLabel());
            hrmFieldBean.setFieldhtmltype(Util.null2String(cusFormFieldPO.getFieldHtmlType()));
            hrmFieldBean.setType(cusFormFieldPO.getType());
            hrmFieldBean.setIsQuickSearch(false);
            hrmFieldBean.setIsScope(false);
            hrmFieldBean.setDmlurl(cusFormFieldPO.getDmlUrl());
            hrmFieldBean.setIssystem("hrm".equals(cusFormFieldPO.getTableName()) ? "1" : "0");
            hrmFieldBean.setIsFormField(true);
            if ("-1_hrm_status".equals(hrmFieldBean.getFieldname())) {
                hrmFieldBean.setFieldvalue("1");
            }
            SearchConditionItem searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user);
            conditionItems.add(searchConditionItem);
            // 如果为下拉框,添加一条空选项
            if (searchConditionItem.getConditionType().equals(ConditionType.SELECT)) {
                addEmptyForSelect(searchConditionItem);
            }

        }
    }

    /**
     * 获取模板中的字段，构建搜索条件
     *
     * @param hrmFieldSearchConditionComInfo
     * @param addGroups
     * @param title
     * @param scopeid
     * @param fieldNames
     */
    private void getTemplateItems(HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo, List<SearchConditionGroup> addGroups, String title, Integer scopeid, String[] fieldNames) {
        try {

            HrmFieldManager hfm = new HrmFieldManager("HrmCustomFieldByInfoType", scopeid);
            List<SearchConditionItem> conditionItems = new ArrayList<>();
            for (String field : fieldNames) {
                String fieldName = field.substring(field.lastIndexOf("_") + 1);
                JSONObject hrmFieldConf = hfm.getHrmFieldConf(fieldName);
                if (null == hrmFieldConf) {
                    continue;
                }
                boolean baseField = hfm.isBaseField(fieldName);
                HrmFieldBean hrmFieldBean = new HrmFieldBean();
                hrmFieldBean.setFieldid(Util.null2String(hrmFieldConf.getString("id")));
                hrmFieldBean.setFieldname(scopeid + "_" + (baseField ? "hrm" : "cus") + "_" + fieldName);
                hrmFieldBean.setFieldlabel(hrmFieldConf.getString("fieldlabel"));
                hrmFieldBean.setFieldhtmltype(hrmFieldConf.getString("fieldhtmltype"));
                hrmFieldBean.setType(hrmFieldConf.getString("type"));
                hrmFieldBean.setDmlurl(hrmFieldConf.getString("dmlurl"));
                hrmFieldBean.setIssystem(baseField ? "1" : "0");
                hrmFieldBean.setIsFormField(true);
                hrmFieldBean.setIsQuickSearch(false);
                hrmFieldBean.setIsScope(false);
                if ("jobactivity".equals(fieldName)) {
                    // 职务：282
                    hrmFieldBean.setType("282");
                }
                SearchConditionItem searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user);
                conditionItems.add(searchConditionItem);
                // 如果为下拉框,添加一条空选项
                if (searchConditionItem.getConditionType().equals(ConditionType.SELECT)) {
                    addEmptyForSelect(searchConditionItem);
                }
            }
            if (CollectionUtils.isNotEmpty(conditionItems)) {
                addGroups.add(new SearchConditionGroup(title, true, conditionItems));
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据所选字段信息，构建搜素模板对象
     *
     * @param fields
     * @return
     */
    private SearchTemplatePO buildSearchTemplateByFields(String fields) {
        String[] split = fields.split(",");
        if (split.length > 0) {
            List<String> basicFields = new ArrayList<>();
            List<String> personalFields = new ArrayList<>();
            List<String> workFields = new ArrayList<>();
            for (String fieldName : split) {
                if (fieldName.startsWith(HrmGroupEnum.HRM_BASIC.getGroupType().toString())) {
                    basicFields.add(fieldName);
                } else if (fieldName.startsWith(HrmGroupEnum.HRM_PERSONAL.getGroupType().toString())) {
                    personalFields.add(fieldName);
                } else if (fieldName.startsWith(HrmGroupEnum.HRM_WORK.getGroupType().toString())) {
                    workFields.add(fieldName);
                }
            }
            return SearchTemplatePO.builder().basicFields(StringUtils.join(basicFields, ",")).personalFields(StringUtils.join(personalFields, ",")).workFields(StringUtils.join(workFields, ",")).build();
        }
        return null;
    }

    /**
     * 根据搜索模板对象，构建搜索条件表单
     *
     * @param templatePO
     * @param hrmFieldSearchConditionComInfo
     * @param addGroups
     */
    private void buildSearchConditionGroup(SearchTemplatePO templatePO, HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo, List<SearchConditionGroup> addGroups) {
        String[] basicFields = Util.null2String(templatePO.getBasicFields()).split(",");
        if (basicFields.length > 0) {
            getTemplateItems(hrmFieldSearchConditionComInfo, addGroups, SystemEnv.getHtmlLabelName(547175,user.getLanguage()), HrmGroupEnum.HRM_BASIC.getGroupType(), basicFields);
        }

        String[] personalFields = Util.null2String(templatePO.getPersonalFields()).split(",");
        if (personalFields.length > 0) {
            getTemplateItems(hrmFieldSearchConditionComInfo, addGroups, SystemEnv.getHtmlLabelName(547578,user.getLanguage()), HrmGroupEnum.HRM_PERSONAL.getGroupType(), personalFields);
        }
        String[] workFields = Util.null2String(templatePO.getWorkFields()).split(",");
        if (workFields.length > 0) {
            getTemplateItems(hrmFieldSearchConditionComInfo, addGroups, SystemEnv.getHtmlLabelName(547579,user.getLanguage()), HrmGroupEnum.HRM_WORK.getGroupType(), workFields);
        }
    }

    /**
     * 根据字段信息，动态拼接where条件SQL
     *
     * @param conditionItem
     * @param key
     * @param value
     * @param sb
     * @param dbType
     */
    private void buildDynamicSql(SearchConditionItem conditionItem, String key, String value, StringBuilder sb, DBType dbType, boolean isQuickSearch, Map<String, Object> params) {
        if (null == conditionItem) {
            return;
        }
        if (key.endsWith("workyear") || key.endsWith("companyworkyear")) {
            conditionItem.setConditionType(ConditionType.INPUTNUMBER);
        }
        // 职务
        if (key.endsWith("jobactivity")) {
            searchJobTitle = true;
            List<Integer> jobTitleIds = getSystemDataMapper().getJobTitleIds(value, null);
            if (null == jobTitleList) {
                jobTitleList = jobTitleIds;
            } else {
                jobTitleList.retainAll(jobTitleIds);
            }
            return;
        }
        // 职务类别
        if (key.endsWith("jobGroupId")) {
            searchJobTitle = true;
            List<Integer> jobTitleIds = getSystemDataMapper().getJobTitleIds(null, value);
            if (null == jobTitleList) {
                jobTitleList = jobTitleIds;
            } else {
                jobTitleList.retainAll(jobTitleIds);
            }
            return;
        }
        // 岗位
        if (key.endsWith("jobtitle")) {
            searchJobTitle = true;
            jobTitleList = new ArrayList<>();
            jobTitleList.add(Integer.parseInt(value));
            return;
        }
        String tableSql = buildTableSql(key);
        if (StringUtils.isBlank(tableSql)) {
            return;
        }
        switch (conditionItem.getConditionType()) {
            case INPUT:// 单行文本框
            case TEXTAREA:// 多行文本框
                if (isQuickSearch) {
                    if ("-1".equals(value)) {
                        break;
                    }
                    QuickSearchDetail quickSearchDetailById = getQuickSearchMapper().getQuickSearchDetailById(value);
                    Integer maxNum = quickSearchDetailById.getMaxNum();
                    Integer minNum = quickSearchDetailById.getMinNum();
                    sb.append(" and ").append(dbType.ifNull(tableSql, "0")).append(" >= ").append(minNum);
                    sb.append(" and ").append(dbType.ifNull(tableSql, "0")).append(" < ").append(maxNum);
                } else {
                    sb.append(" and ").append(tableSql).append(dbType.like(value));
                }
                // 模糊搜索
                break;

            case BROWSER://浏览按钮
                // 兼容多选浏览按钮
                sb.append(" and ").append(dbType.concat(tableSql)).append(dbType.like(value));
                break;

            case INPUTNUMBER:// 数字
                if (isQuickSearch) {
                    if ("-1".equals(value)) {
                        break;
                    }
                    QuickSearchDetail quickSearchDetailById = getQuickSearchMapper().getQuickSearchDetailById(value);
                    Integer maxNum = quickSearchDetailById.getMaxNum();
                    Integer minNum = quickSearchDetailById.getMinNum();
                    sb.append(" and ").append(dbType.ifNull(tableSql, "0")).append(" >= ").append(minNum);
                    sb.append(" and ").append(dbType.ifNull(tableSql, "0")).append(" < ").append(maxNum);
                } else {
                    sb.append(" and ").append(dbType.ifNull(tableSql, "0")).append(" = '").append(value).append("' ");
                }
                break;
            case CHECKBOX:
            case SWITCH:
                sb.append(" and ").append(dbType.ifNull(tableSql, "0")).append(" = '").append(value).append("' ");
                break;
            case SELECT://选择框
                if (!"-1".equals(value)) {
                    if ("t.status".equalsIgnoreCase(tableSql) && "10".equals(value)) {
                        sb.append(" and ").append(tableSql).append(" < 4 ");
                    } else {
                        sb.append(" and ").append(tableSql).append(" = '").append(value).append("' ");
                    }
                }
                break;
            case DATE:
            case DATEPICKER:
            case TIMEPICKER:
            case RANGEPICKER:
                if (isQuickSearch) {
                    if (StringUtils.isNotBlank(value) && !"-1".equals(value) && !"0,,".equals(value) && !"0".equals(value)) {
                        if (!"6".equals(value)) {
                            if ("1".equals(value)) {
                                sb.append(" and ").append(tableSql).append(" = '").append(OrganizationDateUtil.getFormatLocalDate(LocalDate.now())).append("'");
                            } else {
                                sb.append(" and ").append(tableSql).append(" >= '").append(TimeUtil.getDateByOption(value, "0")).append(" 00:00:00'");
                                sb.append(" and ").append(tableSql).append(" <= '").append(TimeUtil.getDateByOption(value, "")).append(" 23:59:59'");
                            }

                        } else {
                            String startDate = Util.null2String(params.get(key + "_start"));
                            String endDate = Util.null2String(params.get(key + "_end"));
                            if (StringUtils.isNotBlank(startDate)) {
                                sb.append(" and ").append(tableSql).append(" >= '").append(startDate).append("' ");

                            }
                            if (StringUtils.isNotBlank(endDate)) {
                                sb.append(" and ").append(tableSql).append(" <= '").append(endDate).append("' ");
                            }
                        }
                    }
                } else {
                    // 精准搜索
                    sb.append(" and ").append(tableSql).append(" = '").append(value).append("' ");
                }
                break;
            default:
                break;
        }
    }

    /**
     * 处理当前字段所在表关系
     *
     * @param key
     * @return
     */
    public String buildTableSql(String key) {
        StringBuilder sb = new StringBuilder();
        String[] s = key.split("_");
        if (s.length < 3) {
            return "";
        }

        String scopeId = s[0];
        String tableName = s[1];
        String fieldName = s[2];

        if ("jobactivity".equalsIgnoreCase(fieldName)) {
            return "t4.id";
        }
        if ("jobGroupId".equalsIgnoreCase(fieldName)) {
            return "t5.id";
        }
        // 姓名点击事件
        if ("lastname".equalsIgnoreCase(fieldName)) {
            return "lastname";
        }

        if ("hrm".equals(tableName)) {
            return sb.append("t.").append(fieldName).toString();
        }

        switch (scopeId) {
            case "-1":
                sb.append("t0.").append(fieldName);
                break;
            case "1":
                sb.append("t1.").append(fieldName);
                break;
            case "3":
                sb.append("t2.").append(fieldName);
                break;
            default:
                return "";
        }
        return sb.toString();
    }

    /**
     * 为下拉框搜索条件、添加空选项
     *
     * @param searchConditionItem
     */
    private void addEmptyForSelect(SearchConditionItem searchConditionItem) {
        searchConditionItem.setValue("-1");
        if ("-1_hrm_status".equals(searchConditionItem.getDomkey()[0])) {
            // 默认赋值 在职状态
            searchConditionItem.setValue("10");
        }
        List<SearchConditionOption> options = searchConditionItem.getOptions();
        SearchConditionOption searchConditionOption = new SearchConditionOption();
        searchConditionOption.setKey("-1");
        searchConditionOption.setShowname(SystemEnv.getHtmlLabelName(547191,user.getLanguage()));
        options.add(0, searchConditionOption);
        options.forEach(item -> item.setSelected(false));
    }

    /**
     * 根据模板示例，组装所有selectKeys
     *
     * @param searchTemplatePO
     * @return
     */
    public List<String> getSelectKeys(SearchTemplatePO searchTemplatePO) {
        List<String> selectKeys = new ArrayList<>();
        String basicFields = searchTemplatePO.getBasicFields();
        String personalFields = searchTemplatePO.getPersonalFields();
        String workflowFields = searchTemplatePO.getWorkFields();
        if (StringUtils.isNotBlank(basicFields)) {
            selectKeys.addAll(Arrays.asList(basicFields.split(",")));
        }
        if (StringUtils.isNotBlank(personalFields)) {
            selectKeys.addAll(Arrays.asList(personalFields.split(",")));
        }
        if (StringUtils.isNotBlank(workflowFields)) {
            selectKeys.addAll(Arrays.asList(workflowFields.split(",")));
        }
        return selectKeys;
    }

}
