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.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.mes.bean.MesDataObject;
import cn.estsh.i3plus.pojo.mes.bean.MesObjectCfg;
import cn.estsh.i3plus.pojo.mes.repository.MesDataObjectRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesObjectCfgRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesPlcRepository;
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\9
 * @Modify:
 **/
@Service
public class SxObjectCfgExcelService implements IExcelImportExtService {

    @Autowired
    private MesObjectCfgRepository objectCfgRepository;

    @Autowired
    private MesDataObjectRepository dataObjectRepository;

    @Autowired
    private MesPlcRepository plcRepository;

    @Autowired
    private CommonExtService commonExtService;

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

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

        //MesObjectCfg集合
        List<MesObjectCfg> objectCfgList = new ArrayList<>();

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

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

        //用于EXCEL表中的对象代码唯一校验，key：objectCode&fieldCode&plcCode，value：row
        Map<String,String> existMap = new HashMap<>();

        //查询对象结构表
        List<MesObjectCfg> objectCfgs = objectCfgRepository.findByProperty(new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesObjectCfg>> objectCfgMap = objectCfgs.stream().filter(o -> null != o && !StringUtils.isEmpty(o.getObjectCode()) && !StringUtils.isEmpty(o.getFieldCode()) && !StringUtils.isEmpty(o.getPlcCode()))
                .collect(Collectors.groupingBy(o -> (o.getObjectCode() + "&" + o.getFieldCode() + "&" + o.getPlcCode())));

        //查询数据对象
        Map<String, Object> objectCodeEntityMap;
        try {
            objectCodeEntityMap = MesCommonUtil.getCodeEntityMap(dataObjectRepository, MesExtConstWords.OBJECT_CODE, organizeCode, "数据对象表");
        } catch (Exception e) {
            objectCodeEntityMap = null;
        }

        //查询PLC
        Map<String, Object> plcCodeEntityMap;
        try {
            plcCodeEntityMap = MesCommonUtil.getCodeEntityMap(plcRepository, MesExtConstWords.PLC_CODE, organizeCode, "PLC表");
        } catch (Exception e) {
            plcCodeEntityMap = 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 objectCode = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                //plc代码
                String plcCode = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    plcCode = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //字段代码
                String fieldCode = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    fieldCode = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //字段名称
                String fieldName = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    fieldName = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //显示顺序
                String showSeq = null;
                try {
                    row.getCell(4).setCellType(CellType.STRING);
                    showSeq = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //是否显示
                String isShow = null;
                try {
                    row.getCell(5).setCellType(CellType.STRING);
                    isShow = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //校验对象代码
                if (CollectionUtils.isEmpty(objectCodeEntityMap) ||
                        (!CollectionUtils.isEmpty(objectCodeEntityMap) && !objectCodeEntityMap.containsKey(objectCode))) {
                    errorNum++;
                    cellNum += "A;";
                    errorInfo += "第A列数据无效;";
                }

                //校验PLC代码
                if (StringUtils.isEmpty(plcCode)) {
                    errorNum++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                } else {
                    if (CollectionUtils.isEmpty(plcCodeEntityMap) ||
                            (!CollectionUtils.isEmpty(plcCodeEntityMap) && !plcCodeEntityMap.containsKey(plcCode))) {
                        errorNum++;
                        cellNum += "B;";
                        errorInfo += "第B列数据无效;";
                    }
                }

                //校验字段代码
                if (StringUtils.isEmpty(fieldCode)) {
                    errorNum++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                }

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

                //校验字段名称
                if (StringUtils.isEmpty(fieldName)) {
                    errorNum++;
                    cellNum += "D;";
                    errorInfo += "第D列数据必填;";
                }

                //校验显示顺序
                if (!StringUtils.isEmpty(showSeq)) {
                    try {
                        Integer.valueOf(showSeq);
                    } catch (NumberFormatException e) {
                        errorNum++;
                        cellNum += "E;";
                        errorInfo += "第E列数据无效;";
                    }
                }

                //校验显示顺序
                if (!StringUtils.isEmpty(isShow) && StringUtils.isEmpty(CommonEnumUtil.TRUE_OR_FALSE.descriptionOfValue(isShow))) {
                    errorNum++;
                    cellNum += "F;";
                    errorInfo += "第F列数据无效;";
                }


                //没有错误的时候，封装MesObjectCfg
                if (errorNum == 0) {
                    MesObjectCfg objectCfg;
                    if(isExist){
                        objectCfg = objectCfgMap.get(objectCode+"&"+fieldCode+"&"+plcCode).get(0);
                        ConvertBean.serviceModelUpdate(objectCfg, userName);
                    }else{
                        objectCfg = new MesObjectCfg();
                        ConvertBean.serviceModelInitialize(objectCfg, userName);
                    }
                    objectCfg.setObjectCode(objectCode);
                    objectCfg.setPlcCode(plcCode);
                    objectCfg.setFieldCode(fieldCode);
                    objectCfg.setFieldName(fieldName);
                    objectCfg.setShowSeq(StringUtils.isEmpty(showSeq) ? 1 : Integer.valueOf(showSeq));
                    objectCfg.setIsShow(StringUtils.isEmpty(isShow) ? CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() : CommonEnumUtil.TRUE_OR_FALSE.descriptionOfValue(isShow));
                    objectCfg.setOrganizeCode(organizeCode);
                    objectCfgList.add(objectCfg);
                    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 : objectCfgList);
        return excelImportResultModel;
    }

    /**
     * 数据对象导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelDataObject(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesObjectCfg> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesObjectCfg objectCfg : excelList) {
                    if(StringUtils.isEmpty(objectCfg.getId())){
                        objectCfgRepository.insert(objectCfg);
                    }else{
                        objectCfgRepository.save(objectCfg);
                    }
                }
            }
        }
    }
}
