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.MesProdPackExt;
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.MesProdPackExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.ConvertBeanExt;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
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.util.StringUtil;
import cn.estsh.i3plus.pojo.mes.repository.MesLabelTemplateRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesPartProduceTypeRepository;
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 ProdPackExtExcelService implements IExcelImportExtService {

    @Autowired
    private MesProdPackExtRepository prodPackExtRepository;

    @Autowired
    private MesLabelTemplateRepository labelTemplateRepository;

    @Autowired
    private MesPartProduceTypeRepository partProduceTypeRepository;

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

    /**
     * 产品包装关系导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractProdPackExt(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //MesProdPackExt集合
        List<MesProdPackExt> prodPackExtList = new ArrayList<>();

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

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

        //用于EXCEL表中的 类型+生产类型或物料号 唯一校验，key：type&value，value：row
        Map<String,String> typeAndValueMap = new HashMap<>();

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

        List<MesProdPackExt> prodPackExtDbList = prodPackExtRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesProdPackExt>> prodPackExtMapByPart = prodPackExtDbList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getPartNo())))
                .collect(Collectors.groupingBy(MesProdPackExt::getPartNo));
        Map<String, List<MesProdPackExt>> prodPackExtMapByPpt = prodPackExtDbList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getPptCode())))
                .collect(Collectors.groupingBy(MesProdPackExt::getPptCode));

        //查询打印模板表
        Map<String, Object> templateCodeEntityMap;
        try {
            templateCodeEntityMap = MesCommonUtil.getCodeEntityNotOrgMap(labelTemplateRepository, MesExtConstWords.TEMPLATE_CODE, organizeCode, "打印模板表");
        } catch (Exception e) {
            templateCodeEntityMap = null;
        }

        //查询生产类型表
        Map<String, Object> pptCodeEntityMap;
        try {
            pptCodeEntityMap = MesCommonUtil.getCodeEntityNotOrgMap(partProduceTypeRepository, MesExtConstWords.PPT_CODE, organizeCode, "生产类型表");
        } catch (Exception e) {
            pptCodeEntityMap = 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 type = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                //生产类型或物料号
                String value = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    value = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //产品标签模板
                String processLabelTemplate = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    processLabelTemplate = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //包装标签模板
                String packLabelTemplate = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    packLabelTemplate = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //质保书标签模板
                String qualityAssureTemplate = null;
                try {
                    row.getCell(4).setCellType(CellType.STRING);
                    qualityAssureTemplate = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //大本体条码标签模板
                String bigProcessAssureTemplate = null;
                try {
                    row.getCell(5).setCellType(CellType.STRING);
                    bigProcessAssureTemplate = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //大包装条码标签模板
                String bigPackageLabelTemplate = null;
                try {
                    row.getCell(6).setCellType(CellType.STRING);
                    bigPackageLabelTemplate = row.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                if (type.equals(String.valueOf(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue())) || type.equals(String.valueOf(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()))) {
                    if (type.equals(String.valueOf(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()))) {
                        //校验物料号
                        if (CollectionUtils.isEmpty(partCodeEntityMap) || StringUtils.isEmpty(value) ||
                                (!CollectionUtils.isEmpty(partCodeEntityMap) && !partCodeEntityMap.containsKey(value))) {
                            errorNum ++;
                            cellNum += "B;";
                            errorInfo += "第B列数据无效;";
                        }
                    } else {
                        //校验生产类型
                        if (CollectionUtils.isEmpty(pptCodeEntityMap) || StringUtils.isEmpty(value) ||
                                (!CollectionUtils.isEmpty(pptCodeEntityMap) && !pptCodeEntityMap.containsKey(value))) {
                            errorNum ++;
                            cellNum += "B;";
                            errorInfo += "第B列数据无效;";
                        }
                    }

                    //校验 类型+值 不重复
                    if (!typeAndValueMap.containsKey(type + "&" + value)) {
                        typeAndValueMap.put(type + "&" + value, String.valueOf(rowNum));
                        //校验是否已经存在数据库
                        if (StringUtils.isEmpty(errorInfo)) {
                            if (type.equals(String.valueOf(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()))) {
                                if (!CollectionUtils.isEmpty(prodPackExtMapByPart) && prodPackExtMapByPart.containsKey(value)) {
                                    errorNum ++;
                                    cellNum += "B;";
                                    errorInfo += "第B列数据已经存在数据库;";
                                }
                            } else {
                                if (!CollectionUtils.isEmpty(prodPackExtMapByPpt) && prodPackExtMapByPpt.containsKey(value)) {
                                    errorNum ++;
                                    cellNum += "B;";
                                    errorInfo += "第B列数据已经存在数据库;";
                                }
                            }
                        }
                    } else {
                        errorNum ++;
                        cellNum += "AB;";
                        errorInfo += "第A+B列数据跟第" + typeAndValueMap.get(type + "&" + value) +
                                "行的第A+B列数据重复;";
                    }

                    //校验产品标签模板
                    if (!StringUtils.isEmpty(processLabelTemplate)) {
                        if (CollectionUtils.isEmpty(templateCodeEntityMap) ||
                                (!CollectionUtils.isEmpty(templateCodeEntityMap) && !templateCodeEntityMap.containsKey(processLabelTemplate))) {
                            errorNum ++;
                            cellNum += "C;";
                            errorInfo += "第C列数据无效;";
                        }
                    }

                    //校验产品标签模板
                    if (!StringUtils.isEmpty(packLabelTemplate)) {
                        if (CollectionUtils.isEmpty(templateCodeEntityMap) ||
                                (!CollectionUtils.isEmpty(templateCodeEntityMap) && !templateCodeEntityMap.containsKey(packLabelTemplate))) {
                            errorNum ++;
                            cellNum += "D;";
                            errorInfo += "第D列数据无效;";
                        }
                    }

                    //校验质保书标签模板
                    if (!StringUtil.isEmpty(qualityAssureTemplate)) {
                       if (CollectionUtils.isEmpty(templateCodeEntityMap) ||
                               (!CollectionUtils.isEmpty(templateCodeEntityMap) && !templateCodeEntityMap.containsKey(qualityAssureTemplate))) {
                           errorNum ++;
                           cellNum += "E;";
                           errorInfo += "第E列数据无效;";
                       }
                    }

                    //校验大本体条码标签模板
                    if (!StringUtil.isEmpty(bigProcessAssureTemplate)) {
                        if (CollectionUtils.isEmpty(templateCodeEntityMap) ||
                                (!CollectionUtils.isEmpty(templateCodeEntityMap) && !templateCodeEntityMap.containsKey(bigProcessAssureTemplate))) {
                            errorNum ++;
                            cellNum += "F;";
                            errorInfo += "第F列数据无效;";
                        }
                    }
                } else {
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据无效;";
                }

                //没有错误的时候，封装MesProdPackExt
                if (errorNum == 0) {
                    MesProdPackExt prodPackExt = new MesProdPackExt();
                    if (type.equals(String.valueOf(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()))) {
                        prodPackExt.setPartNo(value);
                    } else {
                        prodPackExt.setPptCode(value);
                    }
                    prodPackExt.setProcessLabelTemplate(processLabelTemplate);
                    prodPackExt.setProdLabelTemplate(packLabelTemplate);
                    prodPackExt.setPackLabelTemplate(packLabelTemplate);
                    prodPackExt.setQualityAssureTemplate(qualityAssureTemplate);
                    prodPackExt.setBigProcessLabelTemplate(bigProcessAssureTemplate);
                    prodPackExt.setBigPackageLabelTemplate(bigPackageLabelTemplate);
                    prodPackExt.setOrganizeCode(organizeCode);
                    ConvertBean.serviceModelInitialize(prodPackExt, userName);
                    new ConvertBeanExt(prodPackExt).convertBean(prodPackExt);

                    prodPackExtList.add(prodPackExt);

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

    /**
     * 产品包装关系导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelProdPackExt(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesProdPackExt> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesProdPackExt prodPackExt : excelList) {
                    prodPackExtRepository.insert(prodPackExt);
                }
            }
        }
    }
}
