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

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.MesProcessFirstItem;
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.MesProcessFirstItemRepository;
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.pojo.base.enumutil.CommonEnumUtil;
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;

/**
 * @Author: xiangming.liao
 * @CreateDate: 2021/02/03 15:34
 * @Description: 工序首检项目导入
 **/
@Service
public class ProcessFirstItemExtExcelService implements IExcelImportExtService {

    @Autowired
    private MesProcessFirstItemRepository processFirstItemRepository;

    @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.sheetExtractMesProcessFirstItem(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesProcessFirstItem(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

    /**
     * 工序首检项目导入-读取表格
     *
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractMesProcessFirstItem(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //MesProcessFirstItem集合
        List<MesProcessFirstItem> processCheckExtList = new ArrayList<>();

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

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

        //用于EXCEL表中的 零件编号+工序编号+检测信息 唯一校验  key：partNo&processCode&checkMessage，value：row
        Map<String, String> processFirstItemByOnlyMap = new HashMap<>();

        // 查询物料表
        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;
        }

        //查询4M变化表
        List<MesProcessFirstItem> processFirstItems = processFirstItemRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});

        Map<String, List<MesProcessFirstItem>> processFirstItemMap = CollectionUtils.isEmpty(processFirstItems) ? null :
                processFirstItems.stream().filter(o -> null != o)
                        .collect(Collectors.groupingBy(o -> new StringJoiner(MesExtConstWords.AND).add(o.getPartNo()).add(o.getProcessCode()).add(o.getCheckMessage()).add(o.getCheckStand()).add(o.getManageType()).add(getImportanceSafePartNo(o.getManageType(), o.getImportanceSafePartNo())).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 = ""; //错误信息

                //工序代码
                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 manageType = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    manageType = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //重要安全部品编码
                String importanceSafePartNo = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    importanceSafePartNo = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //检测信息
                String checkMessage = null;
                try {
                    row.getCell(4).setCellType(CellType.STRING);
                    checkMessage = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //检查频度
                String checkFrequency = null;
                try {
                    row.getCell(5).setCellType(CellType.STRING);
                    checkFrequency = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //样品数量
                String sampleQty = null;
                try {
                    row.getCell(6).setCellType(CellType.STRING);
                    sampleQty = row.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //确认方法
                String confirmMethod = null;
                try {
                    row.getCell(7).setCellType(CellType.STRING);
                    confirmMethod = row.getCell(7, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //检测标准
                String checkStand = null;
                try {
                    row.getCell(8).setCellType(CellType.STRING);
                    checkStand = row.getCell(8, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

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

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

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

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

                //校验管理类型
                if (StringUtils.isEmpty(manageType)) {
                    errorNum++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                } else {
                    manageType = MesExtEnumUtil.Q_MANAGE_MANAGE_TYPE.descriptionOfValue(manageType);
                    if (StringUtils.isEmpty(manageType)) {
                        errorNum++;
                        cellNum += "C;";
                        errorInfo += "第C列数据无效;";
                    }
                }

                //校验重要安全部品编码
                if ((!StringUtils.isEmpty(importanceSafePartNo)) && (CollectionUtils.isEmpty(partNoEntityMap) || !partNoEntityMap.containsKey(partNo))) {
                    errorNum++;
                    cellNum += "D;";
                    errorInfo += "第D列数据无效;";
                }

                //校验检测信息
                if (StringUtils.isEmpty(checkMessage)) {
                    errorNum++;
                    cellNum += "E;";
                    errorInfo += "第E列数据必填;";
                } else {
                    if (checkMessage.length() > 255) {
                        errorNum ++;
                        cellNum += "E;";
                        errorInfo += "第E列数据长度不能超过255个字符;";
                    }
                }

                //校验检测标志
                if (StringUtils.isEmpty(checkStand)) {
                    errorNum++;
                    cellNum += "I;";
                    errorInfo += "第I列数据必填;";
                } else {
                    if (checkStand.length() > 255) {
                        errorNum ++;
                        cellNum += "I;";
                        errorInfo += "第I列数据长度不能超过255个字符;";
                    }
                }

                //校验唯一性 不重复
                boolean isExist = false;

                if (errorNum == 0) {
                    String key = new StringJoiner(MesExtConstWords.AND).add(partNo).add(processCode).add(checkMessage).add(checkStand).add(manageType).add(getImportanceSafePartNo(manageType, importanceSafePartNo)).toString();

                    if (!processFirstItemByOnlyMap.containsKey(key)) {
                        processFirstItemByOnlyMap.put(key, String.valueOf(rowNum));
                        //校验 项目确认代码 是否已经存在数据库
                        if (StringUtils.isEmpty(errorInfo) && !CollectionUtils.isEmpty(processFirstItemMap) &&
                                processFirstItemMap.containsKey(key)) {
                            isExist = true;
                        }
                    } else {
                        errorNum++;
                        cellNum += "A+B+C+D+E+I;";
                        errorInfo += "第A+B+C+D+E+I列数据跟第" + processFirstItemByOnlyMap.get(key) +
                                "行的第A+B+C+D+E+I列数据重复;";
                    }
                }

                //上下限值校验

                if ((!StringUtils.isEmpty(upLimits) && StringUtils.isEmpty(downLimits)) ||
                        (StringUtils.isEmpty(upLimits) && !StringUtils.isEmpty(downLimits))){
                    errorNum ++;
                    cellNum += "J+K;";
                    errorInfo += "第J+K列数据缺少,上下限值必须同时存在;";
                }

                //上限值
                Double upLimit = null;
                //下限值
                Double downLimit = null;

                if(!StringUtils.isEmpty(upLimits)){
                    upLimit =  Double.valueOf(upLimits);
                    String[] standard = upLimits.split(MesExtConstWords.DECIMAL_POINT);
                    if (null != standard && standard.length == 2 && standard[1].length() > 4) {
                        errorNum ++;
                        cellNum += "J+K;";
                        errorInfo += "第J+K列数据最多四位小数;";
                    }
                }

                if(!StringUtils.isEmpty(downLimits)){
                    downLimit =  Double.valueOf(downLimits);
                    String[] standard = downLimits.split(MesExtConstWords.DECIMAL_POINT);
                    if (null != standard && standard.length == 2 && standard[1].length() > 4) {
                        errorNum ++;
                        cellNum += "J+K;";
                        errorInfo += "第J+K列数据最多四位小数;";
                    }
                }

                if (!StringUtils.isEmpty(upLimits) && !StringUtils.isEmpty(downLimits)){
                    if (upLimit < downLimit){
                        errorNum ++;
                        cellNum += "J+K;";
                        errorInfo += "第J+K列数据上限值不能小于下限值;";
                    }
                }

                //没有错误的时候，MesProcessFirstItem
                if (errorNum == 0) {
                    MesProcessFirstItem processFirstItem;
                    if(isExist){
                        String key = new StringJoiner(MesExtConstWords.AND).add(partNo).add(processCode).add(checkMessage).add(checkStand).add(manageType).add(getImportanceSafePartNo(manageType, importanceSafePartNo)).toString();
                        processFirstItem = processFirstItemMap.get(key).get(0);
                        ConvertBean.serviceModelUpdate(processFirstItem, userName);
                    }else{
                        processFirstItem = new MesProcessFirstItem();
                        ConvertBean.serviceModelInitialize(processFirstItem, userName);
                    }
                    processFirstItem.setPartNo(partNo);
                    processFirstItem.setProcessCode(processCode);
                    processFirstItem.setProcessName(processName);
                    processFirstItem.setCheckMessage(checkMessage);
                    processFirstItem.setCheckStand(checkStand);
                    processFirstItem.setUpLimit(upLimits);
                    processFirstItem.setDownLimit(downLimits);
                    processFirstItem.setManageType(manageType);
                    processFirstItem.setImportanceSafePartNo(MesExtEnumUtil.Q_MANAGE_MANAGE_TYPE.RESULT_TYPE.getValue().equals(manageType) ? importanceSafePartNo : "");
                    processFirstItem.setCheckFrequency(checkFrequency);
                    processFirstItem.setConfirmMethod(confirmMethod);
                    processFirstItem.setSampleQty(sampleQty);
                    processFirstItem.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                    processFirstItem.setOrganizeCode(organizeCode);
                    ConvertBean.serviceModelInitialize(processFirstItem, userName);
                    processCheckExtList.add(processFirstItem);
                    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 : processCheckExtList);
        return excelImportResultExtModel;
    }

    private String getImportanceSafePartNo(String manageType,String importanceSafePartNo) {
        return MesExtEnumUtil.Q_MANAGE_MANAGE_TYPE.COMPARE_TYPE.getValue().equals(manageType) || StringUtils.isEmpty(importanceSafePartNo) ? "" : importanceSafePartNo;
    }

    /**
     * 工序首检项目导入-数据入库
     *
     * @param excelImportResultExtModel
     */
    private void insertExcelMesProcessFirstItem(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesProcessFirstItem> processFirstItemList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(processFirstItemList)) {
                for (MesProcessFirstItem processFirstItem : processFirstItemList) {
                    if(StringUtils.isEmpty(processFirstItem.getId())){
                        processFirstItemRepository.insert(processFirstItem);
                    }else{
                        processFirstItemRepository.save(processFirstItem);
                    }
                }
            }
        }
    }
}
