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.model.ExcelImportErrorExtModel;
import cn.estsh.i3plus.ext.mes.pojo.model.ExcelImportResultExtModel;
import cn.estsh.i3plus.mes.apiservice.util.MesCommonUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.util.MesConstWords;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.MesEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkCell;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkCenter;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkCellRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkCenterRepository;
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 WorkCellExtExcelService implements IExcelImportExtService {

    @Autowired
    private MesWorkCenterRepository workCenterRepository;

    @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 excelImportResultModel = this.sheetExtractMesWorkCell(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesWorkCell(excelImportResultModel);
        return excelImportResultModel;
    }

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

        //MesWorkCell集合
        List<MesWorkCell> workCellList = new ArrayList<>();

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

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

        //用于EXCEL表中的工位代码唯一校验，key：workCenterCode&workCellCode，value：row
        Map<String,String> workCenterCodeAndWorkCellCodeMap = new HashMap<>();

        //查询工位表
        List<MesWorkCell> workCells = workCellRepository.findByProperty(new String[]{MesConstWords.ORGANIZE_CODE, MesConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesWorkCell>> workCellMap = workCells.stream().filter(workCell -> null != workCell)
                .collect(Collectors.groupingBy(workCell -> (workCell.getWorkCenterCode() + "&" + workCell.getWorkCellCode())));

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

        //从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 workCellCode = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                //工位名称
                String workCellName = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    workCellName = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //生产线代码
                String workCenterCode = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    workCenterCode = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //工位类型
                String workCellType = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    workCellType = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //工位等级
                String gradeName = null;
                try {
                    row.getCell(4).setCellType(CellType.STRING);
                    gradeName = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //序号
                String seq = null;
                try {
                    row.getCell(5).setCellType(CellType.STRING);
                    seq = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //区域代码
                String areaCode = null;

                boolean isExist = false;
                //校验 工位代码+生产线 不重复
                if (!workCenterCodeAndWorkCellCodeMap.containsKey(workCenterCode + "&" + workCellCode)) {
                    workCenterCodeAndWorkCellCodeMap.put(workCenterCode + "&" + workCellCode, String.valueOf(rowNum));
                    //校验 工位代码+生产线 是否已经存在数据库
                    if (!StringUtils.isEmpty(workCenterCode) && !StringUtils.isEmpty(workCellCode) && !CollectionUtils.isEmpty(workCellMap)
                            && workCellMap.containsKey(workCenterCode + "&" + workCellCode)) {
                        isExist = true;
                    }
                } else {
                    errorNum ++;
                    cellNum += "AC;";
                    errorInfo += "第A+C列数据跟第" + workCenterCodeAndWorkCellCodeMap.get(workCenterCode + "&" + workCellCode) + "行的第A+C列数据重复;";
                }
                //校验工位名称
                if (StringUtils.isEmpty(workCellName)) {
                    errorNum ++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                }
                //校验生产线代码
                if (StringUtils.isEmpty(workCenterCode)) {
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                } else {
                    if (CollectionUtils.isEmpty(workCenterCodeEntityMap) ||
                            (!CollectionUtils.isEmpty(workCenterCodeEntityMap) && !workCenterCodeEntityMap.containsKey(workCenterCode))) {
                        errorNum ++;
                        cellNum += "C;";
                        errorInfo += "第C列数据无效;";
                    } else {
                        MesWorkCenter workCenter = (MesWorkCenter) workCenterCodeEntityMap.get(workCenterCode);
                        if (null != workCenter) {
                            areaCode = workCenter.getAreaCode();
                        }
                    }
                }
                //校验工位类型
                if (StringUtils.isEmpty(workCellType)) {
                    errorNum ++;
                    cellNum += "D;";
                    errorInfo += "第D列数据必填;";
                } else if (!StringUtils.isEmpty(workCellType) && StringUtils.isEmpty(MesEnumUtil.MES_WORK_CELL_TYPE.descriptionOfValue(workCellType))) {
                    errorNum ++;
                    cellNum += "D;";
                    errorInfo += "第D列数据无效;";
                }

                //校验工位等级
                Integer grade = null;
                if (!StringUtils.isEmpty(gradeName)) {

                    grade = MesEnumUtil.WORK_CELL_GRADE.descriptionOfValue(gradeName);

                    if (grade == null) {
                        errorNum ++;
                        cellNum += "E;";
                        errorInfo += "第E列数据无效;";
                    }

                }

                //校验序号
                if (StringUtils.isEmpty(seq)) {
                    errorNum ++;
                    cellNum += "F;";
                    errorInfo += "第F列数据必填;";
                } else {
                    try {
                        Integer.valueOf(seq);
                    } catch (NumberFormatException e) {
                        errorNum ++;
                        cellNum += "F;";
                        errorInfo += "第F列数据无效;";
                    }
                }

                //没有错误的时候，封装MesWorkCell
                if (errorNum == 0) {

                    MesWorkCell workCell;
                    if(isExist){
                        workCell = workCellMap.get(workCenterCode + "&" + workCellCode).get(0);
                        ConvertBean.serviceModelUpdate(workCell,userName);
                    }else{
                        workCell = new MesWorkCell();
                        ConvertBean.serviceModelInitialize(workCell, userName);
                    }
                    workCell.setWorkCellCode(workCellCode);
                    workCell.setWorkCellName(workCellName);
                    workCell.setWorkCenterCode(workCenterCode);
                    workCell.setAreaCode(areaCode);
                    workCell.setWorkCellType(MesEnumUtil.MES_WORK_CELL_TYPE.descriptionOfValue(workCellType));
                    workCell.setGrade(grade);
                    workCell.setSeq(Integer.valueOf(seq));
                    workCell.setOrganizeCode(organizeCode);

                    workCellList.add(workCell);

                    successRowNum ++;
                } else {
                    //封装错误行信息ExcelImportErrorModel
                    excelImportErrorModels = commonExtService.getExcelImportErrorModels(excelImportErrorModels, rowNum, errorNum, cellNum, errorInfo);

                    errorRows += rowNum + ";";
                    failRowNum ++;
                }
            }
        }

        //校验EXCEL数据
        commonExtService.checkExcelData(failRowNum, successRowNum, errorRows);

        //封装返回结果
        ExcelImportResultExtModel excelImportResultModel = commonExtService.getExcelImportResultModel(failRowNum, successRowNum, excelImportErrorModels, errorRows);
        excelImportResultModel.setExcelList((failRowNum > 0) ? null : workCellList);
        return excelImportResultModel;
    }

    /**
     * 工位导入-数据入库
     * @param excelImportResultModel
     */
    private void insertExcelMesWorkCell(ExcelImportResultExtModel excelImportResultModel) {
        //导入数据
        if (null != excelImportResultModel) {
            List<MesWorkCell> excelList = excelImportResultModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) workCellRepository.saveAll(excelList);
        }
    }
}
