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.MesPartExt;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesProductPrintType;
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.MesProductPrintTypeRepository;
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.repository.MesPartRepository;
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-04-23
 * @Modify:
 **/
@Service
public class MesProductPrintTypeExcelService implements IExcelImportExtService {

    @Autowired
    private MesProductPrintTypeRepository productPrintTypeRepository;

    @Autowired
    private MesPartRepository partRepository;

    @Autowired
    private CommonExtService commonExtService;

    /**
     * 产品打印类型导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractProductPrintType(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelContainer(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

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

        //MesProductPrintType
        List<MesProductPrintType> productPrintTypeList = new ArrayList<>();

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

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

        //用于EXCEL表中的产品打印类型唯一校验，key：partNo & printType，value：row
        Map<String, String> productPrintTypeMap = new HashMap<>();

        //查询容器表
        List<MesProductPrintType> productPrintTypes = productPrintTypeRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesProductPrintType>> productPrintTypeDbMap = CollectionUtils.isEmpty(productPrintTypes) ? null :
                productPrintTypes.stream().filter(o -> null != o).collect(Collectors.groupingBy(productPrintType -> new StringJoiner(MesExtConstWords.AND).add(productPrintType.getPartNo()).add(productPrintType.getPrintType().toString()).toString()));

        // 物料信息
        Map<String, Object> partEntityMap;
        try {
            partEntityMap = MesCommonUtil.getCodeEntityMap(partRepository, MesExtConstWords.PART_NO, organizeCode, "物料信息表");
        } catch (Exception e) {
            partEntityMap = 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 partNo = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                //打印类型
                String printTypeStr = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    printTypeStr = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //打印方式
                String printModeStr = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    printModeStr = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                boolean isExist = false;
                String partName = "";
                if(StringUtils.isEmpty(partNo)){
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据必填;";
                }else if(CollectionUtils.isEmpty(partEntityMap) || !partEntityMap.containsKey(partNo)){
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据无效,不存在于物料信息中;";
                }else{
                    partName = ((MesPartExt)partEntityMap.get(partNo)).getPartName();
                }


                //校验打印类型
                Integer printType = null;
                if (StringUtils.isEmpty(printTypeStr)) {
                    errorNum ++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                } else {
                    try {
                        printType = Integer.valueOf(printTypeStr);
                        MesExtEnumUtil.PRINT_QUEUE_TYPE.valueOfDescription(printType);
                    } catch (NumberFormatException e) {
                        errorNum ++;
                        cellNum += "B;";
                        errorInfo += "第B列数据格式无效;";
                    }
                }

                //校验打印方式
                Integer printMode = null;
                if (StringUtils.isEmpty(printModeStr)) {
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                } else {
                    try {
                        printMode = Integer.valueOf(printModeStr);
                        if(!MesExtEnumUtil.PRINT_MODE.checkValueIsValid(printMode)){
                            errorNum ++;
                            cellNum += "C;";
                            errorInfo += "第C列数据【"+ printModeStr +"】无效;";
                        }
                    } catch (NumberFormatException e) {
                        errorNum ++;
                        cellNum += "C;";
                        errorInfo += "第C列数据格式无效;";
                    }
                }

                //校验容器代码不重复
                if (!productPrintTypeMap.containsKey(new StringJoiner(MesExtConstWords.AND).add(partNo).add(printTypeStr).toString())) {
                    productPrintTypeMap.put(new StringJoiner(MesExtConstWords.AND).add(partNo).add(printTypeStr).toString(), String.valueOf(rowNum));
                    //校验 物料编码 & 打印类型 是否已经存在数据库
                    if (StringUtils.isEmpty(errorInfo) && !CollectionUtils.isEmpty(productPrintTypeDbMap) && productPrintTypeDbMap.containsKey(new StringJoiner(MesExtConstWords.AND).add(partNo).add(printTypeStr).toString())) {
                        isExist = true;
                    }
                } else {
                    errorNum ++;
                    cellNum += "AB;";
                    errorInfo += "第AB列数据跟第" + productPrintTypeMap.get(new StringJoiner(MesExtConstWords.AND).add(partNo).add(printTypeStr).toString()) + "行的第AB列数据重复;";
                }

                //没有错误的时候，封装MesContainer
                if (errorNum == 0) {
                    MesProductPrintType productPrintType;
                    if(isExist){
                        productPrintType = productPrintTypeDbMap.get(new StringJoiner(MesExtConstWords.AND).add(partNo).add(printTypeStr).toString()).get(0);
                        productPrintType.setPrintType(printType);
                        productPrintType.setPrintMode(printMode);
                        ConvertBean.serviceModelUpdate(productPrintType, userName);
                    }else{
                        productPrintType = new MesProductPrintType();
                        productPrintType.setPartNo(partNo);
                        productPrintType.setPartName(partName);
                        productPrintType.setPrintType(printType);
                        productPrintType.setPrintMode(printMode);
                        ConvertBean.serviceModelInitialize(productPrintType, userName);
                    }
                    productPrintType.setPrintMode(printMode);
                    productPrintType.setOrganizeCode(organizeCode);

                    productPrintTypeList.add(productPrintType);

                    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 : productPrintTypeList);
        return excelImportResultModel;
    }

    /**
     * 容器导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelContainer(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesProductPrintType> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesProductPrintType productPrintType : excelList) {
                    if(StringUtils.isEmpty(productPrintType.getId())){
                        productPrintTypeRepository.insert(productPrintType);
                    }else{
                        productPrintTypeRepository.save(productPrintType);
                    }
                }
            }
        }
    }
}
