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.MesShiftProd;
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.MesShiftProdRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.MathOperation;
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-04-23
 * @Modify:
 **/
@Service
public class ShiftProdExcelService implements IExcelImportExtService {

    @Autowired
    private MesShiftProdRepository shiftProdRepository;

    @Autowired
    private CommonExtService commonExtService;

    /**
     * 班次作业项目导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractMesShiftProd(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesShiftProd(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

    /**
     * 班次作业项目导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractMesShiftProd(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //MesShiftProd集合
        List<MesShiftProd> shiftProdList = new ArrayList<>();

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

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

        //用于EXCEL表中的作业内容代码唯一校验，key：prodCode，value：row
        Map<String, String> prodCodeMap = new HashMap<>();

        //查询班次作业项目表
        List<MesShiftProd> shiftProds = shiftProdRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesShiftProd>> shiftProdMap = CollectionUtils.isEmpty(shiftProds) ? null :
                shiftProds.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesShiftProd::getProdCode));

        //从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 prodCode = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                //作业内容名称
                String prodName = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    prodName = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //作业内容分类
                String prodCategory = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    prodCategory = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //是否作业时间
                String isProdTime = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    isProdTime = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //作业类型
                String prodType = null;
                try {
                    row.getCell(4).setCellType(CellType.STRING);
                    prodType = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //计划比例
                String planRate = null;
                try {
                    row.getCell(5).setCellType(CellType.STRING);
                    planRate = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                boolean isExist = false;
                //校验作业内容代码不重复
                if (!prodCodeMap.containsKey(prodCode)) {
                    prodCodeMap.put(prodCode, String.valueOf(rowNum));
                    //校验 作业内容代码 是否已经存在数据库
                    if (StringUtils.isEmpty(errorInfo) && !CollectionUtils.isEmpty(shiftProdMap) && shiftProdMap.containsKey(prodCode)) {
                        isExist = true;
                    }
                } else {
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据跟第" + prodCodeMap.get(prodCode) + "行的第A列数据重复;";
                }

                //校验作业内容名称
                if (StringUtils.isEmpty(prodName)) {
                    errorNum ++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                }

                //校验作业内容分类
                if (StringUtils.isEmpty(prodCategory)) {
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                } else {
                    if (StringUtils.isEmpty(MesExtEnumUtil.SHIFT_PROD_CATEGORY.descriptionOfValue(prodCategory))) {
                        ++errorNum;
                        cellNum = cellNum + "C;";
                        errorInfo = errorInfo + "第C列数据无效;";
                    }
                }

                //校验是否作业时间
                if (StringUtils.isEmpty(isProdTime)) {
                    errorNum ++;
                    cellNum += "D;";
                    errorInfo += "第D列数据必填;";
                } else {
                    if (StringUtils.isEmpty(MesExtEnumUtil.SHIFT_PROD_IS_PROD_TIME.descriptionOfValue(isProdTime))) {
                        ++errorNum;
                        cellNum = cellNum + "D;";
                        errorInfo = errorInfo + "第D列数据无效;";
                    }
                }

                //校验作业类型
                if (StringUtils.isEmpty(prodType)) {
                    errorNum ++;
                    cellNum += "E;";
                    errorInfo += "第E列数据必填;";
                } else {
                    if (StringUtils.isEmpty(MesExtEnumUtil.SHIFT_PROD_TYPE.descriptionOfValue(prodType))) {
                        ++errorNum;
                        cellNum = cellNum + "E;";
                        errorInfo = errorInfo + "第E列数据无效;";
                    }
                }

                //校验计划比例
                if (StringUtils.isEmpty(planRate)) {
                    errorNum ++;
                    cellNum += "F;";
                    errorInfo += "第F列数据必填;";
                } else {
                    try {
                        if (MathOperation.compareTo(Double.valueOf(planRate), new Double(100)) > 0 ||
                                MathOperation.compareTo(Double.valueOf(planRate), new Double(0)) < 0) {
                            errorNum ++;
                            cellNum += "F;";
                            errorInfo += "第F列数据无效,最大100,最小0;";
                        }
                        String[] planRateArr = planRate.split(MesExtConstWords.DECIMAL_POINT);
                        if (null != planRateArr && planRateArr.length == 2 && planRateArr[1].length() > 2) {
                            errorNum ++;
                            cellNum += "F;";
                            errorInfo += "第F列数据无效,最多2位小数;";
                        }

                    } catch (NumberFormatException e) {
                        errorNum ++;
                        cellNum += "F;";
                        errorInfo += "第F列数据无效;";
                    }
                }

                //没有错误的时候，封装MesShiftProd
                if (errorNum == 0) {
                    MesShiftProd shiftProd;
                    if(isExist){
                        shiftProd = shiftProdMap.get(prodCode).get(0);
                        ConvertBean.serviceModelUpdate(shiftProd, userName);
                    }else{
                        shiftProd = new MesShiftProd();
                        ConvertBean.serviceModelInitialize(shiftProd, userName);
                    }
                    shiftProd.setProdCode(prodCode);
                    shiftProd.setProdName(prodName);
                    shiftProd.setProdCategory(MesExtEnumUtil.SHIFT_PROD_CATEGORY.descriptionOfValue(prodCategory));
                    shiftProd.setIsProdTime(MesExtEnumUtil.SHIFT_PROD_IS_PROD_TIME.descriptionOfValue(isProdTime));
                    shiftProd.setProdType(MesExtEnumUtil.SHIFT_PROD_TYPE.descriptionOfValue(prodType));
                    shiftProd.setPlanRate(Double.valueOf(planRate));
                    shiftProd.setOrganizeCode(organizeCode);

                    shiftProdList.add(shiftProd);

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

    /**
     * 班次作业项目扩展导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelMesShiftProd(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesShiftProd> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesShiftProd shiftProd : excelList) {
                    if(StringUtils.isEmpty(shiftProd.getId())){
                        shiftProdRepository.insert(shiftProd);
                    }else{
                        shiftProdRepository.save(shiftProd);
                    }
                }
            }
        }
    }
}
