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.model.ExcelImportErrorExtModel;
import cn.estsh.i3plus.ext.mes.pojo.model.ExcelImportResultExtModel;
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.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesDefect;
import cn.estsh.i3plus.pojo.mes.bean.MesTypeCfg;
import cn.estsh.i3plus.pojo.mes.repository.MesDefectRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesTypeCfgRepository;
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\10\16 15:28
 * @Modify:
 **/
@Service
public class SxDefectExcelService implements IExcelImportExtService {

    @Autowired
    private MesDefectRepository defectRepository;

    @Autowired
    private MesTypeCfgRepository typeCfgRepository;

    @Autowired
    private CommonExtService commonExtService;

    /**
     * 缺陷导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractMesDefect(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesDefect(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

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

        //MesDefect集合
        List<MesDefect> defectList = new ArrayList<>();

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

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

        //用于EXCEL表中的唯一校验，key：defectCode，value：row
        Map<String,String> defectMap = new HashMap<>();

        //查询缺陷表
        List<MesDefect> shifts = defectRepository.findByProperty(new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesDefect>> defectDBMap = shifts.stream().filter(defect -> null != defect && !StringUtils.isEmpty(defect.getDefectCode()))
                .collect(Collectors.groupingBy(MesDefect::getDefectCode));

        //查询出缺陷类型信息
        List<MesTypeCfg> typeCfgs = typeCfgRepository.findByProperty(new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.TYPE_CODE},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), MesExtEnumUtil.MES_TYPE_CFG_EXT.BAD.getValue()});
        Map<String, List<MesTypeCfg>> typeCfgMap = typeCfgs.stream().filter(typeCfg -> (null != typeCfg && !StringUtils.isEmpty(typeCfg.getBusinessTypeCode())) )
                .collect(Collectors.groupingBy(MesTypeCfg ::getBusinessTypeCode));

        //从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 defectCode = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();

                //缺陷名称
                String defectName = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    defectName = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //缺陷类型代码
                String defectTypeCode = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    defectTypeCode = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                boolean isExist =false;
                //校验缺陷代码唯一
                if(!defectMap.containsKey(defectCode)){
                    defectMap.put(defectCode,String.valueOf(rowNum));
                    //校验 数据库是否已经存在缺陷代码
                    if (!CollectionUtils.isEmpty(defectDBMap) && defectDBMap.containsKey(defectCode)) {
                        isExist = true;
                    }
                }else{
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据跟第" + defectMap.get(defectCode) + "行的第A列数据重复;";
                }

                //校验缺陷名称必填
                if(StringUtils.isEmpty(defectName)){
                    errorNum ++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                }

                //校验缺陷类型必填
                if(StringUtils.isEmpty(defectTypeCode)){
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                } else {
                    //校验缺陷类型是否匹配
                    if(CollectionUtils.isEmpty(typeCfgMap) || (!CollectionUtils.isEmpty(typeCfgMap) && !typeCfgMap.containsKey(defectTypeCode))){
                        errorNum ++;
                        cellNum += "C;";
                        errorInfo += "第C列数据无效;";
                    }
                }

                //没有错误的时候，封装MesDefect
                if(errorNum == 0){
                    MesDefect defect ;
                    if(isExist){
                        defect = defectDBMap.get(defectCode).get(0);
                        ConvertBean.serviceModelUpdate(defect,userName);
                    }else{
                        defect = new MesDefect();
                        ConvertBean.serviceModelInitialize(defect,userName);
                    }
                    defect.setDefectCode(defectCode);
                    defect.setDefectName(defectName);
                    defect.setDefectType(defectTypeCode);
                    defect.setOrganizeCode(organizeCode);

                    defectList.add(defect);

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

    }

    /**
     * 缺陷导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelMesDefect(ExcelImportResultExtModel excelImportResultExtModel) {
        if (null != excelImportResultExtModel) {
            List<MesDefect> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesDefect defect : excelList) {
                    if(StringUtils.isEmpty(defect.getId())){
                        defectRepository.insert(defect);
                    }else{
                        defectRepository.save(defect);
                    }
                }
            }
        }
    }
}
