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.postion.po.PostInfoPO;
import com.engine.organization.entity.postion.po.PostPO;
import com.engine.organization.mapper.post.PostInfoMapper;
import com.engine.organization.mapper.post.PostMapper;
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.*;

/**
 * @author:ml
 * @createTime:2022/11/9
 * @version:1.0
 */
public class PostInfoImportUtil {
    static Map<String, ExtendInfoPO> importFieldsMap;

    static {
        importFieldsMap = new HashMap<>();
        importFieldsMap.put("编号", ExtendInfoPO.builder().tableName("jcl_org_post").fieldName("post_info_no").fieldNameDesc("编号").isrequired(1).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("名称", ExtendInfoPO.builder().tableName("jcl_org_post").fieldName("post_info_name").fieldNameDesc("名称").isrequired(1).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("权限", ExtendInfoPO.builder().tableName("jcl_org_post").fieldName("post_info_authority").fieldNameDesc("权限").isrequired(0).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("责任", ExtendInfoPO.builder().tableName("jcl_org_post").fieldName("post_info_duty").fieldNameDesc("责任").isrequired(0).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("资格", ExtendInfoPO.builder().tableName("jcl_org_post").fieldName("post_info_qualification").fieldNameDesc("资格").isrequired(0).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("职务分类", ExtendInfoPO.builder().tableName("jcl_org_post").fieldName("post_name").fieldNameDesc("职务分类").isrequired(1).controlType(1).browserType("1").customValue("[\"input\",\"text\",\"100\"]").build());
        importFieldsMap.put("描述说明", ExtendInfoPO.builder().tableName("jcl_org_post").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("staff_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<>();
            PostInfoPO postInfoPO = null;
            PostInfoPO postInfoPoNew = new PostInfoPO();
            PostPO postPO = null;
            PostPO postPoNew = new PostPO();

            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;
                    try {
                        reallyValue = OrgImportUtil.getReallyValue(infoPO, cellValue);
                    } catch (Exception e) {
                        historyDetailPO.setOperateDetail(cellValue + "转换失败");
                        historyDetailPO.setStatus("0");
                        OrgImportUtil.saveImportDetailLog(historyDetailPO);
                        continue nextRow;
                    }

                    if (StringUtils.isNotBlank(cellValue) && StringUtils.isBlank(Util.null2String(reallyValue))) {
                        historyDetailPO.setOperateDetail(infoPO.getFieldNameDesc() + "数据转换失败,未找到对应数据");
                        historyDetailPO.setStatus("0");
                        OrgImportUtil.saveImportDetailLog(historyDetailPO);
                        continue nextRow;
                    }
                    map.put(infoPO.getFieldName(), reallyValue);
                    // 职务信息编号是否重复
                    if ("post_info_no".equals(infoPO.getFieldName())){
                        List<PostInfoPO> postInfoPOS = MapperProxyFactory.getProxy(PostInfoMapper.class).listByNo(Util.null2String(reallyValue));
                        if(postInfoPOS.size()>0){
                            historyDetailPO.setRelatedName("");
                            historyDetailPO.setOperateDetail("编号:" + reallyValue + ",编号不允许重复");
                            historyDetailPO.setStatus("0");
                            OrgImportUtil.saveImportDetailLog(historyDetailPO);
                            continue nextRow;
                        }
                    }
                }
            }
            // 校验、数据交互
            if (i == 0) {
                continue;
            }
            //处理职务分类：判断是否存在，不存在则新增
            String postName = (String)map.get("post_name");
            postPO = MapperProxyFactory.getProxy(PostMapper.class).getPostByName(postName);
            if(postPO==null){
                postPoNew.setPostName(postName);
                postPoNew.setCreator((long) user.getUID());
                postPoNew.setDeleteType(0);
                postPoNew.setCreateTime(currDate);
                postPoNew.setUpdateTime(currDate);
                MapperProxyFactory.getProxy(PostMapper.class).insertIgnoreNull(postPoNew);
            }
            postPO = MapperProxyFactory.getProxy(PostMapper.class).getPostByName(postName);
            postInfoPoNew.setPostInfoNo((String)map.get("post_info_no"));
            postInfoPoNew.setPostInfoName((String) map.get("post_info_name"));
            postInfoPoNew.setPostId(postPO.getId());
            postInfoPoNew.setDescription((String)map.get("description"));
            postInfoPoNew.setPostInfoAuthority((String)map.get("post_info_authority"));
            postInfoPoNew.setPostInfoDuty((String)map.get("post_info_duty"));
            postInfoPoNew.setPostInfoQualification((String) map.get("post_info_qualification"));
            postInfoPoNew.setForbiddenTag(0);
            postInfoPoNew.setCreator((long) user.getUID());
            postInfoPoNew.setCreateTime(currDate);
            postInfoPoNew.setUpdateTime(currDate);
            MapperProxyFactory.getProxy(PostInfoMapper.class).insertIgnoreNull(postInfoPoNew);

            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<>();
        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/postinfo.xls");
            }
            item.put("value", value);
            itemList.add(item);
        }
        groupItem.put("items", itemList);
        lsGroup.add(groupItem);
        return lsGroup;
    }
}
