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

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.MesProcessLabelMarking;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesSkillKanbanProcessInformation;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesWorkCenterExt;
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.MesProcessLabelMarkingRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesSkillKanbanProcessInformationRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesWorkCenterExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.util.MesConstWords;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
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.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @PROJECT_NAME: i3plus-mes-panasonic-dev
 * @DESCRIPTION:
 * @USER: xinwang.yi
 * @DATE: 2021-12-13 10:04
 */
@Service
public class MesSkillKanbanProcessInformationExcelService implements IExcelImportExtService {

    @Autowired
    private CommonExtService commonService;

    @Autowired
    private MesSkillKanbanProcessInformationRepository skillKanbanProcessInformationRepository;

    @Autowired
    private MesWorkCenterExtRepository workCenterExtRepository;

    @Autowired
    private MesProcessLabelMarkingRepository processLabelMarkingRepository;

    /**
     * 技能看板工序信息导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultModel = this.sheetExtractMesSkillKanbanProcessInformation(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesSkillKanbanProcessInformation(excelImportResultModel);
        return excelImportResultModel;
    }

    /**
     * 技能看板工序信息导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractMesSkillKanbanProcessInformation(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //技能看板工序信息 集合
        List<MesSkillKanbanProcessInformation> skillKanbanProcessInformationList = new ArrayList<>();

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

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

        //用于EXCEL表中的技能看板工序代码唯一校验，key：seq、workCenterCode、skillKanbanProcessCode，value：row
        Map<String,String> mesSkillKanbanProcessInformationMap = new HashMap<>();

        //查询产线信息
        List<MesWorkCenterExt> workCenterExtList = workCenterExtRepository.findByProperty(new String[]{MesConstWords.ORGANIZE_CODE, MesConstWords.IS_DELETED, MesConstWords.IS_VALID},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue()});
        //产线代码集合
        List<String> workCenterCodeList = workCenterExtList.stream().map(MesWorkCenterExt::getWorkCenterCode).collect(Collectors.toList());

        //工序标签标示
        List<MesProcessLabelMarking> processLabelMarkingList = processLabelMarkingRepository.findByProperty(new String[]{MesConstWords.ORGANIZE_CODE, MesConstWords.IS_DELETED, MesConstWords.IS_VALID},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue()});
        Map<String, List<MesProcessLabelMarking>> processLabelMarkingMap = processLabelMarkingList.stream().collect(Collectors.groupingBy(MesProcessLabelMarking::getProcessLabelCode));

        //技能看板工序信息
        List<MesSkillKanbanProcessInformation> mesSkillKanbanProcessInformationList = skillKanbanProcessInformationRepository.findByProperty(new String[]{MesConstWords.ORGANIZE_CODE, MesConstWords.IS_DELETED, MesConstWords.IS_VALID},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue()});
        Map<String, List<MesSkillKanbanProcessInformation>> skillKanbanProcessInformationMap = mesSkillKanbanProcessInformationList.stream().filter(mesSkillKanbanProcessInformation -> mesSkillKanbanProcessInformation != null).collect(
                Collectors.groupingBy(o -> (new StringJoiner(MesExtConstWords.AND).add(o.getSeq().toString()).add(o.getWorkCenterCode()).add(o.getSkillKanbanProcessCode()).toString())));

        //从excel表的第2行数据开始导入，getFirstRowNum是从0行开始读取
        for (int i = (sheetAt.getFirstRowNum() + 1); 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 seq = null;
                try {
                    row.getCell(0).setCellType(CellType.STRING);
                    seq = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //产线代码
                String workCenterCode = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    workCenterCode = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //技能看板工序代码
                String skillKanbanProcessCode = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    skillKanbanProcessCode = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //技能看板工序名称
                String skillKanbanProcessName = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    skillKanbanProcessName = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //工序标签标示代码
                String processLabelCode = null;
                try {
                    row.getCell(4).setCellType(CellType.STRING);
                    processLabelCode = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //工序标签标示名称
                String processLabelName = null;
                try {
                    row.getCell(5).setCellType(CellType.STRING);
                    processLabelName = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                if(StringUtils.isEmpty(seq)){
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据必填;";
                }else{
                    try {
                        Integer.valueOf(seq);
                    } catch (NumberFormatException e) {
                        errorNum ++;
                        cellNum += "A;";
                        errorInfo += "第A列数据无效;";
                    }
                }

                //校验产线
                if (StringUtils.isEmpty(workCenterCode)) {
                    errorNum ++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                }else{
                    if(!workCenterCodeList.contains(workCenterCode)){
                        errorNum ++;
                        cellNum += "B;";
                        errorInfo += "第B列数据无效;";
                    }
                }

                if(StringUtils.isEmpty(skillKanbanProcessCode)){
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                }

                if(StringUtils.isEmpty(skillKanbanProcessName)){
                    errorNum ++;
                    cellNum += "D;";
                    errorInfo += "第D列数据必填;";
                }

                if(StringUtils.isEmpty(processLabelCode)){
                    errorNum ++;
                    cellNum += "E;";
                    errorInfo += "第E列数据必填;";
                }else{
                    if(processLabelMarkingMap.containsKey(processLabelCode)){
                        processLabelName =  processLabelMarkingMap.get(processLabelCode).get(0).getProcessLabelName();
                    }else{
                        errorNum ++;
                        cellNum += "E;";
                        errorInfo += "第E列数据无效;";
                    }
                }

                boolean isExist = false;

                //校验 序号、产线代码、技能看板工序代码 不重复
                if (!mesSkillKanbanProcessInformationMap.containsKey(new StringJoiner(MesExtConstWords.AND).add(seq).add(workCenterCode).add(skillKanbanProcessCode).toString())) {
                    mesSkillKanbanProcessInformationMap.put(new StringJoiner(MesExtConstWords.AND).add(seq).add(workCenterCode).add(skillKanbanProcessCode).toString(), String.valueOf(rowNum));
                    //校验设备代码是否已经存在数据库
                    if (!CollectionUtils.isEmpty(skillKanbanProcessInformationMap) && skillKanbanProcessInformationMap.containsKey(new StringJoiner(MesExtConstWords.AND).add(seq).add(workCenterCode).add(skillKanbanProcessCode).toString())) {
                        isExist = true;
                    }
                } else {
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A+B+C列数据跟第" + mesSkillKanbanProcessInformationMap.get(new StringJoiner(MesExtConstWords.AND).add(seq).add(workCenterCode).add(skillKanbanProcessCode).toString()) + "行的第A+B+C列数据重复;";
                }

                //没有错误的时候，封装MesSkillKanbanProcessInformation
                if (errorNum == 0) {
                    MesSkillKanbanProcessInformation skillKanbanProcessInformation;
                    if(isExist){
                        skillKanbanProcessInformation = skillKanbanProcessInformationMap.get(new StringJoiner(MesExtConstWords.AND).add(seq).add(workCenterCode).add(skillKanbanProcessCode).toString()).get(0);
                        ConvertBean.serviceModelUpdate(skillKanbanProcessInformation,userName);
                    }else {
                        skillKanbanProcessInformation = new MesSkillKanbanProcessInformation();
                        ConvertBean.serviceModelInitialize(skillKanbanProcessInformation, userName);
                    }
                    skillKanbanProcessInformation.setSeq(Integer.parseInt(seq));
                    skillKanbanProcessInformation.setWorkCenterCode(workCenterCode);
                    skillKanbanProcessInformation.setSkillKanbanProcessCode(skillKanbanProcessCode);
                    skillKanbanProcessInformation.setSkillKanbanProcessName(skillKanbanProcessName);
                    skillKanbanProcessInformation.setProcessLabelCode(processLabelCode);
                    skillKanbanProcessInformation.setProcessLabelName(processLabelName);
                    skillKanbanProcessInformation.setOrganizeCode(organizeCode);
                    skillKanbanProcessInformationList.add(skillKanbanProcessInformation);

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

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

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

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

    /**
     * 技能看板工序信息导入-数据入库
     * @param excelImportResultModel
     */
    private void insertExcelMesSkillKanbanProcessInformation(ExcelImportResultExtModel excelImportResultModel) {
        //导入数据
        if (null != excelImportResultModel) {
            List<MesSkillKanbanProcessInformation> excelList = excelImportResultModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesSkillKanbanProcessInformation skillKanbanProcessInformation : excelList) {
                    if(StringUtils.isEmpty(skillKanbanProcessInformation.getId())){
                        skillKanbanProcessInformationRepository.insert(skillKanbanProcessInformation);
                    }else{
                        skillKanbanProcessInformationRepository.update(skillKanbanProcessInformation);
                    }
                }
            }
        }
    }
}
