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.MesEquipmentCheck;
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.MesEquipmentCheckRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesWorkCenterExtRepository;
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.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkCell;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkCellRepository;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
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.ObjectUtils;
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 SxEquipmentCheckExcelService implements IExcelImportExtService {

    @Autowired
    private MesEquipmentCheckRepository equipmentCheckRepository;

    @Autowired
    private MesWorkCenterExtRepository workCenterExtRepository;

    @Autowired
    private MesWorkCellRepository workCellRepository;

    @Autowired
    private CommonExtService commonExtService;

    /**
     * 工位设备点检导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractMesEquipmentCheck(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesEquipmentCheck(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

    /**
     * 工位设备点检导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractMesEquipmentCheck(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //MesEquipmentCheck集合
        List<MesEquipmentCheck> equipmentCheckList = new ArrayList<>();

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

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

        //用于EXCEL表中的工作中心代码+工位代码+设备代码+项目内容+点检方法+类型唯一校验，key：workCenterCode&workCellCode&equNo&projectContent&checkMethod&checkType，value：row
        Map<String, String> existMap = new HashMap<>();

        // 查询产线表
        Map<String, Object> workCenterCodeEntityMap;
        try {
            workCenterCodeEntityMap = MesCommonUtil.getCodeEntityMap(workCenterExtRepository, MesExtConstWords.WORK_CENTER_CODE, organizeCode, "产线表");
        } catch (Exception e) {
            workCenterCodeEntityMap = null;
        }

        // 查询工位表
        List<MesWorkCell> workCellList = workCellRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesWorkCell>> workCellCodeEntityMap = CollectionUtils.isEmpty(workCellList) ? null :
                workCellList.stream().filter(o -> null != o).collect(Collectors.groupingBy(o -> o.getWorkCenterCode() + "&" + o.getWorkCellCode()));

        //查询工位设备点检表
        List<MesEquipmentCheck> equipmentChecks = equipmentCheckRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue()});
        Map<String, List<MesEquipmentCheck>> equipmentCheckMap = CollectionUtils.isEmpty(equipmentChecks) ? null :
                equipmentChecks.stream().filter(o -> null != o)
                        .collect(Collectors.groupingBy(o -> new StringJoiner(MesExtConstWords.AND)
                                .add(o.getWorkCenterCode()).add(o.getWorkCellCode()).add(o.getEquNo()).add(o.getProjectContent()).add(o.getCheckMethod()).add(o.getCheckType()).toString()));

        //从excel表的第2行数据开始导入，getFirstRowNum是从0行开始读取
        for (int i = (sheetAt.getFirstRowNum() + 1); 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 workCenterCode = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                //工位代码
                String workCellCode = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    workCellCode = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                String workCellName = null;
                //设备编号
                String equNo = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    equNo = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //设备管理号
                String equManageNo = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    equManageNo = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //设备名称
                String equName = null;
                try {
                    row.getCell(4).setCellType(CellType.STRING);
                    equName = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //项目内容
                String projectContent = null;
                try {
                    row.getCell(5).setCellType(CellType.STRING);
                    projectContent = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //点检方法
                String checkMethod = null;
                try {
                    row.getCell(6).setCellType(CellType.STRING);
                    checkMethod = row.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //类型
                String checkType = null;
                try {
                    row.getCell(7).setCellType(CellType.STRING);
                    checkType = row.getCell(7, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //上限值
                String upLimits = null;
                try {
                    row.getCell(8).setCellType(CellType.STRING);
                    upLimits = row.getCell(8, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //下限值
                String downLimits = null;
                try {
                    row.getCell(9).setCellType(CellType.STRING);
                    downLimits = row.getCell(9, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //校验生产线代码
                if (CollectionUtils.isEmpty(workCenterCodeEntityMap) || !workCenterCodeEntityMap.containsKey(workCenterCode)) {
                    errorNum++;
                    cellNum += "A;";
                    errorInfo += "第A列数据无效;";
                }

                //校验工位代码
                if (StringUtils.isEmpty(workCellCode)) {
                    errorNum++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                } else {
                    if (StringUtils.isEmpty(errorInfo)) {
                        if (CollectionUtils.isEmpty(workCellCodeEntityMap) || !workCellCodeEntityMap.containsKey(workCenterCode + "&" + workCellCode)) {
                            errorNum++;
                            cellNum += "A+B;";
                            errorInfo += "第A+B列数据无效;";
                        } else {
                            workCellName = workCellCodeEntityMap.get(workCenterCode + "&" + workCellCode).get(0).getWorkCellName();
                        }
                    }
                }

                //校验设备编号
                if (StringUtils.isEmpty(equNo)) {
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                }

                //校验项目内容
                if (StringUtils.isEmpty(projectContent)) {
                    errorNum ++;
                    cellNum += "F;";
                    errorInfo += "第F列数据必填;";
                } else {
                    if (projectContent.length() > 255) {
                        errorNum++;
                        cellNum += "F;";
                        errorInfo += "第F列数据长度不能超过255个字符;";
                    }
                }

                //校验点击方法
                if (StringUtils.isEmpty(checkMethod)) {
                    errorNum ++;
                    cellNum += "G;";
                    errorInfo += "第G列数据必填;";
                }

                //校验点击方法
                if (StringUtils.isEmpty(checkType)) {
                    errorNum ++;
                    cellNum += "H;";
                    errorInfo += "第H列数据必填;";
                } else {
                    if (StringUtils.isEmpty(MesExtEnumUtil.MES_EQUIPMENT_CHECK_TYPE.valueOfDescription(checkType))) {
                        errorNum ++;
                        cellNum += "H;";
                        errorInfo += "第H列数据无效;";
                    }
                }

                //校验工作中心代码+工位代码+项目内容+点检方法+类型不重复
                String key = new StringJoiner(MesExtConstWords.AND).add(workCenterCode).add(workCellCode).add(equNo).add(projectContent).add(checkMethod).add(checkType).toString();
                if (!existMap.containsKey(key)) {
                    existMap.put(key, String.valueOf(rowNum));
                    //校验 工作中心代码+工位代码+设备代码+项目内容+点检方法+类型 是否已经存在数据库
                    if (StringUtils.isEmpty(errorInfo) && !CollectionUtils.isEmpty(equipmentCheckMap) && equipmentCheckMap.containsKey(key)) {
                        errorNum ++;
                        cellNum += "A+B+C+F+G+H;";
                        errorInfo += "第A+B+C+F+G+H列数据已经存在于数据库;";
                    }
                } else {
                    errorNum ++;
                    cellNum += "A+B+C+F+G+H;";
                    errorInfo += "第A+B+C+F+G+H列数据跟第" + existMap.get(key) + "行的第A+B+C+F+G+H列数据重复;";
                }

                DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(AuthUtil.getOrganizeCode());
                DdlPreparedPack.getStringEqualPack(equNo, "equNo", ddlPackBean);
                DdlPreparedPack.getStringEqualPack(workCellCode, "workCellCode", ddlPackBean);
                DdlPreparedPack.getStringEqualPack(workCenterCode, "workCenterCode", ddlPackBean);
                DdlPreparedPack.getStringEqualPack(projectContent, "projectContent", ddlPackBean);
                DdlPreparedPack.getStringEqualPack(checkMethod, "checkMethod", ddlPackBean);
                DdlPreparedPack.getStringEqualPack(checkType, "checkType", ddlPackBean);
                MesEquipmentCheck mesEquipmentCheck = equipmentCheckRepository.getByProperty(ddlPackBean);
                if (!ObjectUtils.isEmpty(mesEquipmentCheck)) {
                    errorNum ++;
                    cellNum += "数据已存在;";
                    errorInfo += "数据已存在;";
                }

                //上下限值校验

                if ((!StringUtils.isEmpty(upLimits) && StringUtils.isEmpty(downLimits)) ||
                        (StringUtils.isEmpty(upLimits) && !StringUtils.isEmpty(downLimits))){
                    errorNum ++;
                    cellNum += "H+I;";
                    errorInfo += "第H+I列数据缺少,上下限值必须同时存在;";
                }

                //上限值
                Double upLimit = null;
                //下限值
                Double downLimit = null;

                if(!StringUtils.isEmpty(upLimits)){
                    upLimit =  Double.valueOf(upLimits);
                    String[] standard = upLimits.split(MesExtConstWords.DECIMAL_POINT);
                    if (null != standard && standard.length == 2 && standard[1].length() > 4) {
                        errorNum ++;
                        cellNum += "H+I;";
                        errorInfo += "第H+I列数据最多四位小数;";
                    }
                }

                if(!StringUtils.isEmpty(downLimits)){
                    downLimit =  Double.valueOf(downLimits);
                    String[] standard = downLimits.split(MesExtConstWords.DECIMAL_POINT);
                    if (null != standard && standard.length == 2 && standard[1].length() > 4) {
                        errorNum ++;
                        cellNum += "H+I;";
                        errorInfo += "第H+I列数据最多四位小数;";
                    }
                }

                if (!StringUtils.isEmpty(upLimits) && !StringUtils.isEmpty(downLimits)){
                    if (upLimit < downLimit){
                        errorNum ++;
                        cellNum += "H+I;";
                        errorInfo += "第H+I列数据上限值不能小于下限值;";
                    }
                }

                //没有错误的时候，封装MesEquipmentParam
                if (errorNum == 0) {
                    MesEquipmentCheck equipmentCheck = new MesEquipmentCheck();
                    ConvertBean.serviceModelInitialize(equipmentCheck, userName);
                    equipmentCheck.setWorkCenterCode(workCenterCode);
                    equipmentCheck.setWorkCellCode(workCellCode);
                    equipmentCheck.setWorkCellName(workCellName);
                    equipmentCheck.setEquNo(equNo);
                    equipmentCheck.setEquManageNo(equManageNo);
                    equipmentCheck.setEquName(equName);
                    equipmentCheck.setProjectContent(projectContent);
                    equipmentCheck.setCheckMethod(checkMethod);
                    equipmentCheck.setUpLimit(upLimits);
                    equipmentCheck.setDownLimit(downLimits);
                    equipmentCheck.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                    equipmentCheck.setCheckType(checkType);

                    equipmentCheck.setOrganizeCode(organizeCode);

                    equipmentCheckList.add(equipmentCheck);

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

    /**
     * 工位设备点检扩展导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelMesEquipmentCheck(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesEquipmentCheck> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesEquipmentCheck equipmentCheck : excelList) {
                    equipmentCheckRepository.insert(equipmentCheck);
                }
            }
        }
    }
}
