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.repository.MesWorkCenterExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.mes.apiservice.util.MesCommonUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.MesEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesPlc;
import cn.estsh.i3plus.pojo.mes.bean.MesWcEquipment;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkCell;
import cn.estsh.i3plus.pojo.mes.repository.MesPlcRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesWcEquipmentRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkCellRepository;
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:PLC地址清单导入，支持编辑
 * @Reference:
 * @Author: wangjie
 * @CreateDate:2019\10\9
 * @Modify:
 **/
@Service
public class SxPlcExcelService implements IExcelImportExtService {

    @Autowired
    private MesPlcRepository plcRepository;

    @Autowired
    private CommonExtService commonExtService;

    @Autowired
    private MesWorkCenterExtRepository workCenterExtRepository;

    @Autowired
    private MesWorkCellRepository workCellRepository;

    @Autowired
    private MesWcEquipmentRepository wcEquipmentRepository;

    /**
     * PLC地址清单导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractMesPlc(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesPlc(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

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

        //MesPlc集合
        List<MesPlc> plcList = new ArrayList<>();

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

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

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

        //查询PLC地址清单表
        List<MesPlc> plcs = plcRepository.findByProperty(new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesPlc>> plcDBMap = plcs.stream().filter(plc -> null != plc && !StringUtils.isEmpty(plc.getPlcCode()))
                .collect(Collectors.groupingBy(MesPlc::getPlcCode));

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

        //查询工位表
        List<MesWorkCell> workCells = workCellRepository.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<MesWorkCell>> workCellDBMap = workCells.stream().filter(workCell -> null != workCell && !StringUtils.isEmpty(workCell.getWorkCenterCode()) && !StringUtils.isEmpty(workCell.getWorkCellCode()))
                .collect(Collectors.groupingBy(workCell -> workCell.getWorkCenterCode() + "&" + workCell.getWorkCellCode()));

        //查询工作单元设备关系表
        List<MesWcEquipment> wcEquipments = wcEquipmentRepository.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<MesWcEquipment>> wcEquipmentDBMap = wcEquipments.stream().filter(wcEquipment -> null != wcEquipment && !StringUtils.isEmpty(wcEquipment.getWorkCenterCode()) && !StringUtils.isEmpty(wcEquipment.getWorkCellCode()) && !StringUtils.isEmpty(wcEquipment.getEquipmentCode()))
                .collect(Collectors.groupingBy(wcEquipment -> wcEquipment.getWorkCenterCode() + "&" + wcEquipment.getWorkCellCode() + "&" + wcEquipment.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 = ""; //错误信息

                //PLC代码
                try {
                    //第一列必须有值，否则跳过
                    row.getCell(0).setCellType(CellType.STRING);
                } catch (Exception e) {
                    continue;
                }
                String plcCode = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                //PLC名称
                String plcName = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    plcName = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //PLC型号
                String plcModel = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    plcModel = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //PLC IP
                String plcIp = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    plcIp = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //通道
                String channel = null;
                try {
                    row.getCell(4).setCellType(CellType.STRING);
                    channel = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //驱动
                String device = null;
                try {
                    row.getCell(5).setCellType(CellType.STRING);
                    device = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //标签地址
                String tagAddress = null;
                try {
                    row.getCell(6).setCellType(CellType.STRING);
                    tagAddress = row.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //标签名称
                String tagName = null;
                try {
                    row.getCell(7).setCellType(CellType.STRING);
                    tagName = row.getCell(7, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //标签数据类型
                String dataType = null;
                try {
                    row.getCell(8).setCellType(CellType.STRING);
                    dataType = row.getCell(8, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //OPCUA路径
                String opcUrl = null;
                try {
                    row.getCell(9).setCellType(CellType.STRING);
                    opcUrl = row.getCell(9, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //生产线
                String workCenterCode = null;
                try {
                    row.getCell(10).setCellType(CellType.STRING);
                    workCenterCode = row.getCell(10, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //工位
                String workCellCode = null;
                try {
                    row.getCell(11).setCellType(CellType.STRING);
                    workCellCode = row.getCell(11, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //设备代码
                String equipmentCode = null;
                try {
                    row.getCell(12).setCellType(CellType.STRING);
                    equipmentCode = row.getCell(12, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

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

                //校验PLC名称
                if(StringUtils.isEmpty(plcName)){
                    errorNum ++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                }
                //校验PLC IP
                if(StringUtils.isEmpty(plcIp)){
                    errorNum ++;
                    cellNum += "D;";
                    errorInfo += "第D列数据必填;";
                }
                //校验通道
                if(StringUtils.isEmpty(channel)){
                    errorNum ++;
                    cellNum += "E;";
                    errorInfo += "第E列数据必填;";
                }
                //校验驱动
                if(StringUtils.isEmpty(device)){
                    errorNum ++;
                    cellNum += "F;";
                    errorInfo += "第F列数据必填;";
                }
                //校验标签地址
                if(StringUtils.isEmpty(tagAddress)){
                    errorNum ++;
                    cellNum += "G;";
                    errorInfo += "第G列数据必填;";
                }
                //校验标签数据类型
                if(StringUtils.isEmpty(dataType)){
                    errorNum ++;
                    cellNum += "I;";
                    errorInfo += "第I列数据必填;";
                } else {
                    if (StringUtils.isEmpty(MesEnumUtil.PLC_DATA_TYPE.codeOfValue(dataType))) {
                        errorNum ++;
                        cellNum += "I;";
                        errorInfo += "第I列数据格式错误;";
                    } else {
                        dataType = MesEnumUtil.PLC_DATA_TYPE.codeOfValue(dataType);
                    }
                }
                //校验标签地址
                if(StringUtils.isEmpty(opcUrl)){
                    errorNum ++;
                    cellNum += "J;";
                    errorInfo += "第J列数据必填;";
                }
                //校验生产线
                if(StringUtils.isEmpty(workCenterCode)){
                    errorNum ++;
                    cellNum += "K;";
                    errorInfo += "第K列数据必填;";
                }else{
                    //校验生产线有效性
                    if(CollectionUtils.isEmpty(workCenterCodeEntityMap) || (!CollectionUtils.isEmpty(workCenterCodeEntityMap) && !workCenterCodeEntityMap.containsKey(workCenterCode))){
                        errorNum ++;
                        cellNum += "K;";
                        errorInfo += "第K列数据无效;";
                    }else{
                        //校验工位
                        if(StringUtils.isEmpty(workCellCode)){
                            errorNum ++;
                            cellNum += "L;";
                            errorInfo += "第L列数据必填;";
                        }else{
                            //校验工位的有效性
                            if(CollectionUtils.isEmpty(workCellDBMap) || (!CollectionUtils.isEmpty(workCellDBMap) && !workCellDBMap.containsKey(workCenterCode + "&" + workCellCode))){
                                errorNum ++;
                                cellNum += "L;";
                                errorInfo += "第L列数据无效;";
                            }else{
                                //校验设备代码是否有效
                                if(!StringUtils.isEmpty(equipmentCode) && (null == wcEquipmentDBMap || wcEquipmentDBMap.size() == 0 || !wcEquipmentDBMap.containsKey(workCenterCode + "&" + workCellCode + "&" + equipmentCode))){
                                    errorNum ++;
                                    cellNum += "M;";
                                    errorInfo += "第M列数据无效;";
                                }
                            }
                        }
                    }
                }


                //没有错误的时候，封装MesPlc
                if (errorNum == 0) {
                    MesPlc plc;
                    if(isExist){
                        plc = plcDBMap.get(plcCode).get(0);
                        ConvertBean.serviceModelUpdate(plc,userName);
                    }else{
                        plc = new MesPlc();
                        ConvertBean.serviceModelInitialize(plc, userName);
                    }
                    plc.setPlcCode(plcCode);
                    plc.setPlcName(plcName);
                    plc.setPlcModel(plcModel);
                    plc.setPlcIp(plcIp);
                    plc.setChannel(channel);
                    plc.setDevice(device);
                    plc.setTagAddress(tagAddress);
                    plc.setTagName(tagName);
                    plc.setOpcUrl(opcUrl);
                    plc.setDataType(dataType);
                    plc.setEquipmentCode(equipmentCode);
                    plc.setWorkCenterCode(workCenterCode);
                    plc.setWorkCellCode(workCellCode);
                    plc.setOrganizeCode(organizeCode);
                    plcList.add(plc);
                    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 : plcList);
        return excelImportResultModel;
    }

    /**
     * PLC地址清单导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelMesPlc(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesPlc> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesPlc plc : excelList) {
                    if(StringUtils.isEmpty(plc.getId())){
                        plcRepository.insert(plc);
                    }else{
                        plcRepository.save(plc);
                    }
                }
            }
        }
    }
}
