package cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.excel.bu3;

import cn.estsh.i3plus.ext.mes.api.base.IExcelImportExtService;
import cn.estsh.i3plus.ext.mes.api.base.bu.IBusiConfigService;
import cn.estsh.i3plus.ext.mes.api.base.bu3.ISxPartCategoryPlanRateService;
import cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.base.CommonExtService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesCareerCorrelationCfg;
import cn.estsh.i3plus.ext.mes.pojo.model.ExcelImportErrorExtModel;
import cn.estsh.i3plus.ext.mes.pojo.model.ExcelImportResultExtModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesCareerCorrelationCfgRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.MathOperation;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description :事业别相关配置导入
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-04-23
 * @Modify:
 **/
@Service
public class SxCareerCorrelationCfgExcelService implements IExcelImportExtService {

    @Autowired
    private IBusiConfigService busiConfigService;

    @Autowired
    private MesCareerCorrelationCfgRepository careerCorrelationCfgRepository;

    @Autowired
    private ISxPartCategoryPlanRateService partCategoryPlanRateService;

    @Autowired
    private CommonExtService commonExtService;

    /**
     * 事业别相关配置导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractMesCareerCorrelationCfg(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesCareerCorrelationCfg(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

    /**
     * 事业别相关配置导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractMesCareerCorrelationCfg(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //MesCareerCorrelationCfg集合
        List<MesCareerCorrelationCfg> partCategoryTargetCfgList = new ArrayList<>();

        //成功数量
        Integer successRowNum = 0;
        //失败数量
        Integer failRowNum = 0;
        //错误的行号
        String errorRows = "";

        //错误行信息集合
        List<ExcelImportErrorExtModel> excelImportErrorExtModels = new ArrayList<>();

        Map<String, String> existMap = new HashMap<>();

        Map<String, String> careerMap = busiConfigService.getConfigMap(organizeCode, MesExtConstWords.SX_CAREER_CFG);

        Map<String, String> categoryMap = partCategoryPlanRateService.getCategoryMap(organizeCode);

        List<MesCareerCorrelationCfg> careerCorrelationCfgDbList = careerCorrelationCfgRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED}, new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesCareerCorrelationCfg>> careerCorrelationCfgDbMapByCareer = CollectionUtils.isEmpty(careerCorrelationCfgDbList) ? null :
                careerCorrelationCfgDbList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getCareerCode()) && StringUtils.isEmpty(o.getCategoryCode()) && !StringUtils.isEmpty(o.getDataType()) && !StringUtils.isEmpty(o.getDataKey())))
                        .collect(Collectors.groupingBy(o -> new StringJoiner(MesExtConstWords.AND).add(o.getCareerCode()).add(MesExtConstWords.ONE_SPACE).add(o.getDataType()).add(o.getDataKey()).toString()));
        Map<String, List<MesCareerCorrelationCfg>> careerCorrelationCfgDbMapByCategory = CollectionUtils.isEmpty(careerCorrelationCfgDbList) ? null :
                careerCorrelationCfgDbList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getCategoryCode()) && !StringUtils.isEmpty(o.getDataType()) && !StringUtils.isEmpty(o.getDataKey())))
                        .collect(Collectors.groupingBy(o -> new StringJoiner(MesExtConstWords.AND).add(MesExtConstWords.ONE_SPACE).add(o.getCategoryCode()).add(o.getDataType()).add(o.getDataKey()).toString()));

        //从excel表的第5行数据开始导入，getFirstRowNum是从0行开始读取
        for (int i = (sheetAt.getFirstRowNum() + 4); i < totalNumberOfRows; i ++) {
            Row row = sheetAt.getRow(i);
            //空行跳过
            if (null == row) {
                continue;
            }
            //获取总列数
            Short lastCellNum = row.getLastCellNum();
            if (lastCellNum > 0) {

                int rowNum = i + 1;    //当前行号
                int errorNum = 0;      //错误数量
                String cellNum = "";   //错误列号
                String errorInfo = ""; //错误信息

                //数据类型
                String dataTypeDesc;
                String dataType;
                try {
                    dataTypeDesc = new DataFormatter().formatCellValue(row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                    continue;
                }

                //事业别代码
                String careerCode;
                try {
                    careerCode = new DataFormatter().formatCellValue(row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                    continue;
                }

                //产品别代码
                String categoryCode;
                try {
                    categoryCode = new DataFormatter().formatCellValue(row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                    continue;
                }

                //配置键
                String dataKey = null;
                try {
                    dataKey = new DataFormatter().formatCellValue(row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //配置值1
                String cfgValue = null;
                try {
                    cfgValue = new DataFormatter().formatCellValue(row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //配置值2
                String cfgValue2 = null;
                try {
                    cfgValue2 = new DataFormatter().formatCellValue(row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //配置值3
                String cfgValue3 = null;
                try {
                    cfgValue3 = new DataFormatter().formatCellValue(row.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                dataType = MesExtEnumUtil.CAREER_CORRELATION_CFG_DATA_TYPE.descriptionOfValue(dataTypeDesc);
                if (StringUtils.isEmpty(dataType)) {
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据无效;";
                }

                if (!StringUtils.isEmpty(careerCode) && (CollectionUtils.isEmpty(careerMap) || !careerMap.containsKey(careerCode))) {
                    errorNum ++;
                    cellNum += "B;";
                    errorInfo += "第B列数据无效;";
                }

                if (!StringUtils.isEmpty(categoryCode) && (CollectionUtils.isEmpty(categoryMap) || !categoryMap.containsKey(categoryCode))) {
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据无效;";
                }

                if (MesExtEnumUtil.CAREER_CORRELATION_CFG_DATA_TYPE.COMPOSITE_RATE_TARGET.getValue().equals(dataType)) {
                    if (StringUtils.isEmpty(careerCode) && StringUtils.isEmpty(categoryCode)) {
                        errorNum ++;
                        cellNum += "B+C;";
                        errorInfo += "第B+C列数据至少必填一个;";
                    }
                } else {
                    if (StringUtils.isEmpty(careerCode)) {
                        errorNum ++;
                        cellNum += "B;";
                        errorInfo += "第B列数据必填;";
                    }
                    if (StringUtils.isEmpty(categoryCode)) {
                        errorNum ++;
                        cellNum += "C;";
                        errorInfo += "第C列数据必填;";
                    }
                }


                //验证配置键
                if (StringUtils.isEmpty(dataKey)) {
                    errorNum ++;
                    cellNum += "D;";
                    errorInfo += "第D列数据必填;";
                }

                //验证配置值
                if (StringUtils.isEmpty(cfgValue)) {
                    errorNum ++;
                    cellNum += "E;";
                    errorInfo += "第E列数据必填;";
                } else {
                    try {
                        if (MathOperation.compareTo(new Double(cfgValue), new Double(0)) < 0) {
                            errorNum++;
                            cellNum += "E;";
                            errorInfo += "第E列数据无效,必须是正数,最多四位小数;";
                        }
                        String[] cfgValueArr = cfgValue.split(MesExtConstWords.DECIMAL_POINT);
                        if (null != cfgValueArr && cfgValueArr.length == 2 && cfgValueArr[1].length() > 4) {
                            errorNum++;
                            cellNum += "E;";
                            errorInfo += "第E列数据无效,必须是正数,最多四位小数;";
                        }
                    } catch (NumberFormatException e) {
                        errorNum++;
                        cellNum += "E;";
                        errorInfo += "第E列数据无效,必须是正数,最多四位小数;";
                    }
                }

                if (MesExtEnumUtil.CAREER_CORRELATION_CFG_DATA_TYPE.COMPOSITE_RATE_TARGET.getValue().equals(dataType)) {
                    //验证配置值
                    if (StringUtils.isEmpty(cfgValue2)) {
                        errorNum ++;
                        cellNum += "F;";
                        errorInfo += "第F列数据必填;";
                    } else {
                        try {
                            if (MathOperation.compareTo(new Double(cfgValue2), new Double(0)) < 0) {
                                errorNum++;
                                cellNum += "F;";
                                errorInfo += "第F列数据无效,必须是正数,最多四位小数;";
                            }
                            String[] cfgValueArr = cfgValue2.split(MesExtConstWords.DECIMAL_POINT);
                            if (null != cfgValueArr && cfgValueArr.length == 2 && cfgValueArr[1].length() > 4) {
                                errorNum++;
                                cellNum += "F;";
                                errorInfo += "第F列数据无效,必须是正数,最多四位小数;";
                            }
                        } catch (NumberFormatException e) {
                            errorNum++;
                            cellNum += "F;";
                            errorInfo += "第F列数据无效,必须是正数,最多四位小数;";
                        }
                    }

                    //验证配置值
                    if (StringUtils.isEmpty(cfgValue3)) {
                        errorNum ++;
                        cellNum += "G;";
                        errorInfo += "第G列数据必填;";
                    } else {
                        try {
                            if (MathOperation.compareTo(new Double(cfgValue3), new Double(0)) < 0) {
                                errorNum++;
                                cellNum += "G;";
                                errorInfo += "第G列数据无效,必须是正数,最多四位小数;";
                            }
                            String[] cfgValueArr = cfgValue3.split(MesExtConstWords.DECIMAL_POINT);
                            if (null != cfgValueArr && cfgValueArr.length == 2 && cfgValueArr[1].length() > 4) {
                                errorNum++;
                                cellNum += "G;";
                                errorInfo += "第G列数据无效,必须是正数,最多四位小数;";
                            }
                        } catch (NumberFormatException e) {
                            errorNum++;
                            cellNum += "G;";
                            errorInfo += "第G列数据无效,必须是正数,最多四位小数;";
                        }
                    }
                }

                Boolean isExist = false;
                String key = StringUtils.isEmpty(categoryCode) ?
                        new StringJoiner(MesExtConstWords.AND).add(careerCode).add(MesExtConstWords.ONE_SPACE).add(dataType).add(dataKey).toString() :
                        new StringJoiner(MesExtConstWords.AND).add(MesExtConstWords.ONE_SPACE).add(categoryCode).add(dataType).add(dataKey).toString();
                if (StringUtils.isEmpty(errorInfo)) {
                    if (!existMap.containsKey(key)) {
                        existMap.put(key, String.valueOf(rowNum));
                        //校验是否已经存在数据库
                        if (!CollectionUtils.isEmpty(careerCorrelationCfgDbMapByCareer) && careerCorrelationCfgDbMapByCareer.containsKey(key)) isExist = true;
                        if (!CollectionUtils.isEmpty(careerCorrelationCfgDbMapByCategory) && careerCorrelationCfgDbMapByCategory.containsKey(key)) isExist = true;
                    } else {
                        errorNum ++;
                        cellNum += "A+B+C+D;";
                        errorInfo += "第A+B+C+D列数据跟第" + existMap.get(key) + "行的数据重复;";
                    }
                }

                //没有错误的时候，封装MesCareerCorrelationCfg
                if (errorNum == 0) {
                    MesCareerCorrelationCfg partCategoryTargetCfg;
                    if (isExist) {
                        partCategoryTargetCfg = (!CollectionUtils.isEmpty(careerCorrelationCfgDbMapByCareer) && careerCorrelationCfgDbMapByCareer.containsKey(key)) ? careerCorrelationCfgDbMapByCareer.get(key).get(0) : careerCorrelationCfgDbMapByCategory.get(key).get(0);
                        partCategoryTargetCfg.setIsValid(CommonEnumUtil.IS_VAILD.VAILD.getValue());
                        ConvertBean.serviceModelUpdate(partCategoryTargetCfg, userName);
                    } else {
                        partCategoryTargetCfg = new MesCareerCorrelationCfg();
                        ConvertBean.serviceModelInitialize(partCategoryTargetCfg, userName);
                    }

                    partCategoryTargetCfg.setCareerCode(careerCode);
                    partCategoryTargetCfg.setCategoryCode(categoryCode);
                    partCategoryTargetCfg.setWorkCenterCode("");
                    partCategoryTargetCfg.setDataType(dataType);
                    partCategoryTargetCfg.setDataKey(dataKey);
                    if (!MesExtEnumUtil.CAREER_CORRELATION_CFG_DATA_TYPE.COMPOSITE_RATE_TARGET.getValue().equals(dataType)) partCategoryTargetCfg.setCfgValue(cfgValue);
                    else partCategoryTargetCfg.setCfgValue(new StringJoiner(MesExtConstWords.COMMA).add(cfgValue).add(cfgValue2).add(cfgValue3).toString());
                    partCategoryTargetCfg.setOrganizeCode(organizeCode);
                    partCategoryTargetCfg.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());

                    partCategoryTargetCfgList.add(partCategoryTargetCfg);

                    successRowNum ++;
                } else {
                    //封装错误行信息ExcelImportErrorExtModel
                    excelImportErrorExtModels = commonExtService.getExcelImportErrorModels(excelImportErrorExtModels, rowNum, errorNum, cellNum, errorInfo);

                    errorRows += rowNum + ";";
                    failRowNum ++;
                }
            }
        }

        //校验EXCEL数据
        commonExtService.checkExcelData(failRowNum, successRowNum, errorRows);

        //封装返回结果
        ExcelImportResultExtModel excelImportResultModel = commonExtService.getExcelImportResultModel(failRowNum, successRowNum, excelImportErrorExtModels, errorRows);
        excelImportResultModel.setExcelList((failRowNum > 0) ? null : partCategoryTargetCfgList);
        return excelImportResultModel;
    }

    /**
     * 事业别相关配置导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelMesCareerCorrelationCfg(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesCareerCorrelationCfg> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesCareerCorrelationCfg careerCorrelationCfg : excelList) {
                    if (StringUtils.isEmpty(careerCorrelationCfg.getId())) {
                        careerCorrelationCfgRepository.insert(careerCorrelationCfg);
                    } else {
                        careerCorrelationCfgRepository.save(careerCorrelationCfg);
                    }
                }
            }
        }
    }
}
