package com.engine.organization.util.saveimport;


import com.engine.organization.entity.extend.po.ExtendInfoPO;
import com.engine.organization.entity.jclimport.po.JclImportHistoryDetailPO;

import com.engine.organization.entity.scheme.po.SchemePO;
import com.engine.organization.entity.sequence.po.SequencePO;
import com.engine.organization.mapper.comp.CompMapper;
import com.engine.organization.mapper.scheme.SchemeMapper;
import com.engine.organization.mapper.sequence.SequenceMapper;
import com.engine.organization.util.OrganizationAssert;
import com.engine.organization.util.db.MapperProxyFactory;
import org.apache.commons.lang3.StringUtils;
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.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

import java.io.IOException;
import java.util.*;

/**
 * @Description: 岗位序列
 * @Author: liang.cheng
 * @Date: 2024/3/12 2:17 PM
 * @param:
 * @return:
 */
public class SequenceImportUtil {
    static Map<String, ExtendInfoPO> importFieldsMap;

    static {
        importFieldsMap = new HashMap<>();
        importFieldsMap.put("编号", ExtendInfoPO.builder().tableName("jcl_org_sequence").fieldName("sequence_no").fieldNameDesc("编号").isrequired(1).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("名称", ExtendInfoPO.builder().tableName("jcl_org_sequence").fieldName("sequence_name").fieldNameDesc("名称").isrequired(1).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("等级方案", ExtendInfoPO.builder().tableName("jcl_org_sequence").fieldName("scheme_name").fieldNameDesc("等级方案").isrequired(1).controlType(1).browserType("3").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("方案所属分部", ExtendInfoPO.builder().tableName("jcl_org_sequence").fieldName("subcompanyname").fieldNameDesc("方案所属分部").isrequired(1).controlType(1).browserType("3").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("描述说明", ExtendInfoPO.builder().tableName("jcl_org_sequence").fieldName("description").fieldNameDesc("描述说明").isrequired(0).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());

    }



    public static Long saveImport(String operateType, String excelFile, User user) {
        Long importHistoryId = OrgImportUtil.saveImportLog("sequence_info", 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);
        }
        // 当前sheet
        XSSFSheet sheetAt = workbook.getSheetAt(0);
        int lastRow = sheetAt.getLastRowNum();
        OrganizationAssert.isTrue(lastRow > 0, "文件数据为空");
        short lastCellNum = sheetAt.getRow(0).getLastCellNum();
        List<ExtendInfoPO> extendInfoPOS = new ArrayList<>();
        Date currDate = new Date();
        // 遍历每一行数据
        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<>(16);
            Integer parentCompanyId = null;

            historyDetailPO.setRowNums(String.valueOf(i + 1));
            for (int cellIndex = 0; cellIndex < lastCellNum; cellIndex++) {
                XSSFCell cell = row.getCell((short) cellIndex);
                String cellValue = OrgImportUtil.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("");
                        historyDetailPO.setOperateDetail(infoPO.getFieldNameDesc() + "为必填项");
                        historyDetailPO.setStatus("0");
                        OrgImportUtil.saveImportDetailLog(historyDetailPO);
                        continue nextRow;
                    }

                    Object reallyValue = cellValue;

                    if ("subcompanyname".equalsIgnoreCase(infoPO.getFieldName())) {
                        historyDetailPO.setRelatedName(cellValue);
                        String[] split = cellValue.split(">");
                        if (split.length > 0) {
                            if (split.length > 8) {
                                historyDetailPO.setOperateDetail("分部层级不能大于10");
                                historyDetailPO.setStatus("0");
                                OrgImportUtil.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");
                                    OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                    continue nextRow;
                                }
                            }
                        }
                        map.put("subcompanyid", Util.null2String(parentCompanyId));
                    }

                    // 编号是否重复
                    if ("sequence_no".equals(infoPO.getFieldName())){
                        List<SequencePO> sequencePOS = MapperProxyFactory.getProxy(SequenceMapper.class).listByNo(Util.null2String(reallyValue));
                        if(sequencePOS.size()>0){
                            historyDetailPO.setRelatedName("");
                            historyDetailPO.setOperateDetail("编号:" + reallyValue + ","+SystemEnv.getHtmlLabelName(547137, user.getLanguage()));
                            historyDetailPO.setStatus("0");
                            OrgImportUtil.saveImportDetailLog(historyDetailPO);
                            continue nextRow;
                        }
                    }

                    map.put(infoPO.getFieldName(), reallyValue);

                }
            }
            if (i == 0) {
                continue nextRow;
            }
          String subCompanyName = (String) map.get("scheme_name");
          String subCompanyId = (String) map.get("subcompanyid");

          List<SchemePO> schemePOS = MapperProxyFactory.getProxy(SchemeMapper.class).selectByParams(Integer.parseInt(subCompanyId), subCompanyName);
          if (schemePOS.size() == 0){
              historyDetailPO.setRelatedName("");
              historyDetailPO.setOperateDetail("第"+i+"行,所属分部下的等级方案不存在");
              historyDetailPO.setStatus("0");
              OrgImportUtil.saveImportDetailLog(historyDetailPO);
              continue nextRow;
          }

            SequencePO build = SequencePO.builder()
                    .sequenceNo((String) map.get("sequence_no"))
                    .sequenceName((String) map.get("sequence_name"))
                    .schemeId(schemePOS.get(0).getId())
                    .description((String) map.get("description"))
                    .build();
            MapperProxyFactory.getProxy(SequenceMapper.class).insertIgnoreNull(build);
            historyDetailPO.setOperateDetail("添加成功");
            historyDetailPO.setStatus("1");
            OrgImportUtil.saveImportDetailLog(historyDetailPO);
        }

        return importHistoryId;
    }


    public static List<Map<String, Object>> importForm(User user) {
        // 返回导入数据
        List<Map<String, Object>> lsGroup = new ArrayList<>();
        Map<String, Object> groupItem = new HashMap<>(3);
        List<Object> itemList = new ArrayList<>();
        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", "/hrm/import/template/sequence.xls");
            }
            item.put("value", value);
            itemList.add(item);
        }
        Map<String,Object> map = new HashMap<String,Object>(2){{
            put("index",3);
            put("value",SystemEnv.getHtmlLabelName(547228,user.getLanguage()));
        }};
        itemList.add(map);
        groupItem.put("items", itemList);
        lsGroup.add(groupItem);
        return lsGroup;
    }
}
