package com.engine.organization.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.browser.bean.SearchConditionItem;
import com.api.browser.bean.SearchConditionOption;
import com.api.browser.util.ConditionFactory;
import com.api.browser.util.ConditionType;
import com.cloudstore.eccom.result.WeaResultMsg;
import com.engine.core.impl.Service;
import com.engine.hrm.entity.FieldSelectOptionBean;
import com.engine.organization.component.OrganizationWeaTable;
import com.engine.organization.entity.SelectOptionParam;
import com.engine.organization.entity.commom.RecordInfo;
import com.engine.organization.entity.extend.ExtendInfoOperateType;
import com.engine.organization.entity.extend.param.ExtendInfoParams;
import com.engine.organization.entity.extend.po.ExtendInfoPO;
import com.engine.organization.entity.fieldset.param.FieldTransferParam;
import com.engine.organization.entity.jclimport.po.CusFormFieldPO;
import com.engine.organization.entity.jclimport.po.JclImportHistoryDetailPO;
import com.engine.organization.entity.jclimport.po.JclImportHistoryPO;
import com.engine.organization.entity.jclimport.vo.JclImportHistoryDetailVO;
import com.engine.organization.enums.LogModuleNameEnum;
import com.engine.organization.enums.OperateTypeEnum;
import com.engine.organization.mapper.comp.CompMapper;
import com.engine.organization.mapper.department.DepartmentMapper;
import com.engine.organization.mapper.extend.ExtMapper;
import com.engine.organization.mapper.extend.ExtendInfoMapper;
import com.engine.organization.mapper.hrmresource.SystemDataMapper;
import com.engine.organization.mapper.jclimport.JclImportHistoryDetailMapper;
import com.engine.organization.mapper.jclimport.JclImportHistoryMapper;
import com.engine.organization.mapper.job.JobMapper;
import com.engine.organization.service.ImportCommonService;
import com.engine.organization.thread.CompanyTriggerRunnable;
import com.engine.organization.thread.DepartmentTriggerRunnable;
import com.engine.organization.thread.JobTriggerRunnable;
import com.engine.organization.thread.OrganizationSyncEc;
import com.engine.organization.util.HasRightUtil;
import com.engine.organization.util.OrganizationAssert;
import com.engine.organization.util.db.MapperProxyFactory;
import com.engine.organization.util.excel.ExcelUtil;
import com.engine.organization.util.relation.EcHrmRelationUtil;
import com.engine.organization.util.saveimport.hrmimport.HrmImportAdaptExcelE9;
import com.engine.organization.util.saveimport.hrmimport.HrmImportProcessE9;
import com.orgimport.service.OrgImportEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import weaver.common.DateUtil;
import weaver.file.FileUploadToPath;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.hrm.definedfield.HrmFieldManager;
import weaver.join.hrm.in.HrmResourceVo;
import weaver.systeminfo.SystemEnv;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author:dxfeng
 * @createTime: 2022/06/29
 * @version: 1.0
 */
public class ImportCommonServiceImpl extends Service implements ImportCommonService {
    /**
     * extend_group
     */
    private static final Long COMPANY_TYPE = 1L;
    private static final Long DEPARTMENT_TYPE = 2L;
    private static final Long JOB_TYPE = 3L;

    private static final String RIGHT_NAME = "DataImport:All";
    private static final String HRM_COMPANY = "hrmsubcompany";
    private static final String HRM_DEPARTMENT = "hrmdepartment";


    private ExtendInfoMapper getExtendInfoMapper() {
        return MapperProxyFactory.getProxy(ExtendInfoMapper.class);
    }

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

    @Override
    public Map<String, Object> getImportFields(String importType) {
        String extendType = "";
        String tableName = "";
        String errorMsg = "";
        List<String> excludeFields = new ArrayList<>();
        Map<String, Object> returnMaps = new HashMap<>();
        if (StringUtils.isNotBlank(importType)) {
            switch (importType) {
                case "company":
                    extendType = "1";
                    tableName = "JCL_ORG_COMP";
                    excludeFields.add("parent_company");
                    excludeFields.add("ec_company");
                    break;
                case "department":
                    extendType = "2";
                    tableName = "JCL_ORG_DEPT";
                    excludeFields.add("parent_dept");
                    excludeFields.add("ec_department");
                    break;
                case "jobtitle":
                    extendType = "3";
                    tableName = "JCL_ORG_JOB";
                    excludeFields.add("parent_job");
                    break;
                case "resource":
                    extendType = "4";
                    tableName = "hrmResource";
                    break;
                default:
                    errorMsg = "未找到对应的导入类型，请确认";
                    break;
            }
        } else {
            errorMsg = "请选择导入类型";
        }
        OrganizationAssert.isBlank(errorMsg, errorMsg);
        if (StringUtils.isAnyEmpty(extendType, tableName)) {
            return returnMaps;
        }
        if ("4".equals(extendType)) {
            String voField = "subcompanyid1,departmentid," +
                    "workcode,lastname,loginid,password,seclevel,sex," +
                    // "jobtitle,jobactivity,jobgroupid,jobcall,joblevel," +
                    "jobactivitydesc,managerid,assistantid,status," +
                    "workroom,locationid,telephone,mobile,mobilecall," +
                    "fax,email,systemlanguage,birthday,folk," +
                    "nativeplace,regresidentplace,certificatenum," +
                    "maritalstatus,policy,bememberdate,bepartydate," +
                    "islabouunion,educationlevel,degree,healthinfo,height," +
                    "weight,usekind,startdate,enddate,probationenddate," +
                    "residentplace,homeaddress,tempresidentnumber," +
                    "companystartdate,workstartdate," +
                    "accumfundaccount,accounttype,belongto,height,weight,accountname,bankid1,accountid1," +
                    "telephone,dsporder,classification";
            Collection<String> hrmFields = Arrays.asList(voField.split(","));
            // 获取人员表单字段
            List<CusFormFieldPO> hrmFieldBeanList = getSystemDataMapper().getHrmFieldBeanListByFields(hrmFields);
            List<CusFormFieldPO> customFieldList = getSystemDataMapper().getHrmCustomFieldList();
            List<CusFormFieldPO> mergeList = new ArrayList<>();
            mergeList.addAll(hrmFieldBeanList);
            mergeList.addAll(customFieldList);

            List<FieldTransferParam> fieldDatas = mergeList.stream().map(item -> FieldTransferParam.builder().id(item.getScopeId() + item.getTableName() + item.getFieldId()).name(item.getFieldLabel()).build()).collect(Collectors.toList());
            List<String> selectedKeys = mergeList.stream().filter(item -> ("1".equals(item.getRequired()) || "workcode".equals(item.getFieldName()) || "subcompanyid1".equals(item.getFieldName()) || "departmentid".equals(item.getFieldName()))).map(item -> item.getScopeId() + item.getTableName() + item.getFieldId()).collect(Collectors.toList());

            returnMaps.put("data", fieldDatas);
            returnMaps.put("selectedKeys", selectedKeys);
        } else {
            List<ExtendInfoPO> infoPOList = getExtendInfoMapper().listFields(extendType, "", tableName, ExtendInfoOperateType.LIST.getValue(), "1");
            List<ExtendInfoPO> filterList = infoPOList.stream().filter(item -> !excludeFields.contains(item.getFieldName()) && 6 != item.getControlType()).collect(Collectors.toList());
            List<FieldTransferParam> fieldDatas = filterList.stream().map(item -> FieldTransferParam.builder().id(item.getId().toString()).name(item.getFieldNameDesc()).build()).collect(Collectors.toList());
            List<String> selectedKeys = filterList.stream().filter(item -> (0 == item.getIsSystemDefault()) && 1 == item.getIsrequired()).map(item -> item.getId().toString()).collect(Collectors.toList());
            returnMaps.put("data", fieldDatas);
            returnMaps.put("selectedKeys", selectedKeys);
        }
        return returnMaps;
    }

    @Override
    public Map<String, Object> getImportForm(String importType, String columns) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            if (StringUtils.isNotBlank(importType)) {
                String templatePath = getTemplatePath(importType, columns);
                switch (importType) {
                    case "company":
                        returnMap.put("condition", getCompanyImportForm(templatePath));
                        break;
                    case "department":
                        returnMap.put("condition", getDepartmentImportForm(templatePath));
                        break;
                    case "jobtitle":
                        returnMap.put("condition", getJobTitleImportForm(templatePath));
                        break;
                    case "resource":
                        returnMap.put("condition", getResourceImportForm(templatePath));
                        break;
                    default:
                        returnMap.put("status", "-1");
                        returnMap.put("message", "请选择合适的导入类型");
                        return returnMap;
                }
            }
            returnMap.put("status", "1");
        } catch (IOException e) {
            returnMap.put("status", "-1");
            returnMap.put("message", "导入模板生成异常");
            new BaseBean().writeLog(e);
        }
        return returnMap;
    }

    @Override
    public Map<String, Object> saveImport(Map<String, Object> params, HttpServletRequest request) {
        String importType = (String) params.get("importType");
        String operateType = (String) params.get("operateType");
        String excelFile = (String) params.get("excelfile");
        Map<String, Object> returnMap = new HashMap<>();
        if (StringUtils.isNotBlank(importType)) {
            switch (importType) {
                case "company":
                    returnMap.put("pId", companyImport(operateType, excelFile));
                    break;
                case "department":
                    returnMap.put("pId", departmentImport(operateType, excelFile));
                    break;
                case "jobtitle":
                    returnMap.put("pId", jobImport(operateType, excelFile));
                    break;
                case "resource":
                    Long importHistoryId = saveImportLog("resource", operateType);
                    List<Object> lsErrorInfo = new ArrayList<>();
                    HrmImportAdaptExcelE9 importAdapt = new HrmImportAdaptExcelE9();
                    FileUploadToPath fu = new FileUploadToPath(request);

                    List errorInfo = importAdapt.creatImportMap(fu);

                    //如果读取数据和验证模板没有发生错误
                    if (errorInfo.isEmpty()) {
                        Map<String, HrmResourceVo> hrMap = importAdapt.getHrmImportMap();

                        HrmImportProcessE9 importProcess = new HrmImportProcessE9();
                        importProcess.init(request, importHistoryId);


                        importProcess.processMap(hrMap);
                    } else {
                        Map<String, Object> error;
                        for (int i = 0; i < errorInfo.size(); i++) {
                            error = new HashMap<>();
                            error.put("message", Util.null2String(errorInfo.get(i)));
                            lsErrorInfo.add(error);
                            MapperProxyFactory.getProxy(JclImportHistoryDetailMapper.class).insertHistoryDetail(JclImportHistoryDetailPO.builder().pid(importHistoryId).operateDetail(Util.null2String(errorInfo.get(i))).status("0").build());
                        }
                    }
                    returnMap.put("pId", importHistoryId);
                    break;
                default:
                    break;
            }
        }

        // 列表
        // importstatus
        return returnMap;
    }

    @Override
    public Map<String, Object> getImportResult(Map<String, Object> params) {
        String pId = (String) params.get("pId");
        // 刷新引用状态
        OrganizationWeaTable<JclImportHistoryDetailVO> table = new OrganizationWeaTable<>(user, JclImportHistoryDetailVO.class);
        String sqlWhere = " where status = '0' and pId = '" + pId + "'";
        table.setSqlwhere(sqlWhere);
        WeaResultMsg result = new WeaResultMsg(false);
        result.putAll(table.makeDataResult());
        result.success();
        Map<String, Object> resultMap = new HashMap<>(result.getResultMap());
        resultMap.put("importStatus", "over");
        resultMap.put("succnum", MapperProxyFactory.getProxy(JclImportHistoryDetailMapper.class).countRows("1", pId));
        resultMap.put("failnum", MapperProxyFactory.getProxy(JclImportHistoryDetailMapper.class).countRows("0", pId));
        return resultMap;
    }

    @Override
    public Map<String, Object> getHasRight() {
        Map<String, Object> returnMap = new HashMap<>();
        boolean hasRight = HasRightUtil.hasRight(user, RIGHT_NAME, true);
        returnMap.put("hasRight", hasRight);
        return returnMap;
    }

    @Override
    public Map<String, Object> saveCommonImport(Map<String, Object> params) {
        String importModule = Util.null2String(params.get("importModule"));
        OrgImportEnum orgImport = OrgImportEnum.getOrgImportUtil(importModule);
        return orgImport.orgImport(params, user);
    }

    @Override
    public Map<String, Object> getCommonForm(String importModule) {
        Map<String, Object> returnMap = new HashMap<>();
        OrgImportEnum orgImport = OrgImportEnum.getOrgImportUtil(importModule);
        returnMap.put("condition", orgImport.orgForm(user));
        returnMap.put("status", "1");
        return returnMap;
    }


    /**
     * 分部导入表单
     */
    private List<Object> getCompanyImportForm(String templatePath) throws IOException {


        // 返回导入数据
        List<Object> lsGroup = new ArrayList<>();
        Map<String, Object> groupItem = new HashMap<>();
        List<Object> itemList = new ArrayList<>();

        groupItem.put("title", SystemEnv.getHtmlLabelName(1361, user.getLanguage()));
        groupItem.put("defaultshow", true);

        SearchConditionItem searchConditionItem;
        ConditionFactory conditionFactory = new ConditionFactory(user);
        //导入类型
        List<SearchConditionOption> statusOptions = new ArrayList<>();
        statusOptions.add(new SearchConditionOption("add", SystemEnv.getHtmlLabelName(611, user.getLanguage()), true));
        statusOptions.add(new SearchConditionOption("update", SystemEnv.getHtmlLabelName(17744, user.getLanguage())));
        searchConditionItem = conditionFactory.createCondition(ConditionType.SELECT, 24863, "importType", statusOptions);
        searchConditionItem.setValue("add");
        itemList.add(searchConditionItem);

        //模板文件
        searchConditionItem = conditionFactory.createCondition(ConditionType.INPUT, 28576, "templet");
        searchConditionItem.setValue(templatePath);
        itemList.add(searchConditionItem);

        //Excel文件
        searchConditionItem = conditionFactory.createCondition(ConditionType.RESOURCEIMG, 16630, "excelfile");
        itemList.add(searchConditionItem);

        groupItem.put("items", itemList);
        lsGroup.add(groupItem);


        itemList = new ArrayList<>();
        groupItem = new HashMap<>();
        groupItem.put("title", SystemEnv.getHtmlLabelName(33803, Util.getIntValue(user.getLanguage())));
        groupItem.put("defaultshow", true);
        List<Integer> lsPromptLabel = new ArrayList<>(); //提示信息
        lsPromptLabel.add(34275);
        lsPromptLabel.add(125452);
        lsPromptLabel.add(125466);
        lsPromptLabel.add(522355);
        lsPromptLabel.add(522356);
        lsPromptLabel.add(522357);
        //lsPromptLabel.add(530411);

        for (int i = 0; i < lsPromptLabel.size(); i++) {
            Map<String, Object> item = new HashMap<>();
            item.put("index", (i + 1));
            String value = Util.toScreen(SystemEnv.getHtmlLabelName(lsPromptLabel.get(i), user.getLanguage()), user.getLanguage());
            if (i == 0) {
                value += SystemEnv.getHtmlLabelName(28576, user.getLanguage());
                item.put("link", templatePath);
            }
            item.put("value", value);
            itemList.add(item);
        }
        groupItem.put("items", itemList);
        lsGroup.add(groupItem);
        return lsGroup;
    }

    private List<Object> getDepartmentImportForm(String templatePath) throws IOException {

        // 返回导入数据
        List<Object> lsGroup = new ArrayList<>();
        Map<String, Object> groupItem = new HashMap<>();
        List<Object> itemList = new ArrayList<>();

        groupItem.put("title", SystemEnv.getHtmlLabelName(1361, user.getLanguage()));
        groupItem.put("defaultshow", true);

        SearchConditionItem searchConditionItem;
        ConditionFactory conditionFactory = new ConditionFactory(user);
        //导入类型
        List<SearchConditionOption> statusOptions = new ArrayList<>();
        statusOptions.add(new SearchConditionOption("add", SystemEnv.getHtmlLabelName(611, user.getLanguage()), true));
        statusOptions.add(new SearchConditionOption("update", SystemEnv.getHtmlLabelName(17744, user.getLanguage())));
        searchConditionItem = conditionFactory.createCondition(ConditionType.SELECT, 24863, "importType", statusOptions);
        searchConditionItem.setValue("add");
        itemList.add(searchConditionItem);

        //模板文件
        searchConditionItem = conditionFactory.createCondition(ConditionType.INPUT, 28576, "templet");
        searchConditionItem.setValue(templatePath);
        itemList.add(searchConditionItem);

        //Excel文件
        searchConditionItem = conditionFactory.createCondition(ConditionType.RESOURCEIMG, 16630, "excelfile");
        itemList.add(searchConditionItem);

        groupItem.put("items", itemList);
        lsGroup.add(groupItem);


        itemList = new ArrayList<>();
        groupItem = new HashMap<>();
        groupItem.put("title", SystemEnv.getHtmlLabelName(33803, Util.getIntValue(user.getLanguage())));
        groupItem.put("defaultshow", true);
        List<Integer> lsPromptLabel = new ArrayList<>(); //提示信息
        lsPromptLabel.add(34275);
        lsPromptLabel.add(125452);
        lsPromptLabel.add(125466);
        lsPromptLabel.add(522355);
        lsPromptLabel.add(522356);
        lsPromptLabel.add(522357);
        //lsPromptLabel.add(530411);

        for (int i = 0; i < lsPromptLabel.size(); i++) {
            Map<String, Object> item = new HashMap<>();
            item.put("index", (i + 1));
            String value = Util.toScreen(SystemEnv.getHtmlLabelName(lsPromptLabel.get(i), user.getLanguage()), user.getLanguage());
            if (i == 0) {
                value += SystemEnv.getHtmlLabelName(28576, user.getLanguage());
                item.put("link", templatePath);
            }
            item.put("value", value);
            itemList.add(item);
        }
        groupItem.put("items", itemList);
        lsGroup.add(groupItem);
        return lsGroup;
    }

    private List<Object> getJobTitleImportForm(String templatePath) throws IOException {

        // 返回导入数据
        List<Object> lsGroup = new ArrayList<>();
        Map<String, Object> groupItem = new HashMap<>();
        List<Object> itemList = new ArrayList<>();

        groupItem.put("title", SystemEnv.getHtmlLabelName(1361, user.getLanguage()));
        groupItem.put("defaultshow", true);

        SearchConditionItem searchConditionItem;
        ConditionFactory conditionFactory = new ConditionFactory(user);

        //导入类型
        List<SearchConditionOption> statusOptions = new ArrayList<>();
        statusOptions.add(new SearchConditionOption("add", SystemEnv.getHtmlLabelName(611, user.getLanguage()), true));
        statusOptions.add(new SearchConditionOption("update", SystemEnv.getHtmlLabelName(17744, user.getLanguage())));
        searchConditionItem = conditionFactory.createCondition(ConditionType.SELECT, 24863, "importType", statusOptions);
        searchConditionItem.setValue("add");
        itemList.add(searchConditionItem);

        //模板文件
        searchConditionItem = conditionFactory.createCondition(ConditionType.INPUT, 28576, "templet");
        searchConditionItem.setValue(templatePath);
        itemList.add(searchConditionItem);

        //Excel文件
        searchConditionItem = conditionFactory.createCondition(ConditionType.RESOURCEIMG, 16630, "excelfile");
        itemList.add(searchConditionItem);

        groupItem.put("items", itemList);
        lsGroup.add(groupItem);


        itemList = new ArrayList<>();
        groupItem = new HashMap<>();
        groupItem.put("title", SystemEnv.getHtmlLabelName(33803, Util.getIntValue(user.getLanguage())));
        groupItem.put("defaultshow", true);
        List<Integer> lsPromptLabel = new ArrayList<>(); //提示信息
        lsPromptLabel.add(34275);
        lsPromptLabel.add(125452);

        for (int i = 0; i < lsPromptLabel.size(); i++) {
            Map<String, Object> item = new HashMap<>();
            item.put("index", (i + 1));
            String value = Util.toScreen(SystemEnv.getHtmlLabelName(lsPromptLabel.get(i), user.getLanguage()), user.getLanguage());
            if (i == 0) {
                value += SystemEnv.getHtmlLabelName(28576, user.getLanguage());
                item.put("link", templatePath);
            }
            item.put("value", value);
            itemList.add(item);
        }
        groupItem.put("items", itemList);
        lsGroup.add(groupItem);
        return lsGroup;
    }

    private List<Object> getResourceImportForm(String templatePath) throws IOException {

        // 返回导入数据
        List<Object> lsGroup = new ArrayList<>();
        Map<String, Object> groupItem = new HashMap<>();
        List<Object> itemList = new ArrayList<>();

        groupItem.put("title", SystemEnv.getHtmlLabelName(1361, user.getLanguage()));
        groupItem.put("defaultshow", true);

        SearchConditionItem searchConditionItem;
        ConditionFactory conditionFactory = new ConditionFactory(user);

        //重复验证字段
        List<SearchConditionOption> statusOptions = new ArrayList<SearchConditionOption>();
        statusOptions.add(new SearchConditionOption("workcode", SystemEnv.getHtmlLabelName(714, user.getLanguage()), true));
        statusOptions.add(new SearchConditionOption("loginid", SystemEnv.getHtmlLabelName(412, user.getLanguage())));
        statusOptions.add(new SearchConditionOption("lastname", SystemEnv.getHtmlLabelName(413, user.getLanguage())));
        searchConditionItem = conditionFactory.createCondition(ConditionType.SELECT, 24638, "keyField", statusOptions);
        searchConditionItem.setValue("workcode");
        itemList.add(searchConditionItem);

        //导入类型
        List<SearchConditionOption> statusOptions1 = new ArrayList<SearchConditionOption>();
        statusOptions1.add(new SearchConditionOption("add", SystemEnv.getHtmlLabelName(611, user.getLanguage()), true));
        statusOptions1.add(new SearchConditionOption("update", SystemEnv.getHtmlLabelName(17744, user.getLanguage())));
        searchConditionItem = conditionFactory.createCondition(ConditionType.SELECT, 24863, "importType", statusOptions1);
        searchConditionItem.setValue("add");
        itemList.add(searchConditionItem);

        //模板文件
        searchConditionItem = conditionFactory.createCondition(ConditionType.INPUT, 28576, "templet");
        searchConditionItem.setValue(templatePath);
        itemList.add(searchConditionItem);

        //Excel文件
        searchConditionItem = conditionFactory.createCondition(ConditionType.RESOURCEIMG, 16630, "excelfile");
        itemList.add(searchConditionItem);

        groupItem.put("items", itemList);
        lsGroup.add(groupItem);


        itemList = new ArrayList<>();
        groupItem = new HashMap<>();
        groupItem.put("title", SystemEnv.getHtmlLabelName(33803, Util.getIntValue(user.getLanguage())));
        groupItem.put("defaultshow", true);
        List<Integer> lsPromptLabel = new ArrayList<>(); //提示信息
        lsPromptLabel.add(128520);
        lsPromptLabel.add(125868);
        lsPromptLabel.add(128365);
        lsPromptLabel.add(81697);
        lsPromptLabel.add(81698);
        lsPromptLabel.add(81699);
        lsPromptLabel.add(516263);
        lsPromptLabel.add(81701);
        lsPromptLabel.add(388880);
        lsPromptLabel.add(81702);
        lsPromptLabel.add(81703);
        lsPromptLabel.add(125869);

        for (int i = 0; i < lsPromptLabel.size(); i++) {
            Map<String, Object> item = new HashMap<>();
            item.put("index", (i + 1));
            String value = Util.toScreen(SystemEnv.getHtmlLabelName(lsPromptLabel.get(i), user.getLanguage()), user.getLanguage());
            if (i == 0) {
                value += SystemEnv.getHtmlLabelName(28576, user.getLanguage());
                item.put("link", templatePath);
            }
            item.put("value", value);
            itemList.add(item);
        }
        groupItem.put("items", itemList);
        lsGroup.add(groupItem);
        return lsGroup;
    }


    /**
     * 导入分部
     */
    private Long companyImport(String operateType, String excelFile) {
        Long importHistoryId = saveImportLog("company", operateType);
        JclImportHistoryDetailPO historyDetailPO;

        ImageFileManager manager = new ImageFileManager();
        manager.getImageFileInfoById(Util.getIntValue(excelFile));
        XSSFWorkbook workbook;
        try {
            workbook = new XSSFWorkbook(manager.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 当前sheet
        XSSFSheet sheetAt = workbook.getSheetAt(0);
        int lastRow = sheetAt.getLastRowNum();
        List<ExtendInfoPO> extendInfoPOS = new ArrayList<>();
        OrganizationAssert.isTrue(lastRow > 0, "导入数据为空");
        short lastCellNum = sheetAt.getRow(0).getLastCellNum();


        // 遍历每一行数据
        nextRow:
        for (int i = 0; i <= lastRow; i++) {
            historyDetailPO = new JclImportHistoryDetailPO();
            historyDetailPO.setPid(importHistoryId);
            XSSFRow row = sheetAt.getRow(i);
            // 组装待处理数据
            Map<String, Object> map = new HashMap<>();
            Long parentCompanyId = null;
            String companyName = "";

            historyDetailPO.setRowNums(String.valueOf(i + 1));
            for (int cellIndex = 0; cellIndex < lastCellNum; cellIndex++) {
                XSSFCell cell = row.getCell((short) cellIndex);
                String cellValue = getCellValue(cell).trim();
                if (i == 0) {
                    // 首行 初始化字段信息
                    ExtendInfoPO extendInfoPO = getExtendInfoMapper().getInfoByExtendAndLabelName(COMPANY_TYPE, cellValue);
                    extendInfoPOS.add(extendInfoPO);
                } else {
                    ExtendInfoPO infoPO = extendInfoPOS.get(cellIndex);
                    // 数据校验
                    if (infoPO.getIsrequired() == 1 && StringUtils.isBlank(cellValue)) {
                        historyDetailPO.setOperateDetail(infoPO.getFieldNameDesc() + "为必填项");
                        historyDetailPO.setStatus("0");
                        saveImportDetailLog(historyDetailPO);
                        continue nextRow;
                    }

                    Object reallyValue;
                    try {
                        reallyValue = getReallyValue(infoPO, cellValue);
                    } catch (Exception e) {
                        historyDetailPO.setOperateDetail(cellValue + "转换失败");
                        historyDetailPO.setStatus("0");
                        saveImportDetailLog(historyDetailPO);
                        continue nextRow;
                    }
                    if (StringUtils.isNotBlank(cellValue) && StringUtils.isBlank(Util.null2String(reallyValue))) {
                        historyDetailPO.setOperateDetail(infoPO.getFieldNameDesc() + "数据转换失败,未找到对应数据");
                        historyDetailPO.setStatus("0");
                        saveImportDetailLog(historyDetailPO);
                        continue nextRow;
                    }
                    map.put(infoPO.getFieldName(), reallyValue);
                    if ("comp_name".equals(infoPO.getFieldName())) {
                        historyDetailPO.setRelatedName(cellValue);
                        String[] split = cellValue.split(">");
                        if (split.length > 0) {
                            if (split.length > 8) {
                                historyDetailPO.setOperateDetail("分部层级不能大于10");
                                historyDetailPO.setStatus("0");
                                saveImportDetailLog(historyDetailPO);
                                continue nextRow;
                            }
                            for (int index = 0; index < split.length - 1; index++) {
                                parentCompanyId = MapperProxyFactory.getProxy(CompMapper.class).getIdByNameAndPid(split[index], parentCompanyId == null ? 0 : parentCompanyId);
                                if (null == parentCompanyId) {
                                    historyDetailPO.setOperateDetail(split[index] + "分部未找到对应数据");
                                    historyDetailPO.setStatus("0");
                                    saveImportDetailLog(historyDetailPO);
                                    continue nextRow;
                                }
                            }
                        }
                        map.put("parent_company", parentCompanyId);
                        if (null != parentCompanyId) {
                            map.put("ec_company", EcHrmRelationUtil.getEcCompanyId(parentCompanyId.toString()));
                        }
                        companyName = split[split.length - 1];
                        map.put("comp_name", companyName);
                    }
                }
            }
            // 校验、数据交互
            if (i == 0) {
                continue;
            }
            String compNo = (String) map.get("comp_no");
            Long companyId = MapperProxyFactory.getProxy(CompMapper.class).getIdByNameAndPid(companyName, parentCompanyId == null ? 0 : parentCompanyId);
            if ("add".equals(operateType)) {
                if (companyId != null) {
                    historyDetailPO.setOperateDetail("数据已存在");
                    historyDetailPO.setStatus("0");
                    saveImportDetailLog(historyDetailPO);
                    continue;
                }
                // 自动编号
                compNo = CompServiceImpl.repeatDetermine(compNo);
                map.put("comp_no", compNo);
                map.put("creator", user.getUID());
                map.put("delete_type", 0);
                map.put("create_time", new Date());
                // 禁用表示为空，默认启用
                if (StringUtils.isBlank(Util.null2String(map.get("forbidden_tag")))) {
                    map.put("forbidden_tag", 0);
                }
                String showOrder = Util.null2String(map.get("show_order"));
                if (StringUtils.isBlank(showOrder)) {
                    Integer maxShowOrder = MapperProxyFactory.getProxy(CompMapper.class).getMaxShowOrder();
                    if (null == maxShowOrder) {
                        maxShowOrder = 0;
                    }
                    map.put("show_order", maxShowOrder + 1);
                }

                Map<String, Object> syncMap = new OrganizationSyncEc(user, LogModuleNameEnum.COMPANY, OperateTypeEnum.ADD, map, false).sync();
                if (isThrowError(syncMap)) {
                    // 查询UUID
                    String ecCompanyID = Util.null2String(syncMap.get("id"));
                    RecordInfo recordInfo = getSystemDataMapper().getHrmObjectByID(HRM_COMPANY, ecCompanyID);
                    map.put("uuid", recordInfo.getUuid());
                    ExtendInfoParams infoParams = ExtendInfoParams.builder().tableName("JCL_ORG_COMP").params(map).build();
                    MapperProxyFactory.getProxy(ExtMapper.class).insertTable(infoParams);
                    // 刷新组织架构图
                    new Thread(new CompanyTriggerRunnable(infoParams.getId())).start();
                    historyDetailPO.setOperateDetail("添加成功");
                    historyDetailPO.setStatus("1");
                } else {
                    historyDetailPO.setOperateDetail(Util.null2String(syncMap.get("message")));
                    historyDetailPO.setStatus("0");
                }
                saveImportDetailLog(historyDetailPO);
            } else if ("update".equals(operateType)) {
                // 查询对应ID
                if (StringUtils.isNotBlank(compNo)) {
                    if (companyId == null) {
                        historyDetailPO.setOperateDetail("未找到对应数据");
                        historyDetailPO.setStatus("0");
                        saveImportDetailLog(historyDetailPO);
                    }
                    if (checkRepeatNo(compNo, COMPANY_TYPE, companyId)) {
                        map.put("update_time", new Date());
                        map.put("id", companyId);
                        Map<String, Object> syncMap = new OrganizationSyncEc(user, LogModuleNameEnum.COMPANY, OperateTypeEnum.UPDATE, map, false).sync();
                        if (isThrowError(syncMap)) {
                            map.remove("id");
                            MapperProxyFactory.getProxy(ExtMapper.class).updateTable(ExtendInfoParams.builder().id(companyId).tableName("JCL_ORG_COMP").params(map).build());
                            // 刷新组织架构图
                            new Thread(new CompanyTriggerRunnable(companyId)).start();
                            historyDetailPO.setOperateDetail("更新成功");
                            historyDetailPO.setStatus("1");
                        } else {
                            historyDetailPO.setOperateDetail(Util.null2String(syncMap.get("message")));
                            historyDetailPO.setStatus("0");
                        }
                        saveImportDetailLog(historyDetailPO);
                    } else {
                        historyDetailPO.setOperateDetail(compNo + "编号已存在");
                        historyDetailPO.setStatus("0");
                        saveImportDetailLog(historyDetailPO);
                    }
                } else {
                    historyDetailPO.setOperateDetail("编号为空,更新失败");
                    historyDetailPO.setStatus("0");
                    saveImportDetailLog(historyDetailPO);
                }
            }
        }
        return importHistoryId;
    }

    /**
     * 导入部门
     */
    private Long departmentImport(String operateType, String excelFile) {
        Long importHistoryId = saveImportLog("department", operateType);
        JclImportHistoryDetailPO historyDetailPO;

        ImageFileManager manager = new ImageFileManager();
        manager.getImageFileInfoById(Util.getIntValue(excelFile));
        XSSFWorkbook workbook;
        try {
            workbook = new XSSFWorkbook(manager.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 当前sheet
        XSSFSheet sheetAt = workbook.getSheetAt(0);
        int lastRow = sheetAt.getLastRowNum();
        List<ExtendInfoPO> extendInfoPOS = new ArrayList<>();
        OrganizationAssert.isTrue(lastRow > 0, "导入数据为空");
        short lastCellNum = sheetAt.getRow(0).getLastCellNum();


        // 遍历每一行数据
        nextRow:
        for (int i = 0; i <= lastRow; i++) {
            historyDetailPO = new JclImportHistoryDetailPO();
            historyDetailPO.setPid(importHistoryId);
            XSSFRow row = sheetAt.getRow(i);
            // 组装待处理数据
            Map<String, Object> map = new HashMap<>();
            Long parentCompanyId = null;
            Long parentDepartmentId = null;
            String departmentName = "";

            historyDetailPO.setRowNums(String.valueOf(i + 1));
            for (int cellIndex = 0; cellIndex < lastCellNum; cellIndex++) {
                XSSFCell cell = row.getCell((short) cellIndex);
                String cellValue = getCellValue(cell).trim();
                if (i == 0) {
                    // 首行 初始化字段信息
                    ExtendInfoPO extendInfoPO = getExtendInfoMapper().getInfoByExtendAndLabelName(DEPARTMENT_TYPE, cellValue);
                    extendInfoPOS.add(extendInfoPO);
                } else {
                    ExtendInfoPO infoPO = extendInfoPOS.get(cellIndex);
                    // 数据校验
                    if (infoPO.getIsrequired() == 1 && StringUtils.isBlank(cellValue)) {
                        historyDetailPO.setOperateDetail(infoPO.getFieldNameDesc() + "为必填项");
                        historyDetailPO.setStatus("0");
                        saveImportDetailLog(historyDetailPO);
                        continue nextRow;
                    }

                    Object reallyValue;
                    try {
                        reallyValue = getReallyValue(infoPO, cellValue);
                    } catch (Exception e) {
                        historyDetailPO.setOperateDetail(cellValue + "转换失败");
                        historyDetailPO.setStatus("0");
                        saveImportDetailLog(historyDetailPO);
                        continue nextRow;
                    }
                    if (StringUtils.isNotBlank(cellValue) && StringUtils.isBlank(Util.null2String(reallyValue)) && !"parent_comp".equals(infoPO.getFieldName())) {
                        historyDetailPO.setOperateDetail(infoPO.getFieldNameDesc() + "数据转换失败,未找到对应数据");
                        historyDetailPO.setStatus("0");
                        saveImportDetailLog(historyDetailPO);
                        continue nextRow;
                    }
                    map.put(infoPO.getFieldName(), reallyValue);
                    // 上级分部
                    if ("ec_company".equals(infoPO.getFieldName())) {
                        String[] split = cellValue.split(">");
                        if (split.length > 0) {
                            if (split.length > 8) {
                                historyDetailPO.setOperateDetail("分部层级不能大于10");
                                historyDetailPO.setStatus("0");
                                saveImportDetailLog(historyDetailPO);
                                continue nextRow;
                            }
                            for (String s : split) {
                                parentCompanyId = MapperProxyFactory.getProxy(CompMapper.class).getIdByNameAndPid(s, parentCompanyId == null ? 0 : parentCompanyId);
                                if (null == parentCompanyId) {
                                    historyDetailPO.setOperateDetail(cellValue + "分部未找到对应数据");
                                    historyDetailPO.setStatus("0");
                                    saveImportDetailLog(historyDetailPO);
                                    continue nextRow;
                                }
                            }
                        }
                    }

                    if ("dept_name".equals(infoPO.getFieldName())) {
                        if (null == parentCompanyId) {
                            historyDetailPO.setOperateDetail(cellValue + "所属分部未找到");
                            historyDetailPO.setStatus("0");
                            saveImportDetailLog(historyDetailPO);
                            continue nextRow;
                        }
                        historyDetailPO.setRelatedName(cellValue);
                        String[] split = cellValue.split(">");
                        if (split.length > 0) {
                            if (split.length > 8) {
                                historyDetailPO.setOperateDetail("部门层级不能大于10");
                                historyDetailPO.setStatus("0");
                                saveImportDetailLog(historyDetailPO);
                                continue nextRow;
                            }
                            for (int index = 0; index < split.length - 1; index++) {
                                parentDepartmentId = MapperProxyFactory.getProxy(DepartmentMapper.class).getIdByNameAndPid(split[index], parentCompanyId, parentDepartmentId == null ? 0 : parentDepartmentId);
                                if (null == parentDepartmentId) {
                                    historyDetailPO.setOperateDetail(split[index] + "部门未找到对应数据");
                                    historyDetailPO.setStatus("0");
                                    saveImportDetailLog(historyDetailPO);
                                    continue nextRow;
                                }
                            }
                        }
                        map.put("parent_comp", parentCompanyId);
                        map.put("ec_company", EcHrmRelationUtil.getEcCompanyId(parentCompanyId.toString()));
                        map.put("parent_dept", parentDepartmentId);
                        if(null!=parentDepartmentId){
                            map.put("ec_department", EcHrmRelationUtil.getEcDepartmentId(parentCompanyId.toString()));
                        }
                        departmentName = split[split.length - 1];
                        map.put("dept_name", departmentName);
                    }
                }
            }
            // 校验、数据交互
            if (i == 0) {
                continue;
            }
            String deptNo = (String) map.get("dept_no");
            Long departmentId = MapperProxyFactory.getProxy(DepartmentMapper.class).getIdByNameAndPid(departmentName, parentCompanyId, parentDepartmentId == null ? 0 : parentDepartmentId);
            if ("add".equals(operateType)) {
                if (departmentId != null) {
                    historyDetailPO.setOperateDetail("数据已存在");
                    historyDetailPO.setStatus("0");
                    saveImportDetailLog(historyDetailPO);
                    continue;
                }
                // 自动编号
                deptNo = DepartmentServiceImpl.repeatDetermine(deptNo);
                map.put("dept_no", deptNo);
                map.put("creator", user.getUID());
                map.put("delete_type", 0);
                map.put("create_time", new Date());
                // 禁用表示为空，默认启用
                if (StringUtils.isBlank(Util.null2String(map.get("forbidden_tag")))) {
                    map.put("forbidden_tag", 0);
                }
                String showOrder = Util.null2String(map.get("show_order"));
                if (StringUtils.isBlank(showOrder)) {
                    Integer maxShowOrder = MapperProxyFactory.getProxy(DepartmentMapper.class).getMaxShowOrder();
                    if (null == maxShowOrder) {
                        maxShowOrder = 0;
                    }
                    map.put("show_order", maxShowOrder + 1);
                }
                Map<String, Object> syncMap = new OrganizationSyncEc(user, LogModuleNameEnum.DEPARTMENT, OperateTypeEnum.ADD, map, false).sync();
                if (isThrowError(syncMap)) {
                    // 查询UUID
                    String ecDepartmentID = Util.null2String(syncMap.get("id"));
                    RecordInfo recordInfo = getSystemDataMapper().getHrmObjectByID(HRM_DEPARTMENT, ecDepartmentID);
                    map.put("uuid", recordInfo.getUuid());
                    ExtendInfoParams infoParams = ExtendInfoParams.builder().tableName("JCL_ORG_DEPT").params(map).build();
                    MapperProxyFactory.getProxy(ExtMapper.class).insertTable(infoParams);
                    // 刷新组织架构图
                    new Thread(new DepartmentTriggerRunnable(infoParams.getId())).start();
                    map.put("id", infoParams.getId());
                    historyDetailPO.setOperateDetail("添加成功");
                    historyDetailPO.setStatus("1");
                } else {
                    historyDetailPO.setOperateDetail(Util.null2String(syncMap.get("message")));
                    historyDetailPO.setStatus("0");
                }
                saveImportDetailLog(historyDetailPO);
            } else if ("update".equals(operateType)) {
                // 查询对应ID
                if (StringUtils.isNotBlank(deptNo)) {
                    if (departmentId == null) {
                        historyDetailPO.setOperateDetail("未找到对应数据");
                        historyDetailPO.setStatus("0");
                        saveImportDetailLog(historyDetailPO);
                    }
                    if (checkRepeatNo(deptNo, DEPARTMENT_TYPE, departmentId)) {
                        map.put("update_time", new Date());
                        map.put("id", departmentId);
                        Map<String, Object> syncMap = new OrganizationSyncEc(user, LogModuleNameEnum.DEPARTMENT, OperateTypeEnum.UPDATE, map, false).sync();
                        if (isThrowError(syncMap)) {
                            map.remove("id");
                            MapperProxyFactory.getProxy(ExtMapper.class).updateTable(ExtendInfoParams.builder().id(departmentId).tableName("JCL_ORG_DEPT").params(map).build());
                            // 刷新组织架构图
                            new Thread(new DepartmentTriggerRunnable(departmentId)).start();
                            historyDetailPO.setOperateDetail("更新成功");
                            historyDetailPO.setStatus("1");
                        } else {
                            historyDetailPO.setOperateDetail(Util.null2String(syncMap.get("message")));
                            historyDetailPO.setStatus("0");
                        }
                        saveImportDetailLog(historyDetailPO);
                    } else {
                        historyDetailPO.setOperateDetail(deptNo + "编号已存在");
                        historyDetailPO.setStatus("0");
                        saveImportDetailLog(historyDetailPO);
                    }
                } else {
                    historyDetailPO.setOperateDetail("编号为空,更新失败");
                    historyDetailPO.setStatus("0");
                    saveImportDetailLog(historyDetailPO);
                }
            }
        }
        return importHistoryId;
    }

    /**
     * 岗位导入
     */
    private Long jobImport(String operateType, String excelFile) {
        Long importHistoryId = saveImportLog("jobtitle", operateType);
        JclImportHistoryDetailPO historyDetailPO;

        ImageFileManager manager = new ImageFileManager();
        manager.getImageFileInfoById(Util.getIntValue(excelFile));
        XSSFWorkbook workbook;
        try {
            workbook = new XSSFWorkbook(manager.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 当前sheet
        XSSFSheet sheetAt = workbook.getSheetAt(0);
        int lastRow = sheetAt.getLastRowNum();
        List<ExtendInfoPO> extendInfoPOS = new ArrayList<>();
        OrganizationAssert.isTrue(lastRow > 0, "导入数据为空");
        short lastCellNum = sheetAt.getRow(0).getLastCellNum();

        // 遍历每一行数据
        nextRow:
        for (int i = 0; i <= lastRow; i++) {
            historyDetailPO = new JclImportHistoryDetailPO();
            historyDetailPO.setPid(importHistoryId);
            XSSFRow row = sheetAt.getRow(i);
            // 组装待处理数据
            Map<String, Object> map = new HashMap<>();
            Long parentCompanyId = null;
            Long parentDepartmentId = null;
            Long parentJobId = null;
            String jobName = "";

            historyDetailPO.setRowNums(String.valueOf(i + 1));
            for (int cellIndex = 0; cellIndex < lastCellNum; cellIndex++) {
                XSSFCell cell = row.getCell((short) cellIndex);
                String cellValue = getCellValue(cell).trim();
                if (i == 0) {
                    // 首行 初始化字段信息
                    ExtendInfoPO extendInfoPO = getExtendInfoMapper().getInfoByExtendAndLabelName(JOB_TYPE, cellValue);
                    extendInfoPOS.add(extendInfoPO);
                } else {
                    ExtendInfoPO infoPO = extendInfoPOS.get(cellIndex);
                    // 数据校验
                    if (infoPO.getIsrequired() == 1 && StringUtils.isBlank(cellValue)) {
                        historyDetailPO.setOperateDetail(infoPO.getFieldNameDesc() + "为必填项");
                        historyDetailPO.setStatus("0");
                        saveImportDetailLog(historyDetailPO);
                        continue nextRow;
                    }

                    Object reallyValue;
                    try {
                        reallyValue = getReallyValue(infoPO, cellValue);
                    } catch (Exception e) {
                        historyDetailPO.setOperateDetail(cellValue + "转换失败");
                        historyDetailPO.setStatus("0");
                        saveImportDetailLog(historyDetailPO);
                        continue nextRow;
                    }
                    if (StringUtils.isNotBlank(cellValue) && StringUtils.isBlank(Util.null2String(reallyValue)) && !"ec_company".equals(infoPO.getFieldName()) && !"ec_department".equals(infoPO.getFieldName())) {
                        historyDetailPO.setOperateDetail(infoPO.getFieldNameDesc() + "数据转换失败,未找到对应数据");
                        historyDetailPO.setStatus("0");
                        saveImportDetailLog(historyDetailPO);
                        continue nextRow;
                    }
                    map.put(infoPO.getFieldName(), reallyValue);
                    // 上级分部
                    if ("ec_company".equals(infoPO.getFieldName())) {
                        String[] split = cellValue.split(">");
                        if (split.length > 0) {
                            if (split.length > 8) {
                                historyDetailPO.setOperateDetail("分部层级不能大于10");
                                historyDetailPO.setStatus("0");
                                saveImportDetailLog(historyDetailPO);
                                continue nextRow;
                            }
                            for (String s : split) {
                                parentCompanyId = MapperProxyFactory.getProxy(CompMapper.class).getIdByNameAndPid(s, parentCompanyId == null ? 0 : parentCompanyId);
                                if (null == parentCompanyId) {
                                    historyDetailPO.setOperateDetail(cellValue + "分部未找到对应数据");
                                    historyDetailPO.setStatus("0");
                                    saveImportDetailLog(historyDetailPO);
                                    continue nextRow;
                                }
                            }
                        }
                    }


                    if ("ec_department".equals(infoPO.getFieldName())) {
                        String[] split = cellValue.split(">");
                        if (split.length > 0) {
                            if (split.length > 8) {
                                historyDetailPO.setOperateDetail("部门层级不能大于10");
                                historyDetailPO.setStatus("0");
                                saveImportDetailLog(historyDetailPO);
                                continue nextRow;
                            }
                            for (String s : split) {
                                parentDepartmentId = MapperProxyFactory.getProxy(DepartmentMapper.class).getIdByNameAndPid(s, parentCompanyId, parentDepartmentId == null ? 0 : parentDepartmentId);
                                if (null == parentCompanyId) {
                                    historyDetailPO.setOperateDetail(cellValue + "部门未找到对应数据");
                                    historyDetailPO.setStatus("0");
                                    saveImportDetailLog(historyDetailPO);
                                    continue nextRow;
                                }
                            }
                        }
                    }

                    if ("job_name".equals(infoPO.getFieldName())) {
                        if (null == parentCompanyId) {
                            historyDetailPO.setOperateDetail(cellValue + "所属分部未找到");
                            historyDetailPO.setStatus("0");
                            saveImportDetailLog(historyDetailPO);
                            continue nextRow;
                        }
                        historyDetailPO.setRelatedName(cellValue);
                        String[] split = cellValue.split(">");
                        if (split.length > 0) {
                            if (split.length > 8) {
                                historyDetailPO.setOperateDetail("岗位层级不能大于10");
                                historyDetailPO.setStatus("0");
                                saveImportDetailLog(historyDetailPO);
                                continue nextRow;
                            }
                            for (int index = 0; index < split.length - 1; index++) {
                                parentJobId = MapperProxyFactory.getProxy(JobMapper.class).getIdByNameAndPid(split[index], parentCompanyId, parentDepartmentId == null ? 0 : parentDepartmentId, parentJobId == null ? 0 : parentJobId);
                                if (null == parentJobId) {
                                    historyDetailPO.setOperateDetail(split[index] + "岗位未找到对应数据");
                                    historyDetailPO.setStatus("0");
                                    saveImportDetailLog(historyDetailPO);
                                    continue nextRow;
                                }
                            }
                        }
                        map.put("parent_comp", parentCompanyId);
                        map.put("parent_dept", parentDepartmentId);
                        map.put("ec_company", EcHrmRelationUtil.getEcCompanyId( Util.null2String(parentCompanyId)));
                        if (null != parentDepartmentId) {
                            map.put("ec_department", EcHrmRelationUtil.getEcDepartmentId(Util.null2String(parentDepartmentId)));
                        }
                        map.put("parent_job", parentJobId);
                        jobName = split[split.length - 1];
                        map.put("job_name", jobName);
                    }
                }
            }
            // 校验、数据交互
            if (i == 0) {
                continue;
            }
            String jobNo = (String) map.get("job_no");
            Long jobId = MapperProxyFactory.getProxy(JobMapper.class).getIdByNameAndPid(jobName, parentCompanyId, parentDepartmentId == null ? 0 : parentDepartmentId, parentJobId == null ? 0 : parentJobId);
            if ("add".equals(operateType)) {
                if (jobId != null) {
                    historyDetailPO.setOperateDetail("数据已存在");
                    historyDetailPO.setStatus("0");
                    saveImportDetailLog(historyDetailPO);
                    continue;
                }
                // 自动编号
                jobNo = JobServiceImpl.repeatDetermine(jobNo);
                map.put("job_no", jobNo);
                map.put("creator", user.getUID());
                map.put("delete_type", 0);
                map.put("create_time", new Date());
                // 禁用表示为空，默认启用
                if (StringUtils.isBlank(Util.null2String(map.get("forbidden_tag")))) {
                    map.put("forbidden_tag", 0);
                }
                String showOrder = Util.null2String(map.get("show_order"));
                if (StringUtils.isBlank(showOrder)) {
                    Integer maxShowOrder = MapperProxyFactory.getProxy(JobMapper.class).getMaxShowOrder();
                    if (null == maxShowOrder) {
                        maxShowOrder = 0;
                    }
                    map.put("show_order", maxShowOrder + 1);
                }
                ExtendInfoParams infoParams = ExtendInfoParams.builder().tableName("JCL_ORG_JOB").params(map).build();

                map.put("jobactivityid", JobServiceImpl.JOB_ACTIVITY_ID);
                map.put("id", infoParams.getId());
                Map<String, Object> syncMap = new OrganizationSyncEc(user, LogModuleNameEnum.JOB, OperateTypeEnum.ADD, map, false).sync();
                if (isThrowError(syncMap)) {
                    map.remove("id");
                    map.remove("jobactivityid");
                    MapperProxyFactory.getProxy(ExtMapper.class).insertTable(infoParams);
                    // 更新组织架构图
                    new Thread(new JobTriggerRunnable(jobId)).start();
                    historyDetailPO.setOperateDetail("添加成功");
                    historyDetailPO.setStatus("1");
                } else {
                    historyDetailPO.setOperateDetail(Util.null2String(syncMap.get("message")));
                    historyDetailPO.setStatus("0");
                }
                saveImportDetailLog(historyDetailPO);
            } else if ("update".equals(operateType)) {
                // 查询对应ID
                if (StringUtils.isNotBlank(jobNo)) {
                    if (jobId == null) {
                        historyDetailPO.setOperateDetail("未找到对应数据");
                        historyDetailPO.setStatus("0");
                        saveImportDetailLog(historyDetailPO);
                    }
                    if (checkRepeatNo(jobNo, JOB_TYPE, jobId)) {
                        map.put("update_time", new Date());
                        map.put("jobactivityid", JobServiceImpl.JOB_ACTIVITY_ID);
                        map.put("id", jobId);
                        Map<String, Object> syncMap = new OrganizationSyncEc(user, LogModuleNameEnum.JOB, OperateTypeEnum.UPDATE, map, false).sync();
                        if (isThrowError(syncMap)) {
                            map.remove("id");
                            map.remove("jobactivityid");
                            MapperProxyFactory.getProxy(ExtMapper.class).updateTable(ExtendInfoParams.builder().id(jobId).tableName("JCL_ORG_JOB").params(map).build());
                            // 更新组织架构图
                            new Thread(new JobTriggerRunnable(jobId)).start();
                            historyDetailPO.setOperateDetail("更新成功");
                            historyDetailPO.setStatus("1");
                        } else {
                            historyDetailPO.setOperateDetail(Util.null2String(syncMap.get("message")));
                            historyDetailPO.setStatus("0");
                        }
                        saveImportDetailLog(historyDetailPO);
                    } else {
                        historyDetailPO.setOperateDetail(jobNo + "编号已存在");
                        historyDetailPO.setStatus("0");
                        saveImportDetailLog(historyDetailPO);
                    }
                } else {
                    historyDetailPO.setOperateDetail("编号为空,更新失败");
                    historyDetailPO.setStatus("0");
                    saveImportDetailLog(historyDetailPO);
                }
            }
        }
        return importHistoryId;
    }


    /**
     * 读取表格文本内容
     */
    private String getCellValue(XSSFCell cell) {
        String cellValue = "";
        if (cell == null)
            return "";
        switch (cell.getCellType()) {
            case BOOLEAN: // 得到Boolean对象的方法
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case NUMERIC:
                if (HSSFDateUtil.isCellDateFormatted(cell)) {// 先看是否是日期格式
                    SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd");
                    cellValue = sft.format(cell.getDateCellValue()); // 读取日期格式
                } else {
                    cellValue = String.valueOf(new Double(cell.getNumericCellValue())); // 读取数字
                    if (cellValue.endsWith(".0"))
                        cellValue = cellValue.substring(0, cellValue.indexOf("."));
                }
                break;
            case FORMULA: // 读取公式
                cellValue = cell.getCellFormula();
                break;
            case STRING: // 读取String
                cellValue = cell.getStringCellValue();
                break;
        }
        cellValue = Util.toHtmlForHrm(cellValue);
        return cellValue;
    }

    /**
     * 转换存入数据库的值
     */
    private Object getReallyValue(ExtendInfoPO extendInfo, String cellValue) throws Exception {
        if (StringUtils.isBlank(cellValue)) {
            return null;
        }
        Object object = null;
        JSONArray jsonArray = JSONObject.parseArray(extendInfo.getCustomValue());
        switch (extendInfo.getControlType()) {
            case 1:
                String valueType = (String) jsonArray.get(1);
                // INPUT
                if ("int".equals(valueType)) {
                    object = Integer.parseInt(cellValue);
                } else if ("float".equals(valueType)) {
                    object = Float.parseFloat(cellValue);
                } else {
                    object = cellValue;
                }
                break;
            case 3:
                // BROWSER
                org.json.JSONObject jsonObject = new org.json.JSONObject();
                jsonObject.put("fieldhtmltype", extendInfo.getControlType());
                jsonObject.put("type", extendInfo.getBrowserType());
                jsonObject.put("fieldvalue", cellValue);
                if ("161".equals(extendInfo.getBrowserType()) || "162".equals(extendInfo.getBrowserType())) {
                    jsonObject.put("dmlurl", SelectOptionParam.getCustomBrowserId(extendInfo.getCustomValue()));
                } else {
                    jsonObject.put("dmlurl", extendInfo.getBrowserType());
                }
                jsonObject.put("fieldid", 0);
                object = HrmFieldManager.getReallyFieldvalue(jsonObject);
                break;
            case 5:
                // SELECT
                JSONObject o = (JSONObject) jsonArray.get(2);
                JSONArray datas = o.getJSONArray("datas");
                List<FieldSelectOptionBean> options = datas.toJavaList(FieldSelectOptionBean.class);
                Map<String, String> optionMap = options.stream().collect(Collectors.toMap(FieldSelectOptionBean::getOption, FieldSelectOptionBean::getId, (k1, k2) -> k1));
                object = optionMap.get(cellValue);
                break;
            case 4:// CHECKBOX
            case 6:
                // FILEUPLOAD
                break;
            case 7:// TEXT
            case 2:// TEXTAREA
            default:
                object = cellValue;
                break;
        }
        return object;
    }

    /**
     * 校验重复编号
     */
    private boolean checkRepeatNo(String no, Long extendType, Long id) {
        if (StringUtils.isBlank(no)) {
            return true;
        }
        if (null != extendType) {
            switch (extendType.toString()) {
                case "1":
                    return 0 == MapperProxyFactory.getProxy(CompMapper.class).checkRepeatNo(no, id);
                case "2":
                    return 0 == MapperProxyFactory.getProxy(DepartmentMapper.class).checkRepeatNo(no, id);
                case "3":
                    return 0 == MapperProxyFactory.getProxy(JobMapper.class).checkRepeatNo(no, id);
                default:
                    return false;
            }
        }
        return false;
    }

    /**
     * 生成记录日志
     */
    private Long saveImportLog(String importType, String operateType) {
        JclImportHistoryPO historyPO = JclImportHistoryPO.builder().operator((long) user.getUID()).operateTime(DateUtil.getFullDate()).clientAddress(user.getLoginip()).importType(importType).sourceFrom("excel").operateType(operateType).status("importing").build();
        MapperProxyFactory.getProxy(JclImportHistoryMapper.class).insertHistory(historyPO);
        return historyPO.getId();
    }

    /**
     * 日志导入详细信息日志
     */
    private void saveImportDetailLog(JclImportHistoryDetailPO historyDetailPO) {
        String detailMsg = "导入第" + historyDetailPO.getRowNums() + "行数据,[" + historyDetailPO.getRelatedName() + "]" + historyDetailPO.getOperateDetail();
        historyDetailPO.setOperateDetail(detailMsg);
        MapperProxyFactory.getProxy(JclImportHistoryDetailMapper.class).insertHistoryDetail(historyDetailPO);
    }

    /**
     * 生成导入模板文件
     */
    private String getTemplatePath(String importType, String columns) throws IOException {
        // 根据选择字段、生成对应的导入模板
        String[] split = columns.split(",");
        List<Object> columnList = new ArrayList<>(Arrays.asList(split));
        Object companyColumn = "";
        Object departmentColumn = "";
        // 排序
        /*
        第一列：所属分部
        第二列：所属部门\上级部门\部门
         */
        Iterator<Object> iterator = columnList.iterator();
        while (iterator.hasNext()) {
            Object column = iterator.next();
            if ("所属分部".equals(column.toString())) {
                companyColumn = column;
                iterator.remove();
            }

            if ("所属部门".equals(column) || "上级部门".equals(column) || "部门".equals(column)) {
                departmentColumn = column;
                iterator.remove();
            }
        }
        if (StringUtils.isNotBlank(departmentColumn.toString())) {
            columnList.add(0, departmentColumn);
        }

        if (StringUtils.isNotBlank(companyColumn.toString())) {
            columnList.add(0, companyColumn);
        }

        List<List<Object>> excelSheetData = new ArrayList<>();
        excelSheetData.add(columnList);
        String outPutPath = GCONST.getRootPath() + "hrm" + File.separator + "import" + File.separator + "template" + File.separator + user.getUID();
        XSSFWorkbook sheets = ExcelUtil.genWorkbookV2(excelSheetData, importType);
        String excelPath = outPutPath + File.separator + importType + ".xls";
        File excelPathFile = new File(excelPath);
        if (!excelPathFile.exists()) {
            String substring = excelPath.substring(0, excelPath.lastIndexOf(File.separator));
            File file = new File(substring);
            if (file.mkdirs()) {
                boolean newFile = excelPathFile.createNewFile();
                if (!newFile) {
                    throw new IOException(excelPath + "文件创建失败");
                }
            }
        }
        FileOutputStream out = new FileOutputStream(excelPathFile);
        sheets.write(out);
        out.flush();
        excelPath = "/hrm/import/template/" + user.getUID() + "/" + importType + ".xls";
        return excelPath;
    }

    private boolean isThrowError(Map<String, Object> resultMap) {
        return "1".equals(Util.null2String(resultMap.get("status"))) || "1".equals(Util.null2String(resultMap.get("sign")));
    }

}
