package com.engine.organization.service.impl;

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.organization.component.OrganizationWeaTable;
import com.engine.organization.entity.extend.ExtendInfoOperateType;
import com.engine.organization.entity.extend.po.ExtendInfoPO;
import com.engine.organization.entity.fieldset.param.FieldTransferParam;
import com.engine.organization.entity.jclimport.po.JclImportHistoryDetailPO;
import com.engine.organization.entity.jclimport.vo.JclImportHistoryDetailVO;
import com.engine.organization.entity.scheme.po.GradePO;
import com.engine.organization.entity.scheme.po.LevelPO;
import com.engine.organization.entity.scheme.po.SchemePO;
import com.engine.organization.enums.OrgImportEnum;
import com.engine.organization.mapper.extend.ExtendInfoMapper;
import com.engine.organization.mapper.jclimport.ImportMapper;
import com.engine.organization.mapper.jclimport.JclImportHistoryDetailMapper;
import com.engine.organization.mapper.scheme.GradeMapper;
import com.engine.organization.mapper.scheme.LevelMapper;
import com.engine.organization.mapper.scheme.SchemeMapper;
import com.engine.organization.service.ImportCommonService;
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.saveimport.CompanyImport;
import com.engine.organization.util.saveimport.DepartmentImport;
import com.engine.organization.util.saveimport.OrgImportUtil;
import com.engine.organization.util.saveimport.ResourceImport;
import org.apache.commons.collections.CollectionUtils;
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.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
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 {

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

    static Map<String, ExtendInfoPO> importFieldsMap;

    static {
        importFieldsMap = new HashMap<>();
        importFieldsMap.put("方案编号", ExtendInfoPO.builder().tableName("jcl_org_scheme").fieldName("scheme_no").fieldNameDesc("方案编号").isrequired(1).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("方案名称", ExtendInfoPO.builder().tableName("jcl_org_scheme").fieldName("scheme_name").fieldNameDesc("方案名称").isrequired(1).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("职级编号", ExtendInfoPO.builder().tableName("jcl_org_grade").fieldName("grade_no").fieldNameDesc("职级编号").isrequired(1).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("职级名称", ExtendInfoPO.builder().tableName("jcl_org_grade").fieldName("grade_name").fieldNameDesc("职级名称").isrequired(1).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("职等编号", ExtendInfoPO.builder().tableName("jcl_org_level").fieldName("level_no").fieldNameDesc("职等编号").isrequired(1).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("职等名称", ExtendInfoPO.builder().tableName("jcl_org_level").fieldName("level_name").fieldNameDesc("职等名称").isrequired(1).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("方案说明", ExtendInfoPO.builder().tableName("jcl_org_scheme").fieldName("scheme_description").fieldNameDesc("方案说明").isrequired(0).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("职等说明", ExtendInfoPO.builder().tableName("jcl_org_level").fieldName("level_description").fieldNameDesc("职等说明").isrequired(0).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("职级说明", ExtendInfoPO.builder().tableName("jcl_org_grade").fieldName("grade_description").fieldNameDesc("职级说明").isrequired(0).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());

    }

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

    private ImportMapper getImportMapper() {
        return MapperProxyFactory.getProxy(ImportMapper.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":
                    excludeFields.add("subcompanydesc");
                    excludeFields.add("supsubcomid");
                    excludeFields.add("limitUsers");
                    excludeFields.add("subshowid");
                    return CompanyImport.getImportFields(user, excludeFields);
                case "department":
                    excludeFields.add("departmentname");
                    excludeFields.add("supdepid");
                    excludeFields.add("showid");
                    return DepartmentImport.getImportFields(user, excludeFields);
                case "jobtitle":
                case "resource":
                    List<String> resourceExceptedFields = getImportMapper().getResourceExceptedFields();
                    if (CollectionUtils.isNotEmpty(resourceExceptedFields)) {
                        excludeFields.addAll(resourceExceptedFields);
                    }
                    excludeFields.add("resourceimageid");
                    excludeFields.add("messagerurl");
                    excludeFields.add("workyear");
                    excludeFields.add("companyworkyear");
                    excludeFields.add("textfield1");
                    excludeFields.add("textfield2");

                    return ResourceImport.getImportFields(user, excludeFields);
                case "joblevel":
                    extendType = "0";
                    tableName = "JCL_ORG_SCHEME";
                    break;
                default:
                    errorMsg = "未找到对应的导入类型，请确认";
                    break;
            }
        } else {
            errorMsg = "请选择导入类型";
        }
        OrganizationAssert.isBlank(errorMsg, errorMsg);
        if (StringUtils.isAnyEmpty(extendType, tableName)) {
            return returnMaps;
        }

        if ("joblevel".equals(importType)) {
            List<FieldTransferParam> fieldDatas = new ArrayList<>();
            fieldDatas.add(FieldTransferParam.builder().id("1").name("职级编号").build());
            fieldDatas.add(FieldTransferParam.builder().id("2").name("职级名称").build());
            fieldDatas.add(FieldTransferParam.builder().id("3").name("方案编号").build());
            fieldDatas.add(FieldTransferParam.builder().id("4").name("方案名称").build());
            fieldDatas.add(FieldTransferParam.builder().id("5").name("职等编号").build());
            fieldDatas.add(FieldTransferParam.builder().id("6").name("职等名称").build());
            fieldDatas.add(FieldTransferParam.builder().id("7").name("方案说明").build());
            fieldDatas.add(FieldTransferParam.builder().id("8").name("职级说明").build());
            fieldDatas.add(FieldTransferParam.builder().id("9").name("职等说明").build());
            List<String> selectedKeys = new ArrayList<>();
            for (int i = 0; i < fieldDatas.subList(0, 6).size(); i++) {
                selectedKeys.add(fieldDatas.get(i).getId());
            }
            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", CompanyImport.importForm(user, templatePath));
                        break;
                    case "department":
                        returnMap.put("condition", DepartmentImport.importForm(user, templatePath));
                        break;
                    case "jobtitle":
                        //returnMap.put("condition", getJobTitleImportForm(templatePath));
                        //break;
                    case "resource":
                        returnMap.put("condition", ResourceImport.importForm(user, templatePath));
                        break;
                    case "joblevel":
                        returnMap.put("condition", getJobLevelImportForm(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");
        String keyField = (String) params.get("keyField");
        Map<String, Object> returnMap = new HashMap<>();
        if (StringUtils.isNotBlank(importType)) {
            switch (importType) {
                case "company":
                    returnMap.put("pId", CompanyImport.saveImport(operateType, excelFile, user));
                    break;
                case "department":
                    returnMap.put("pId", DepartmentImport.saveImport(operateType, excelFile, user));
                    break;
                case "jobtitle":
                case "resource":
                    returnMap.put("pId", ResourceImport.saveImport(operateType, excelFile, user, request));
                    break;
                case "joblevel":
                    returnMap.put("pId", jobLevelImport(operateType, excelFile));
                    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> getJobLevelImportForm(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);
        }
        Map<String, Object> item = new HashMap<>();
        item.put("index", 3);
        item.put("value", "多个职等之间使用英文状态下逗号”,“隔开");
        itemList.add(item);
        groupItem.put("items", itemList);
        lsGroup.add(groupItem);
        return lsGroup;
    }

    /**
     * 方案职等职级导入
     */
    private Long jobLevelImport(String operateType, String excelFile) {

        Long importHistoryId = OrgImportUtil.saveImportLog("joblevel", operateType, user);
        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);
        }
        int allRow = 0;
        for (int s = 0; s < workbook.getNumberOfSheets(); s++) {
            // 当前sheet
            XSSFSheet sheetAt = workbook.getSheetAt(s);
            int lastRow = sheetAt.getLastRowNum();
            allRow = allRow + lastRow;
            String relatedName;
            switch (s) {
                case 0:
                    relatedName = "方案页";
                    break;
                case 1:
                    relatedName = "职等页";
                    break;
                default:
                    relatedName = "职级页";
                    OrganizationAssert.isTrue(allRow > 0, "导入数据为空");
                    break;
            }
            short lastCellNum = sheetAt.getRow(0).getLastCellNum();
            List<ExtendInfoPO> extendInfoPOS = new ArrayList<>();

            // 遍历每一行数据
            nextRow:
            for (int i = 0; i <= lastRow; i++) {
                historyDetailPO = new JclImportHistoryDetailPO();
                historyDetailPO.setPid(importHistoryId);
                XSSFRow row = sheetAt.getRow(i);
                if (null == row) {
                    continue;
                }
                // 组装待处理数据
                Map<String, Object> map = new HashMap<>();
                SchemePO schemePO = new SchemePO();
                SchemePO schemeNew;
                GradePO gradePO = new GradePO();
                GradePO gradeNew = new GradePO();
                LevelPO levelPO = new LevelPO();
                LevelPO levelNew;

                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 = importFieldsMap.get(cellValue);
                        extendInfoPOS.add(extendInfoPO);
                    } else {
                        ExtendInfoPO infoPO = extendInfoPOS.get(cellIndex);
                        // 数据校验
                        if (infoPO.getIsrequired() == 1 && StringUtils.isBlank(cellValue)) {
                            historyDetailPO.setRelatedName(relatedName);
                            historyDetailPO.setOperateDetail(infoPO.getFieldNameDesc() + "为必填项");
                            historyDetailPO.setStatus("0");
                            OrgImportUtil.saveImportDetailLog(historyDetailPO);
                            continue nextRow;
                        }

                        Object reallyValue;
                        try {
                            // 数据格式转换
                            reallyValue = OrgImportUtil.getReallyValue(infoPO, cellValue);
                        } catch (Exception e) {
                            historyDetailPO.setRelatedName(relatedName);
                            historyDetailPO.setOperateDetail(cellValue + "转换失败");
                            historyDetailPO.setStatus("0");
                            OrgImportUtil.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");
                            OrgImportUtil.saveImportDetailLog(historyDetailPO);
                            continue nextRow;
                        }
                        map.put(infoPO.getFieldName(), reallyValue);
                        // 方案页校验(是否重复)
                        if ("scheme_no".equals(infoPO.getFieldName()) && s == 0 && "add".equals(operateType)) {
                            List<SchemePO> schemePOS = MapperProxyFactory.getProxy(SchemeMapper.class).listByNo(Util.null2String(reallyValue));
                            if (schemePOS.size() > 0) {
                                historyDetailPO.setRelatedName(relatedName);
                                historyDetailPO.setOperateDetail("方案编号[" + reallyValue + "]与原有编号重复");
                                historyDetailPO.setStatus("0");
                                OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                continue nextRow;
                            }
                        }
                        // 职等页校验(方案是否存在)
                        if ("scheme_no".equals(infoPO.getFieldName()) && s == 1) {
                            List<SchemePO> schemePOS = MapperProxyFactory.getProxy(SchemeMapper.class).listByNo(Util.null2String(reallyValue));
                            if (schemePOS.size() == 0) {
                                historyDetailPO.setRelatedName(relatedName);
                                historyDetailPO.setOperateDetail("未找到编号为[" + reallyValue + "]的方案");
                                historyDetailPO.setStatus("0");
                                OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                continue nextRow;
                            }
                        }
                        // 职级页校验(方案是否存在)
                        if ("scheme_no".equals(infoPO.getFieldName()) && s == 2) {
                            List<SchemePO> schemePOS = MapperProxyFactory.getProxy(SchemeMapper.class).listByNo(Util.null2String(reallyValue));
                            if (schemePOS.size() == 0) {
                                historyDetailPO.setRelatedName(relatedName);
                                historyDetailPO.setOperateDetail("未找到编号为[" + reallyValue + "]的方案");
                                historyDetailPO.setStatus("0");
                                OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                continue nextRow;
                            }
                        }
                        // 职级页校验(职等是否存在)
                        if ("level_no".equals(infoPO.getFieldName()) && s == 2) {
                            String[] split = Util.null2String(reallyValue).split(",");
                            if (split.length > 0) {
                                for (String value : split) {
                                    List<LevelPO> levelPOS = MapperProxyFactory.getProxy(LevelMapper.class).listByNo(value);
                                    if (levelPOS.size() == 0) {
                                        historyDetailPO.setRelatedName(relatedName);
                                        historyDetailPO.setOperateDetail("未找到编号为[" + value + "]的职等");
                                        historyDetailPO.setStatus("0");
                                        OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                        continue nextRow;
                                    }
                                }
                            }
                        }
                    }
                }
                // 校验、数据交互
                if (i == 0) {
                    continue;
                }

                map.put("creator", user.getUID());
                map.put("delete_type", 0);
                Date currDate = new Date();
                map.put("create_time", currDate);
                map.put("update_time", currDate);
                // 禁用表示为空，默认启用
                map.put("forbidden_tag", 0);
                map.put("is_used", 1);
                if ("add".equals(operateType)) {
                    switch (s) {
                        case 0:
                            schemePO.setSchemeNo((String) map.get("scheme_no"));
                            schemePO.setSchemeName((String) map.get("scheme_name"));
                            schemePO.setSchemeDescription((String) map.get("scheme_description"));
                            schemePO.setForbiddenTag((int) map.get("forbidden_tag"));
                            schemePO.setIsUsed(1);
                            schemePO.setCreator((long) user.getUID());
                            schemePO.setDeleteType((int) map.get("delete_type"));
                            schemePO.setCreateTime((Date) map.get("create_time"));
                            schemePO.setUpdateTime((Date) map.get("update_time"));
                            MapperProxyFactory.getProxy(SchemeMapper.class).insertIgnoreNull(schemePO);
                            break;
                        case 1:
                            String schemeNo = (String) map.get("scheme_no");
                            String levelNo = (String) map.get("level_no");
                            schemeNew = MapperProxyFactory.getProxy(SchemeMapper.class).getSchemeByNo(schemeNo);
                            if (schemeNew != null) {
                                levelNew = MapperProxyFactory.getProxy(LevelMapper.class).getLevelByNoAndSid(levelNo, schemeNew.getId());
                                if (levelNew != null) {
                                    historyDetailPO.setRelatedName("职等编号");
                                    historyDetailPO.setOperateDetail("职等页导入:同一方案" + schemeNo + "下，职等编号不可重复");
                                    historyDetailPO.setStatus("0");
                                    OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                    continue;
                                } else {
                                    levelPO.setLevelNo(levelNo);
                                    levelPO.setLevelName((String) map.get("level_name"));
                                    levelPO.setDescription((String) map.get("level_description"));
                                    //关联方案id
                                    levelPO.setSchemeId(schemeNew.getId());
                                    levelPO.setForbiddenTag((int) map.get("forbidden_tag"));
                                    levelPO.setIsUsed(1);
                                    levelPO.setCreator((long) user.getUID());
                                    levelPO.setDeleteType((int) map.get("delete_type"));
                                    levelPO.setCreateTime((Date) map.get("create_time"));
                                    levelPO.setUpdateTime((Date) map.get("update_time"));
                                    MapperProxyFactory.getProxy(LevelMapper.class).insertIgnoreNull(levelPO);
                                }
                            } else {
                                historyDetailPO.setRelatedName(relatedName);
                                historyDetailPO.setOperateDetail("未找到编号为[" + schemeNo + "]的方案");
                                historyDetailPO.setStatus("0");
                                OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                continue;
                            }
                            break;
                        case 2:
                            String gradeNo2 = (String) map.get("grade_no");
                            String schemeNo2 = (String) map.get("scheme_no");
                            String levelNo2 = (String) map.get("level_no");

                            schemeNew = MapperProxyFactory.getProxy(SchemeMapper.class).getSchemeByNo(schemeNo2);
                            if (schemeNew == null) {
                                historyDetailPO.setRelatedName(relatedName);
                                historyDetailPO.setOperateDetail("未找到编号为[" + schemeNo2 + "]的方案");
                                historyDetailPO.setStatus("0");
                                OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                continue;
                            }

                            gradePO.setGradeNo(gradeNo2);
                            gradePO.setGradeName((String) map.get("grade_name"));
                            gradePO.setDescription((String) map.get("grade_description"));
                            // 关联方案id
                            gradePO.setSchemeId(schemeNew.getId());
                            gradePO.setForbiddenTag((int) map.get("forbidden_tag"));
                            gradePO.setIsUsed(1);
                            gradePO.setCreator((long) user.getUID());
                            gradePO.setDeleteType((int) map.get("delete_type"));
                            gradePO.setCreateTime((Date) map.get("create_time"));
                            gradePO.setUpdateTime((Date) map.get("update_time"));
                            String[] split = levelNo2.split(",");
                            StringBuilder levelIds = null;
                            if (split.length > 0) {
                                for (String value : split) {
                                    levelNew = MapperProxyFactory.getProxy(LevelMapper.class).getLevelByNoAndSid(value, schemeNew.getId());
                                    if (levelNew == null) {
                                        historyDetailPO.setRelatedName(relatedName);
                                        historyDetailPO.setOperateDetail("未找到编号为[" + value + "]的职等");
                                        historyDetailPO.setStatus("0");
                                        OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                        continue nextRow;
                                    }
                                    if (levelIds != null) {
                                        levelIds.append(",").append(levelNew.getId());
                                    } else {
                                        levelIds = new StringBuilder(String.valueOf(levelNew.getId()));
                                    }
                                }
                            }
                            gradeNew = MapperProxyFactory.getProxy(GradeMapper.class).getGradeByNoAndSid(gradeNo2, schemeNew.getId());
                            if (gradeNew != null) {
                                historyDetailPO.setRelatedName(relatedName);
                                historyDetailPO.setOperateDetail("同一方案[" + schemeNo2 + "]下，职级编号不可重复");
                                historyDetailPO.setStatus("0");
                                OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                continue;
                            } else {
                                // 关联职等id
                                gradePO.setLevelId(levelIds.toString());
                                MapperProxyFactory.getProxy(GradeMapper.class).insertIgnoreNull(gradePO);
                            }
                            break;
                        default:
                            break;
                    }
                    historyDetailPO.setOperateDetail("添加成功");
                    historyDetailPO.setStatus("1");
                    OrgImportUtil.saveImportDetailLog(historyDetailPO);
                } else if ("update".equals(operateType)) {
                    switch (s) {
                        case 0:
                            schemeNew = MapperProxyFactory.getProxy(SchemeMapper.class).getSchemeByNo((String) map.get("scheme_no"));
                            if (schemeNew != null) {
                                schemeNew.setSchemeName((String) map.get("scheme_name"));
                                schemeNew.setSchemeDescription((String) map.get("scheme_description"));
                                schemeNew.setUpdateTime((Date) map.get("update_time"));
                                MapperProxyFactory.getProxy(SchemeMapper.class).updateScheme(schemeNew);
                            } else {
                                historyDetailPO.setRelatedName(relatedName);
                                historyDetailPO.setOperateDetail("未找到编号为[" + map.get("scheme_no") + "]的方案");
                                historyDetailPO.setStatus("0");
                                OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                continue;
                            }
                            break;
                        case 1:
                            String schemeNo = (String) map.get("scheme_no");
                            String levelNo = (String) map.get("level_no");
                            schemeNew = MapperProxyFactory.getProxy(SchemeMapper.class).getSchemeByNo(schemeNo);
                            if (schemeNew != null) {
                                levelNew = MapperProxyFactory.getProxy(LevelMapper.class).getLevelByNoAndSid(levelNo, schemeNew.getId());
                                if (levelNew != null) {
                                    levelNew.setLevelName((String) map.get("level_name"));
                                    levelNew.setDescription((String) map.get("level_description"));
                                    //关联方案id
                                    levelNew.setSchemeId(schemeNew.getId());
                                    levelNew.setUpdateTime((Date) map.get("update_time"));
                                    MapperProxyFactory.getProxy(LevelMapper.class).updateLevel(levelNew);
                                } else {
                                    historyDetailPO.setRelatedName(relatedName);
                                    historyDetailPO.setOperateDetail("未找到编号为[" + schemeNo + "]的方案");
                                    historyDetailPO.setStatus("0");
                                    OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                    continue;
                                }
                            } else {
                                historyDetailPO.setRelatedName(relatedName);
                                historyDetailPO.setOperateDetail("未找到编号为[" + schemeNo + "]的方案，无法更新");
                                historyDetailPO.setStatus("0");
                                OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                continue;
                            }
                            break;
                        case 2:
                            String schemeNo2 = (String) map.get("scheme_no");
                            String levelNo2 = (String) map.get("level_no");
                            schemeNew = MapperProxyFactory.getProxy(SchemeMapper.class).getSchemeByNo(schemeNo2);
                            if (schemeNew == null) {
                                historyDetailPO.setRelatedName(relatedName);
                                historyDetailPO.setOperateDetail("未找到编号为[" + schemeNo2 + "]的方案");
                                historyDetailPO.setStatus("0");
                                OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                continue;
                            }
                            // 处理职级编号
                            String[] split = levelNo2.split(",");
                            StringBuilder levelIds = null;
                            if (split.length > 0) {
                                for (String value : split) {
                                    levelNew = MapperProxyFactory.getProxy(LevelMapper.class).getLevelByNoAndSid(value, schemeNew.getId());
                                    if (levelNew == null) {
                                        historyDetailPO.setRelatedName(relatedName);
                                        historyDetailPO.setOperateDetail("未找到编号为[" + value + "]的职等");
                                        historyDetailPO.setStatus("0");
                                        OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                        continue nextRow;
                                    }
                                    if (levelIds != null) {
                                        levelIds.append(",").append(levelNew.getId());
                                    } else {
                                        levelIds = new StringBuilder(String.valueOf(levelNew.getId()));
                                    }
                                }
                            }

                            if (gradeNew != null) {
                                gradeNew.setSchemeId(schemeNew.getId());
                                gradeNew.setGradeName((String) map.get("grade_name"));
                                gradeNew.setDescription((String) map.get("grade_description"));
                                // 关联职等id
                                gradeNew.setLevelId(levelIds.toString());
                                gradeNew.setUpdateTime((Date) map.get("update_time"));
                                MapperProxyFactory.getProxy(GradeMapper.class).updateGrade(gradeNew);
                            } else {
                                historyDetailPO.setRelatedName(relatedName);
                                historyDetailPO.setOperateDetail("未找到编号[" + schemeNo2 + "]的职级，无法更新");
                                historyDetailPO.setStatus("0");
                                OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                continue;
                            }

                            break;
                        default:
                            break;
                    }
                    historyDetailPO.setOperateDetail("更新成功");
                    historyDetailPO.setStatus("1");
                    OrgImportUtil.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 String getTemplatePath(String importType, String columns) throws IOException {
        // 根据选择字段、生成对应的导入模板
        String[] split = columns.split(",");
        List<Object> columnList = new ArrayList<>(Arrays.asList(split));
        List<Object> schemeList = new ArrayList<>();
        List<Object> levelList = new ArrayList<>();
        List<Object> gradeList = new ArrayList<>();
        Object companyColumn = "";
        Object departmentColumn = "";

        String companyFieldName = "所属分部";
        String departmentFieldName = "所属部门";
        switch (importType) {
            case "company":
                companyFieldName = "简称";
                departmentFieldName = "";
                break;
            case "department":
                companyFieldName = "所属分部";
                departmentFieldName = "简称";
                break;
            case "resource":
                companyFieldName = "分部";
                departmentFieldName = "部门";
                break;
            default:
                break;
        }
        // 排序
        /*
        第一列：分部
        第二列：部门
         */
        Iterator<Object> iterator = columnList.iterator();
        while (iterator.hasNext()) {
            Object column = iterator.next();
            if (companyFieldName.equals(column.toString())) {
                companyColumn = column;
                iterator.remove();
            }

            if (departmentFieldName.equals(column)) {
                departmentColumn = column;
                iterator.remove();
            }
            if ("方案编号".equals(column)) {
                schemeList.add(column);
                levelList.add(column);
                gradeList.add(column);
            }
            if ("方案名称".equals(column)) {
                schemeList.add(column);
            }
            if ("方案说明".equals(column)) {
                schemeList.add(column);
            }
            if ("职等编号".equals(column)) {
                levelList.add(0, column);
                gradeList.add(column);
            }
            if ("职等名称".equals(column)) {
                levelList.add(1, column);
            }
            if ("职等说明".equals(column)) {
                levelList.add(column);
            }
            if ("职级编号".equals(column)) {
                gradeList.add(0, column);
            }
            if ("职级名称".equals(column)) {
                gradeList.add(1, column);
            }
            if ("职级说明".equals(column)) {
                gradeList.add(column);
            }
        }
        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 = new XSSFWorkbook();
        if ("joblevel".equals(importType)) {
            excelSheetData.clear();
            excelSheetData.add(schemeList);
            ExcelUtil.genWorkbookV3(sheets, excelSheetData, 0, "方案");
            excelSheetData.clear();
            excelSheetData.add(levelList);
            ExcelUtil.genWorkbookV3(sheets, excelSheetData, 1, "职等");
            excelSheetData.clear();
            excelSheetData.add(gradeList);
            ExcelUtil.genWorkbookV3(sheets, excelSheetData, 2, "职级");
        } else {
            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;
    }

}
