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

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.model.ExcelImportErrorExtModel;
import cn.estsh.i3plus.ext.mes.pojo.model.ExcelImportResultExtModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesPartExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesWorkCenterExtRepository;
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.MesPartCheck;
import cn.estsh.i3plus.pojo.mes.repository.MesDataObjectRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesPartCheckRepository;
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:物料校验项导入，支持编辑
 * @Reference:
 * @Author: wangjie
 * @CreateDate:2019\10\9
 * @Modify:
 **/
@Service
public class EpPartCheckExtExcelService implements IExcelImportExtService {

    @Autowired
    private MesPartCheckRepository partCheckRepository;

    @Autowired
    private MesDataObjectRepository dataObjectRepository;

    @Autowired
    private MesWorkCenterExtRepository workCenterExtRepository;

    @Autowired
    private MesPartExtRepository partExtRepository;

    @Autowired
    private CommonExtService commonExtService;

    /**
     * 物料校验项导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractPartCheck(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelPartCheck(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

    /**
     * 物料校验项导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractPartCheck(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //MesPartCheck集合
        List<MesPartCheck> partCheckList = new ArrayList<>();

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

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

        //用于EXCEL表中的唯一校验，key：objectCode&workCenterCode&partNo，value：row
        Map<String,String> existMap = new HashMap<>();

        //查询物料校验项表
        List<MesPartCheck> partChecks = partCheckRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesPartCheck>> partCheckMap = partChecks.stream().filter(o -> null != o && !StringUtils.isEmpty(o.getObjectCode()) && !StringUtils.isEmpty(o.getWorkCenterCode()))
                .collect(Collectors.groupingBy(o -> (new StringJoiner(MesExtConstWords.AND).add(o.getObjectCode()).add(o.getWorkCenterCode()).add(o.getPartNo()).toString())));

        //查询数据对象
        Map<String, Object> objectCodeEntityMap;
        try {
            objectCodeEntityMap = MesCommonUtil.getCodeEntityMap(dataObjectRepository, MesExtConstWords.OBJECT_CODE, organizeCode, "数据对象表");
        } catch (Exception e) {
            objectCodeEntityMap = null;
        }

        // 查询产线表
        Map<String, Object> workCenterCodeEntityMap;
        try {
            workCenterCodeEntityMap = MesCommonUtil.getCodeEntityMap(workCenterExtRepository, MesExtConstWords.WORK_CENTER_CODE, organizeCode, "产线表");
        } catch (Exception e) {
            workCenterCodeEntityMap = null;
        }

        // 查询物料表
        Map<String, Object> partCodeEntityMap;
        try {
            partCodeEntityMap = MesCommonUtil.getCodeEntityMap(partExtRepository, MesExtConstWords.PART_NO, organizeCode, "物料表");
        } catch (Exception e) {
            partCodeEntityMap = 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 objectCode = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                //生产线代码
                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 partNo = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    partNo = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //校验表达式
                String checkSpelExpress = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    checkSpelExpress = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //类型表达式
                String typeSpelExpress = null;
                try {
                    row.getCell(4).setCellType(CellType.STRING);
                    typeSpelExpress = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //记录数量表达式
                String recordNumSpelExpress = null;
                try {
                    row.getCell(5).setCellType(CellType.STRING);
                    recordNumSpelExpress = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //限定检测表达式
                String limitSpelExpress = null;
                try {
                    row.getCell(6).setCellType(CellType.STRING);
                    limitSpelExpress = row.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //数据查询类型
                String dataType = null;
                try {
                    row.getCell(7).setCellType(CellType.STRING);
                    dataType = row.getCell(7, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //合格标准描述
                String recordNumDesc = null;
                try {
                    row.getCell(8).setCellType(CellType.STRING);
                    recordNumDesc = row.getCell(8, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //校验对象代码
                if (CollectionUtils.isEmpty(objectCodeEntityMap) ||
                        (!CollectionUtils.isEmpty(objectCodeEntityMap) && !objectCodeEntityMap.containsKey(objectCode))) {
                    errorNum++;
                    cellNum += "A;";
                    errorInfo += "第A列数据无效;";
                }

                //校验生产线代码
                if (StringUtils.isEmpty(workCenterCode)) {
                    errorNum++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                } else {
                    if (CollectionUtils.isEmpty(workCenterCodeEntityMap) || !workCenterCodeEntityMap.containsKey(workCenterCode)) {
                        errorNum++;
                        cellNum += "B;";
                        errorInfo += "第B列数据无效;";
                    }
                }

                //校验物料号
                if (!StringUtils.isEmpty(partNo) && (CollectionUtils.isEmpty(partCodeEntityMap) || !partCodeEntityMap.containsKey(partNo))) {
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据无效;";
                }

                boolean isExist = false;
                //校验对象代码+生产线代码+物料代码
                String key = new StringJoiner(MesExtConstWords.AND).add(objectCode).add(workCenterCode).add(partNo).toString();
                if(!existMap.containsKey(key)){
                    existMap.put(key, String.valueOf(rowNum));
                    //校验数据库是否已经存在对象代码+字段代码
                    if(!CollectionUtils.isEmpty(partCheckMap) && partCheckMap.containsKey(key)){
                        isExist = true;
                    }
                }else{
                    errorNum ++;
                    cellNum += "A+B+C;";
                    errorInfo += "第A+B+C列数据与第" + existMap.get(key) + "行的A+B+C列数据重复;";
                }

                //校验数据类型
                if (StringUtils.isEmpty(dataType)) {
                    errorNum++;
                    cellNum += "H;";
                    errorInfo += "第H列数据必填;";
                } else {
                    try {
                        Integer.valueOf(dataType);
                        if (StringUtils.isEmpty(MesExtEnumUtil.PART_CHECK_DATA_TYPE.valueOfDescription(Integer.valueOf(dataType)))) {
                            errorNum++;
                            cellNum += "H;";
                            errorInfo += "第H列数据无效;";
                        }
                    } catch (NumberFormatException e) {
                        errorNum++;
                        cellNum += "H;";
                        errorInfo += "第H列数据无效;";
                    }
                }

                //没有错误的时候，封装MesPartCheck
                if (errorNum == 0) {
                    MesPartCheck partCheck;
                    if(isExist){
                        partCheck = partCheckMap.get(key).get(0);
                        ConvertBean.serviceModelUpdate(partCheck, userName);
                    }else{
                        partCheck = new MesPartCheck();
                        ConvertBean.serviceModelInitialize(partCheck, userName);
                    }
                    partCheck.setObjectCode(objectCode);
                    partCheck.setWorkCenterCode(workCenterCode);
                    partCheck.setPartNo(partNo);
                    partCheck.setCheckSpelExpress(checkSpelExpress);
                    partCheck.setTypeSpelExpress(typeSpelExpress);
                    partCheck.setRecordNumSpelExpress(recordNumSpelExpress);
                    partCheck.setLimitSpelExpress(limitSpelExpress);
                    partCheck.setDataType(Integer.valueOf(dataType));
                    partCheck.setRecordNumDesc(recordNumDesc);
                    partCheck.setOrganizeCode(organizeCode);
                    partCheckList.add(partCheck);
                    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 : partCheckList);
        return excelImportResultModel;
    }

    /**
     * 物料校验项导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelPartCheck(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesPartCheck> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesPartCheck partCheck : excelList) {
                    if(StringUtils.isEmpty(partCheck.getId())){
                        partCheckRepository.insert(partCheck);
                    }else{
                        partCheckRepository.save(partCheck);
                    }
                }
            }
        }
    }
}
