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

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.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.mes.bean.MesEquipment;
import cn.estsh.i3plus.pojo.mes.repository.MesEquipmentRepository;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @PROJECT_NAME: i3plus-mes-panasonic-dev
 * @DESCRIPTION:
 * @USER: xinwang.yi
 * @DATE: 2021-12-13 10:04
 */
@Service
public class SxEpEquipmentExcelService implements IExcelImportExtService {
    @Autowired
    private MesEquipmentRepository equipmentRepository;

    @Autowired
    private CommonExtService commonService;

    /**
     * 设备信息导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultModel = this.sheetExtractMesEquipment(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesEquipment(excelImportResultModel);
        return excelImportResultModel;
    }

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

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //MesEquipment集合
        List<MesEquipment> mesEquipmentList = new ArrayList<>();

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

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

        //用于EXCEL表中的设备代码唯一校验，key：equipmentCode，value：row
        Map<String,String> equipmentCodeMap = new HashMap<>();

        //查询设备表
        List<MesEquipment> equipmentList = equipmentRepository.findByProperty(new String[]{MesConstWords.ORGANIZE_CODE, MesConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesEquipment>> equipmentCodeEntityMap = equipmentList.stream().filter(mesEquipment -> (null != mesEquipment
                && !StringUtils.isEmpty(mesEquipment.getEquipmentCode()))).collect(Collectors.groupingBy(MesEquipment :: getEquipmentCode));

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

                //设备名称
                String equipmentName = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    equipmentName = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //备注
                String memo = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    memo = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

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

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

                //没有错误的时候，封装MesEquipment
                if (errorNum == 0) {
                    MesEquipment mesEquipment;
                    if(isExist){
                        mesEquipment = equipmentCodeEntityMap.get(equipmentCode).get(0);
                        ConvertBean.serviceModelUpdate(mesEquipment,userName);
                    }else {
                        mesEquipment = new MesEquipment();
                        ConvertBean.serviceModelInitialize(mesEquipment, userName);
                    }
                    mesEquipment.setEquipmentCode(equipmentCode);
                    mesEquipment.setEquipmentName(equipmentName);
                    mesEquipment.setMemo(memo);
                    mesEquipment.setOrganizeCode(organizeCode);
                    mesEquipmentList.add(mesEquipment);

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

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

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

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

    /**
     * 设备信息导入-数据入库
     * @param excelImportResultModel
     */
    private void insertExcelMesEquipment(ExcelImportResultExtModel excelImportResultModel) {
        //导入数据
        if (null != excelImportResultModel) {
            List<MesEquipment> excelList = excelImportResultModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesEquipment mesEquipment : excelList) {
                    if(StringUtils.isEmpty(mesEquipment.getId())){
                        equipmentRepository.insert(mesEquipment);
                    }else{
                        equipmentRepository.update(mesEquipment);
                    }
                }
            }
        }
    }
}
