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.apiservice.serviceimpl.base.CommonExtService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesPartCategoryPlanRate;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesPartCategoryTargetCfg;
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.MesPartCategoryPlanRateRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesPartCategoryTargetCfgRepository;
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 SxPartCategoryTargetCfgExcelService implements IExcelImportExtService {

    @Autowired
    private MesPartCategoryPlanRateRepository partCategoryPlanRateRepository;

    @Autowired
    private MesPartCategoryTargetCfgRepository partCategoryTargetCfgRepository;

    @Autowired
    private CommonExtService commonExtService;

    /**
     * 产品类别目标配置导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractMesPartCategoryTargetCfg(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesPartCategoryTargetCfg(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

    /**
     * 产品类别目标配置导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractMesPartCategoryTargetCfg(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

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

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

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

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

        List<MesPartCategoryPlanRate> partCategoryPlanRateDbList = partCategoryPlanRateRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue()});
        Map<String, List<MesPartCategoryPlanRate>> partCategoryPlanRateDbMap = CollectionUtils.isEmpty(partCategoryPlanRateDbList) ? null :
                partCategoryPlanRateDbList.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesPartCategoryPlanRate::getCategoryCode));

        List<MesPartCategoryTargetCfg> partCategoryTargetCfgDbList = partCategoryTargetCfgRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED}, new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesPartCategoryTargetCfg>> partCategoryTargetCfgDbMap = CollectionUtils.isEmpty(partCategoryTargetCfgDbList) ? null :
                partCategoryTargetCfgDbList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getCategoryCode()) && !StringUtils.isEmpty(o.getDataKey())))
                        .collect(Collectors.groupingBy(o -> new StringJoiner(MesExtConstWords.AND).add(o.getCategoryCode()).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 categoryCode;
                try {
                    categoryCode = new DataFormatter().formatCellValue(row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                    continue;
                }

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

                //目标
                String cfgValue = null;
                try {
                    cfgValue = new DataFormatter().formatCellValue(row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //ST能率目标
                String cfgValue2 = null;
                try {
                    cfgValue2 = new DataFormatter().formatCellValue(row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //比例
                String rate = null;
                try {
                    rate = new DataFormatter().formatCellValue(row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

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

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

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

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

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

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

                //没有错误的时候，封装MesPartCategoryTargetCfg
                if (errorNum == 0) {
                    MesPartCategoryTargetCfg partCategoryTargetCfg;
                    if (isExist) {
                        partCategoryTargetCfg = partCategoryTargetCfgDbMap.get(key).get(0);
                        partCategoryTargetCfg.setIsValid(CommonEnumUtil.IS_VAILD.VAILD.getValue());
                        ConvertBean.serviceModelUpdate(partCategoryTargetCfg, userName);
                    } else {
                        partCategoryTargetCfg = new MesPartCategoryTargetCfg();
                        ConvertBean.serviceModelInitialize(partCategoryTargetCfg, userName);
                    }

                    partCategoryTargetCfg.setCategoryCode(categoryCode);
                    partCategoryTargetCfg.setDataKey(dataKey);
                    partCategoryTargetCfg.setCfgValue(cfgValue);
                    partCategoryTargetCfg.setCfgValue2(cfgValue2);
                    partCategoryTargetCfg.setRate(rate);
                    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 insertExcelMesPartCategoryTargetCfg(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesPartCategoryTargetCfg> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesPartCategoryTargetCfg partCategoryTargetCfg : excelList) {
                    if (StringUtils.isEmpty(partCategoryTargetCfg.getId())) {
                        partCategoryTargetCfgRepository.insert(partCategoryTargetCfg);
                    } else {
                        partCategoryTargetCfgRepository.save(partCategoryTargetCfg);
                    }
                }
            }
        }
    }
}
