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.MesPartExt;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesPrintPartParameterExt;
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.MesPrintPartParameterExtRepository;
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 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 PrintPartParameterExtExcelService implements IExcelImportExtService {

    @Autowired
    private MesPrintPartParameterExtRepository printPartParameterExtRepository;

    @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<MesPrintPartParameterExt> printPartParameterExts = new ArrayList<>();

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

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

        //用于EXCEL表中的 物料号 唯一校验，key：partNo
        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<MesPrintPartParameterExt> printPartParameterExtList = printPartParameterExtRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});

        Map<String, List<MesPrintPartParameterExt>> printPartParameterMap = printPartParameterExtList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getPartNo())))
                .collect(Collectors.groupingBy(MesPrintPartParameterExt::getPartNo));

        //从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 partName = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    partName = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //净重
                String netWeight = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    netWeight = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //毛重
                String roughWeight = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    roughWeight = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //包装尺寸
                String packageSize = null;
                try {
                    row.getCell(4).setCellType(CellType.STRING);
                    packageSize = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                boolean isExist = false;
                //校验打印物料拓展信息 物料代码不重复
                String key = partNo;
                if (!existMap.containsKey(key)) {
                    existMap.put(key, String.valueOf(rowNum));
                    //校验 打印物料拓展信息 物料代码 是否已经存在数据库
                    if (StringUtils.isEmpty(errorInfo) && !CollectionUtils.isEmpty(printPartParameterMap) && printPartParameterMap.containsKey(key)) {
                        isExist = true;
                    }
                    if(!partCodeEntityMap.containsKey(key)){
                        errorNum++;
                        cellNum += "A;";
                        errorInfo += "第A列数据不存在物料信息中;";
                    }else{
                        partName = ((MesPartExt) partCodeEntityMap.get(key)).getPartName();
                    }
                } else {
                    errorNum++;
                    cellNum += "A;";
                    errorInfo += "第A列数据跟第" + existMap.get(key) + "行的第A列数据重复;";
                }

                //校验物料名称
//                if (partCodeEntityMap.containsKey(partNo) && !StringUtils.isEmpty(partName)) {
//                    MesPartExt partDb = (MesPartExt) partCodeEntityMap.get(partNo);
//                    if (!partDb.getPartName().equals(partName)) {
//                        errorNum++;
//                        cellNum += "B;";
//                        errorInfo += "第B列数据无效;";
//                    }
//                } else{
//                    errorNum++;
//                    cellNum += "B;";
//                    errorInfo += "第B列数据无效;";
//                }

                //校验净重
                if(StringUtils.isEmpty(netWeight)){
                    errorNum++;
                    cellNum += "C;";
                    errorInfo += "第C列数据为空;";
                }

                //校验毛重
                if(StringUtils.isEmpty(roughWeight)){
                    errorNum++;
                    cellNum += "D;";
                    errorInfo += "第D列数据为空;";
                }

                //校验包装尺寸
                if(StringUtils.isEmpty(packageSize)){
                    errorNum++;
                    cellNum += "E;";
                    errorInfo += "第E列数据为空;";
                }

                //没有错误的时候，封装MesProjectConfirm
                if (errorNum == 0) {
                    MesPrintPartParameterExt printPartParameterExt;
                    if(isExist){
                        printPartParameterExt = printPartParameterMap.get(key).get(0);
                        ConvertBean.serviceModelUpdate(printPartParameterExt, userName);
                    }else{
                        printPartParameterExt = new MesPrintPartParameterExt();
                        ConvertBean.serviceModelInitialize(printPartParameterExt, userName);
                    }
                    printPartParameterExt.setPartNo(partNo);
                    printPartParameterExt.setPartName(partName);
                    printPartParameterExt.setNetWeight(netWeight);
                    printPartParameterExt.setRoughWeight(roughWeight);
                    printPartParameterExt.setPackageSize(packageSize);
                    printPartParameterExt.setOrganizeCode(organizeCode);
                    printPartParameterExt.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                    printPartParameterExts.add(printPartParameterExt);

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

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