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.MesOqcProject;
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.MesOqcProjectRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesPartExtRepository;
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.base.enumutil.MesEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesPartCategory;
import cn.estsh.i3plus.pojo.mes.repository.MesPartCategoryRepository;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:出货检验项目导入
 * @Reference:
 * @Author: wangjie
 * @CreateDate: 2019\11\4 10:39
 * @Modify:
 **/
@Service
public class OqcProjectExcelService implements IExcelImportExtService {

    @Autowired
    private MesOqcProjectRepository oqcProjectRepository;

    @Autowired
    private MesPartExtRepository partExtRepository;

    @Autowired
    private CommonExtService commonExtService;

    @Autowired
    private MesPartCategoryRepository partCategoryRepository;

    /**
     * 出货检验项目导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractOqcProject(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelOqcProject(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

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

        //MesOqcProject集合
        List<MesOqcProject> oqcProjectList = new ArrayList<>();

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

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

        //用于EXCEL表中的 检验类型+物料+产品类别+序号+项目 唯一校验，key：oqcType&partNo&categoryCode3&seq&oqcProject，value：row
        Map<String,String> existMap = new HashMap<>();

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

        List<MesPartCategory> partCategoryList = partCategoryRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.CATEGORY_TYPE},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), MesEnumUtil.PART_CATEGORY_TYPE.CATEGORY_THREE.getValue()});
        List<String> categoryCode3List = CollectionUtils.isEmpty(partCategoryList) ? null :
                partCategoryList.stream().filter(o -> null != o).map(MesPartCategory::getCategoryCode).collect(Collectors.toList());

        List<MesOqcProject> oqcProjectDbList = oqcProjectRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});

        Map<String, List<MesOqcProject>> oqcProjectMapByPart = CollectionUtils.isEmpty(oqcProjectDbList) ? null :
                oqcProjectDbList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getOqcType()) && MesExtEnumUtil.OQC_CHECK_TYPE.DAILY_INSPECTION.getValue() == o.getOqcType()))
                .collect(Collectors.groupingBy(o -> o.getOqcType() + "&" + o.getPartNo() + "&" + o.getSeq() + "&" + o.getOqcProject()));
        Map<String, List<MesOqcProject>> oqcProjectMapByCate = CollectionUtils.isEmpty(oqcProjectDbList) ? null :
                oqcProjectDbList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getOqcType()) && MesExtEnumUtil.OQC_CHECK_TYPE.DAILY_INSPECTION.getValue() != o.getOqcType()))
                .collect(Collectors.groupingBy(o -> o.getOqcType() + "&" + o.getCategoryCode3() + "&" + o.getSeq() + "&" + o.getOqcProject()));

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

                //检验顺序
                try {
                    //第一列必须有值，否则跳过
                    row.getCell(0).setCellType(CellType.STRING);
                } catch (Exception e) {
                    continue;
                }
                String seq = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                //物料编码
                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 oqcProject = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    oqcProject = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //判断基准
                String standard = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    standard = 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) {
                }
                //启用器具
                String appliance = null;
                try {
                    row.getCell(6).setCellType(CellType.STRING);
                    appliance = row.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //检验类型
                String oqcType = null;
                try {
                    row.getCell(7).setCellType(CellType.STRING);
                    oqcType = row.getCell(7, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //产品类别
                String categoryCode3 = null;
                try {
                    row.getCell(8).setCellType(CellType.STRING);
                    categoryCode3 = row.getCell(8, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //校验检验顺序
                Double seqD = null;
                try {
                    seqD = Double.parseDouble(seq);
                    String[] seqArr = seqD.toString().split(MesExtConstWords.DECIMAL_POINT);
                    if (null != seqArr && seqArr.length == 2 && seqArr[1].length() > 1) {
                        errorNum++;
                        cellNum += "A;";
                        errorInfo += "第A列数据最多1位小数;";
                    }
                } catch (NumberFormatException e) {
                    errorNum++;
                    cellNum += "A;";
                    errorInfo += "第A列数据无效;";
                }

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

                if (StringUtils.isEmpty(oqcType)) {
                    errorNum++;
                    cellNum += "H;";
                    errorInfo += "第H列数据必填;";
                } else {
                    try {
                        if (StringUtils.isEmpty(MesExtEnumUtil.OQC_CHECK_TYPE.valueOfDescription(Integer.parseInt(oqcType)))) {
                            errorNum++;
                            cellNum += "H;";
                            errorInfo += "第H列数据无效;";
                        } else {
                            if (MesExtEnumUtil.OQC_CHECK_TYPE.DAILY_INSPECTION.getValue() == Integer.parseInt(oqcType)) {
                                if (StringUtils.isEmpty(partNo)) {
                                    errorNum++;
                                    cellNum += "B;";
                                    errorInfo += "第B列数据必填;";
                                } else {
                                    if (CollectionUtils.isEmpty(partCodeEntityMap) || !partCodeEntityMap.containsKey(partNo)) {
                                        errorNum ++;
                                        cellNum += "B;";
                                        errorInfo += "第B列数据无效;";
                                    }
                                }
                                if (!StringUtils.isEmpty(categoryCode3)) {
                                    errorNum++;
                                    cellNum += "I;";
                                    errorInfo += "第I列数据不可填;";
                                }
                            } else {
                                if (!StringUtils.isEmpty(partNo)) {
                                    errorNum++;
                                    cellNum += "B;";
                                    errorInfo += "第B列数据不可填;";
                                }
                                if (StringUtils.isEmpty(categoryCode3)) {
                                    errorNum++;
                                    cellNum += "I;";
                                    errorInfo += "第I列数据必填;";
                                } else {
                                    if (CollectionUtils.isEmpty(categoryCode3List) || !categoryCode3List.contains(categoryCode3)) {
                                        errorNum++;
                                        cellNum += "I;";
                                        errorInfo += "第I列数据无效;";
                                    }
                                }
                            }
                        }
                    } catch (NumberFormatException e) {
                        errorNum++;
                        cellNum += "H;";
                        errorInfo += "第H列数据无效;";
                    }
                }

                //oqcType&partNo&categoryCode3&seq&oqcProject
                if (StringUtils.isEmpty(errorInfo)) {
                    String key = oqcType + "&" + partNo + "&" + categoryCode3 + "&" + seqD + "&" + oqcProject;
                    if (!existMap.containsKey(key)) {
                        existMap.put(key, String.valueOf(rowNum));
                        //校验是否已经存在数据库
                        if (StringUtils.isEmpty(errorInfo)) {
                            if (MesExtEnumUtil.OQC_CHECK_TYPE.DAILY_INSPECTION.getValue() == Integer.parseInt(oqcType)) {
                                if (!CollectionUtils.isEmpty(oqcProjectMapByPart) && oqcProjectMapByPart.containsKey(oqcType + "&" + partNo + "&" + seqD + "&" + oqcProject)) {
                                    errorNum ++;
                                    cellNum += "ABCH;";
                                    errorInfo += "第A+B+C+H列数据已经存在数据库;";
                                }
                            } else {
                                if (!CollectionUtils.isEmpty(oqcProjectMapByCate) && oqcProjectMapByCate.containsKey(oqcType + "&" + categoryCode3 + "&" + seqD + "&" + oqcProject)) {
                                    errorNum ++;
                                    cellNum += "ACHI;";
                                    errorInfo += "第A+C+H+I列数据已经存在数据库;";
                                }
                            }
                        }
                    } else {
                        errorNum ++;
                        cellNum += "ABCHI;";
                        errorInfo += "第A+B+C+H+I列数据跟第" + existMap.get(key) +
                                "行的第A+B+C+H+I列数据重复;";
                    }
                }

                //没有错误的时候，封装MesOqcProject
                if (errorNum == 0) {
                    MesOqcProject item = new MesOqcProject();
                    item.setOqcType(Integer.parseInt(oqcType));
                    if (MesExtEnumUtil.OQC_CHECK_TYPE.DAILY_INSPECTION.getValue() == item.getOqcType()) {
                        item.setPartNo(partNo);
                    } else {
                        item.setCategoryCode3(categoryCode3);
                    }
                    item.setOqcProject(oqcProject);
                    item.setStandard(standard);
                    item.setUpLimit(upLimit);
                    item.setDownLimit(downLimit);
                    item.setAppliance(appliance);
                    item.setSeq(seqD);
                    item.setOrganizeCode(organizeCode);
                    ConvertBean.serviceModelInitialize(item, userName);

                    oqcProjectList.add(item);

                    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 : oqcProjectList);
        return excelImportResultExtModel;
    }

    /**
     * 出货检验项目导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelOqcProject(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesOqcProject> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesOqcProject oqcProject : excelList) {
                   oqcProjectRepository.insert(oqcProject);
                }
            }
        }
    }
}
