package cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.excel.jx;

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.MesBadnessClassify;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesBadnessType;
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.MesBadnessClassifyRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesBadnessTypeRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
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.*;
import java.util.stream.Collectors;

/**
 * @Description:不良分类导入
 * @Reference:
 * @Author: wangjie
 * @CreateDate: 2019\11\4 10:39
 * @Modify:
 **/
@Service
public class JxBadnessClassifyExcelService implements IExcelImportExtService {

    @Autowired
    private MesBadnessTypeRepository buBadnessTypeDao;

    @Autowired
    private MesBadnessClassifyRepository buBadnessClassifyDao;

    @Autowired
    private CommonExtService commonExtService;

    /**
     * 不良分类导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractBadnessType(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelBadnessType(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

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

        //MesBadnessType集合
        List<MesBadnessClassify> sxQmsBuBadnessClassifyList = new ArrayList<>();

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

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

        //用于EXCEL表中的 不良类型编码,不良分类编码 唯一校验，key：badnessTypeCode,BadnessClassifyCode，value：row
        Map<String,String> existMap = new HashMap<>();

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

        Map<String, List<MesBadnessType>> badnessTypeMap = CollectionUtils.isEmpty(sxQmsBuBadnessTypeDbs) ? null :
                sxQmsBuBadnessTypeDbs.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getBadnessTypeCode())))
                .collect(Collectors.groupingBy(MesBadnessType::getBadnessTypeCode));

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

        Map<String, List<MesBadnessClassify>> badnessClassifieMap = CollectionUtils.isEmpty(badnessClassifieList) ? null :
                badnessClassifieList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getBadnessTypeCode()) && !StringUtils.isEmpty(o.getBadnessClassifyCode())))
                        .collect(Collectors.groupingBy( o-> (new StringJoiner(MesExtConstWords.AND).add(o.getBadnessTypeCode()).add(o.getBadnessClassifyCode()).toString())));

        //从excel表的第5行数据开始导入，getFirstRowNum是从5行开始读取
        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 badnessTypeCode = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                //不良分类编码
                String badnessClassifyCode = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    badnessClassifyCode = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //不良分类名称
                String badnessClassifyName = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    badnessClassifyName = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                String badnessTypeName = null;
                if (StringUtils.isEmpty(badnessTypeCode)) {
                    errorNum++;
                    cellNum += "A;";
                    errorInfo += "第A列数据必填;";
                }else{
                    if(!badnessTypeMap.containsKey(badnessTypeCode)){
                        errorNum++;
                        cellNum += "A;";
                        errorInfo += "第A列数据无效;";
                    }else{
                        badnessTypeName = badnessTypeMap.get(badnessTypeCode).get(0).getBadnessTypeName();
                    }
                }

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

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

                boolean isExist = false;
                if(!existMap.containsKey(new StringJoiner(MesExtConstWords.AND).add(badnessTypeCode).add(badnessClassifyCode).toString())){

                    existMap.put(new StringJoiner(MesExtConstWords.AND).add(badnessTypeCode).add(badnessClassifyCode).toString(), String.valueOf(rowNum));
                    //校验 不良分类数据 是否已经存在数据库
                    if (StringUtils.isEmpty(errorInfo) && !CollectionUtils.isEmpty(badnessClassifieMap) && badnessClassifieMap.containsKey(new StringJoiner(MesExtConstWords.AND).add(badnessTypeCode).add(badnessClassifyCode).toString())) {
                        isExist = true;
                    }
                }else {
                    errorNum ++;
                    cellNum += "A+C;";
                    errorInfo += "第A+C列数据跟第" + existMap.get(new StringJoiner(MesExtConstWords.AND).add(badnessTypeCode).add(badnessClassifyCode).toString()) + "行的第A+C列数据重复;";
                }

                //没有错误的时候，封装SxQmsOqcProject
                if (errorNum == 0) {
                    MesBadnessClassify item;
                    if(isExist) {
                        item = badnessClassifieMap.get(new StringJoiner(MesExtConstWords.AND).add(badnessTypeCode).add(badnessClassifyCode).toString()).get(0);
                        ConvertBean.serviceModelUpdate(item, userName);
                    }else{
                        item = new MesBadnessClassify();
                    }

                    item.setBadnessTypeCode(badnessTypeCode);
                    item.setBadnessTypeName(badnessTypeName);
                    item.setBadnessClassifyCode(badnessClassifyCode);
                    item.setBadnessClassifyName(badnessClassifyName);
                    item.setOrganizeCode(organizeCode);
                    ConvertBean.serviceModelInitialize(item, userName);
                    sxQmsBuBadnessClassifyList.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 : sxQmsBuBadnessClassifyList);
        return excelImportResultExtModel;
    }

    /**
     * 不良分类导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelBadnessType(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesBadnessClassify> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) buBadnessClassifyDao.saveAll(excelList);
        }
    }
}
