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

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.MesProcessTorqueManage;
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.MesProcessTorqueManageRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
import cn.estsh.i3plus.mes.apiservice.util.MesCommonUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.MathOperation;
import cn.estsh.i3plus.platform.common.util.MesConstWords;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesPart;
import cn.estsh.i3plus.pojo.mes.bean.MesProcess;
import cn.estsh.i3plus.pojo.mes.repository.MesPartRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesProcessRepository;
import org.apache.poi.ss.usermodel.CellType;
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 : Q管理项目导入
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-04-23
 * @Modify:
 **/
@Service
public class TorqueManageExcelService implements IExcelImportExtService {

    @Autowired
    private MesProcessTorqueManageRepository mesProcessTorqueManageRDao;

    @Autowired
    private MesProcessRepository mesProcessRDao;

    @Autowired
    private MesPartRepository mesPartRDao;

    @Autowired
    private CommonExtService commonExtService;

    /**
     * 扭矩管理配置导入
     *
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractMesProcessTorqueManage(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesProcessTorqueManage(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

    /**
     * 扭矩管理配置导入-读取表格
     *
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractMesProcessTorqueManage(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //MesProcessTorqueManage集合
        List<MesProcessTorqueManage> processTorqueManageExtList = new ArrayList<>();

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

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

        //用于EXCEL表中的 partNo+工序编号+紧固位置 唯一校验
        Map<String, String> torqueManageByOnlyMap = new HashMap<>();

        //根据零件号、工序代码、管理项目、管理内容、检查内容 查询替代料中是否存在数据
        List<MesProcessTorqueManage> processTorqueManageList = mesProcessTorqueManageRDao.findByProperty(
                new String[]{MesConstWords.ORGANIZE_CODE, MesConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesProcessTorqueManage>> processTorqueManageMap = CollectionUtils.isEmpty(processTorqueManageList) ? null :
                processTorqueManageList.stream().filter(o -> null != o).collect(Collectors.groupingBy(o -> new StringJoiner(MesExtConstWords.AND).add(o.getProcessCode()).add(o.getPartNo()).add(o.getFasteningPosition()).toString()));

        // 查询物料表
        Map<String, Object> partNoEntityMap;
        try {
            partNoEntityMap = MesCommonUtil.getCodeEntityMap(mesPartRDao, MesExtConstWords.PART_NO, organizeCode, "物料表");
        } catch (Exception e) {
            partNoEntityMap = null;
        }

        // 查询工序表
        Map<String, Object> processCodeEntityMap;
        try {
            processCodeEntityMap = MesCommonUtil.getCodeEntityMap(mesProcessRDao, MesExtConstWords.PROCESS_CODE, organizeCode, "工序表");
        } catch (Exception e) {
            processCodeEntityMap = null;
        }

        //从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 = ""; //错误信息

                //工序编号
                try {
                    //第一列必须有值，否则跳过
                    row.getCell(0).setCellType(CellType.STRING);
                } catch (Exception e) {
                    continue;
                }
                String processCode = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                String processName = null;

                //零件编号
                String partNo = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    partNo = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //紧固部位
                String fasteningPosition = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    fasteningPosition = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //规格
                String specification = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    specification = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //上限值
                String upLimit = null;
                try {
                    row.getCell(4).setCellType(CellType.STRING);
                    upLimit = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //下限值
                String downLimit = null;
                try {
                    row.getCell(5).setCellType(CellType.STRING);
                    downLimit = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //校验工序编号
                if (StringUtils.isEmpty(processCode)) {
                    errorNum++;
                    cellNum += "A;";
                    errorInfo += "第A列数据必填;";
                } else if (!processCodeEntityMap.containsKey(processCode)) {
                    errorNum++;
                    cellNum += "A;";
                    errorInfo += "第A列数据无效;";
                } else {
                    processName = ((MesProcess) processCodeEntityMap.get(processCode)).getProcessName();
                }

                String partName = null;

                //校验零件编号
                if (!StringUtils.isEmpty(partNo)) {
                    if (!partNoEntityMap.containsKey(partNo)) {
                        errorNum++;
                        cellNum += "B;";
                        errorInfo += "第B列数据无效;";
                    } else {
                        partName = ((MesPart)partNoEntityMap.get(partNo)).getPartName();
                    }
                }

                //校验紧固部位
                if (StringUtils.isEmpty(fasteningPosition)) {
                    errorNum++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                }

                //校验规格
                if(StringUtils.isEmpty(specification)){
                    errorNum ++;
                    cellNum += "D;";
                    errorInfo += "第D列数据必填;";
                }

                String key = new StringJoiner(MesExtConstWords.AND).add(processCode).add(partNo).add(fasteningPosition).toString();

                Boolean isExist = false;

                //校验唯一性 不重复
                if (!torqueManageByOnlyMap.containsKey(key)) {
                    torqueManageByOnlyMap.put(key, String.valueOf(rowNum));
                    //根据零件号、工序代码、紧固部位查询替代料中是否存在数据

                    if (StringUtils.isEmpty(errorInfo) && !CollectionUtils.isEmpty(processTorqueManageMap) && processTorqueManageMap.containsKey(key)) {
                        errorNum++;
                        cellNum += "A+B+C;";
                        errorInfo += "第A+B+C列数据已经存在数据库;";
                    }

                    //校验是否已经存在数据库
                    if (!CollectionUtils.isEmpty(processTorqueManageMap) && processTorqueManageMap.containsKey(key)) isExist = true;
                } else {
                    errorNum++;
                    cellNum += "A+B+C;";
                    errorInfo += "第A+B+C列数据跟第" + torqueManageByOnlyMap.get(key) +
                            "行的第A+B+C列数据重复;";
                }

                //校验上限值
                if (!StringUtils.isEmpty(upLimit)) {
                    try {
                        Double.parseDouble(upLimit);
                    } catch (NumberFormatException e) {
                        errorNum++;
                        cellNum += "E;";
                        errorInfo += "第E列数据无效;";
                    }
                    String[] upLimitArr = upLimit.split(MesExtConstWords.DECIMAL_POINT);
                    if (null != upLimitArr && upLimitArr.length == 2 && upLimitArr[1].length() > 2) {
                        errorNum++;
                        cellNum += "E;";
                        errorInfo += "第E列数据无效,最多2位小数;";
                    }

                    if (StringUtils.isEmpty(downLimit)) {
                        errorNum++;
                        cellNum += "E+F;";
                        errorInfo += "第E列跟第F列数据不能只填写其中一个;";
                    }
                }

                //校验下限值
                if (!StringUtils.isEmpty(downLimit)) {
                    try {
                        Double.parseDouble(downLimit);
                    } catch (NumberFormatException e) {
                        errorNum++;
                        cellNum += "F;";
                        errorInfo += "第F列数据无效;";
                    }
                    String[] downLimitArr = downLimit.split(MesExtConstWords.DECIMAL_POINT);
                    if (null != downLimitArr && downLimitArr.length == 2 && downLimitArr[1].length() > 2) {
                        errorNum++;
                        cellNum += "F;";
                        errorInfo += "第F列数据无效,最多2位小数;";
                    }
                    if (StringUtils.isEmpty(upLimit)) {
                        errorNum++;
                        cellNum += "E+F;";
                        errorInfo += "第E列跟第F列数据不能只填写其中一个;";
                    }
                }

                if (StringUtils.isEmpty(errorInfo) && !StringUtils.isEmpty(upLimit) && !StringUtils.isEmpty(downLimit)) {
                    if (MathOperation.compareTo(Double.parseDouble(upLimit), Double.parseDouble(downLimit)) < 0) {
                        errorNum++;
                        cellNum += "E+F;";
                        errorInfo += "第E列数据只能大于等于第F列数据;";
                    }
                }

                //没有错误的时候，封装MesProcessTorqueManage
                if (errorNum == 0) {
                    MesProcessTorqueManage mesProcessTorqueManage;
                    if (isExist) {
                        mesProcessTorqueManage = processTorqueManageMap.get(key).get(0);
                        ConvertBean.serviceModelUpdate(mesProcessTorqueManage, userName);

                    } else {
                        mesProcessTorqueManage = new MesProcessTorqueManage();
                        ConvertBean.serviceModelInitialize(mesProcessTorqueManage, userName);
                        mesProcessTorqueManage.setPartNo(partNo);
                        mesProcessTorqueManage.setPartName(partName);
                        mesProcessTorqueManage.setProcessCode(processCode);
                    }

                    mesProcessTorqueManage.setProcessName(processName);
                    mesProcessTorqueManage.setFasteningPosition(fasteningPosition);
                    mesProcessTorqueManage.setSpecification(specification);
                    mesProcessTorqueManage.setOrganizeCode(organizeCode);
                    mesProcessTorqueManage.setUpLimit(upLimit);
                    mesProcessTorqueManage.setDownLimit(downLimit);
                    mesProcessTorqueManage.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());

                    processTorqueManageExtList.add(mesProcessTorqueManage);

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

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

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

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

    /**
     * 扭矩管理导入-数据入库
     *
     * @param excelImportResultExtModel
     */
    private void insertExcelMesProcessTorqueManage(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesProcessTorqueManage> processTorqueManageList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(processTorqueManageList)) mesProcessTorqueManageRDao.saveAll(processTorqueManageList);
        }
    }
}
