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.bean.SxWorkCellTaktCollectPlcCfg;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesWorkCenterExt;
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.SxWorkCellTaktCollectPlcCfgRepository;
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.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.MesWorkCell;
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.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description : 松下工位节拍PLC配置导入
 * @Reference :
 * @Author : xinwang.yi
 * @CreateDate : 2023-10-23
 * @Modify:
 **/
@Service
public class SxWorkCellTaktCollectPlcCfgExcelService implements IExcelImportExtService {

    @Autowired
    private SxWorkCellTaktCollectPlcCfgRepository sxWorkCellTaktCollectPlcCfgRepository;

    @Autowired
    private MesWorkCellRepository workCellRepository;

    @Autowired
    private CommonExtService commonExtService;

    /**
     * 松下工位节拍PLC配置配置导入
     *
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractSxWorkCellTaktCollectPlcCfg(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelSxWorkCellTaktCollectPlcCfg(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

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

        //SxWorkCellTaktCollectPlcCfg集合
        List<SxWorkCellTaktCollectPlcCfg> sxWorkCellTaktCollectPlcCfgList = new ArrayList<>();

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

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

        //用于EXCEL表中的 松下工位节拍PLC配置 唯一校验
        Map<String, String> sxWorkCellTaktCollectPlcCfgByOnlyMap = new HashMap<>();

        //根据松下工位节拍PLC配置 查询替代料中是否存在数据
        List<SxWorkCellTaktCollectPlcCfg> sxWorkCellTaktCollectPlcCfgDbList = sxWorkCellTaktCollectPlcCfgRepository.findByProperty(
                new String[]{MesConstWords.ORGANIZE_CODE, MesConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, SxWorkCellTaktCollectPlcCfg> sxWorkCellTaktCollectPlcCfgMap = CollectionUtils.isEmpty(sxWorkCellTaktCollectPlcCfgDbList) ? null :
                sxWorkCellTaktCollectPlcCfgDbList.stream().filter(o -> null != o).collect(Collectors.toMap( o -> new StringJoiner(MesExtConstWords.AND).add(o.getWorkCenterCode()).add(o.getWorkCellCode()).toString(), Function.identity()));

        //List<MesWorkCenterExt> workCenterList = workCenterExtRepository.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, MesWorkCenterExt> workCenterCodeMap = CollectionUtils.isEmpty(workCenterList) ? null :
        //        workCenterList.stream().filter(o -> null != o).collect(Collectors.toMap(MesWorkCenterExt::getWorkCenterCode, Function.identity(), (x,y) -> y));

        List<MesWorkCell> workCellList = 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, MesWorkCell> workCellMap = CollectionUtils.isEmpty(workCellList) ? null :
                workCellList.stream().filter(o -> null != o).collect(Collectors.toMap(o -> new StringJoiner(MesExtConstWords.AND).add(o.getWorkCenterCode()).add(o.getWorkCellCode()).toString(), Function.identity(), (x,y) -> y));

        //从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 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) {
                }

                //PLC代码
                String plcCode = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    plcCode = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //产线代码
                String status = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    status = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //校验松下工位节拍PLC配置
                if (StringUtils.isEmpty(workCenterCode)) {
                    errorNum++;
                    cellNum += "A;";
                    errorInfo += "第A列数据必填;";
                }

                //产线代码
                if (StringUtils.isEmpty(workCellCode)) {
                    errorNum++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                } else if (StringUtils.isEmpty(workCenterCode) || (CollectionUtils.isEmpty(workCellMap)) || (!workCellMap.containsKey(new StringJoiner(MesExtConstWords.AND).add(workCenterCode).add(workCellCode).toString()))){
                    errorNum++;
                    cellNum += "B;";
                    errorInfo += "第B列数据无效;";
                }

                if (StringUtils.isEmpty(plcCode)) {
                    errorNum++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                }

                if (!StringUtils.isEmpty(status) && MesExtEnumUtil.IS_ENABLE.descriptionOfValue(status) == null) {
                    errorNum++;
                    cellNum += "D;";
                    errorInfo += "第D列数据无效;";
                }

                String key = new StringJoiner(MesExtConstWords.AND).add(workCenterCode).add(workCellCode).toString();

                Boolean isExist = false;

                //校验唯一性 不重复
                if (!sxWorkCellTaktCollectPlcCfgByOnlyMap.containsKey(key)) {

                    sxWorkCellTaktCollectPlcCfgByOnlyMap.put(key, String.valueOf(rowNum));
                    //根据松下工位节拍PLC配置查询替代信息中是否存在数据

                    //if (StringUtils.isEmpty(errorInfo) && !CollectionUtils.isEmpty(sxWorkCellTaktCollectPlcCfgMap) && sxWorkCellTaktCollectPlcCfgMap.containsKey(key)) {
                    //    errorNum++;
                    //    cellNum += "A;";
                    //    errorInfo += "第A列数据已经存在数据库;";
                    //}

                    //校验是否已经存在数据库
                    if (StringUtils.isEmpty(errorInfo) && !CollectionUtils.isEmpty(sxWorkCellTaktCollectPlcCfgMap) && sxWorkCellTaktCollectPlcCfgMap.containsKey(key)) isExist = true;

                } else {
                    errorNum++;
                    cellNum += "AB;";
                    errorInfo += "第AB列数据跟第" + sxWorkCellTaktCollectPlcCfgByOnlyMap.get(key) +
                            "行的第AB列数据重复;";
                }

                //没有错误的时候，封装SxWorkCellTaktCollectPlcCfg
                if (errorNum == 0) {
                    SxWorkCellTaktCollectPlcCfg sxWorkCellTaktCollectPlcCfg;
                    if (isExist) {
                        sxWorkCellTaktCollectPlcCfg = sxWorkCellTaktCollectPlcCfgMap.get(key);
                        ConvertBean.serviceModelUpdate(sxWorkCellTaktCollectPlcCfg, userName);

                    } else {
                        sxWorkCellTaktCollectPlcCfg = new SxWorkCellTaktCollectPlcCfg();
                        ConvertBean.serviceModelInitialize(sxWorkCellTaktCollectPlcCfg, userName);
                        sxWorkCellTaktCollectPlcCfg.setWorkCenterCode(workCenterCode);
                        sxWorkCellTaktCollectPlcCfg.setWorkCellCode(workCellCode);
                    }

                    sxWorkCellTaktCollectPlcCfg.setPlcCode(workCenterCode);
                    sxWorkCellTaktCollectPlcCfg.setStatus(StringUtils.isEmpty(status) ? MesExtEnumUtil.IS_ENABLE.ENABLE.getValue() : MesExtEnumUtil.IS_ENABLE.descriptionOfValue(status));
                    sxWorkCellTaktCollectPlcCfg.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());

                    sxWorkCellTaktCollectPlcCfgList.add(sxWorkCellTaktCollectPlcCfg);

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

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

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

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

    /**
     * 松下工位节拍PLC配置导入-数据入库
     *
     * @param excelImportResultExtModel
     */
    private void insertExcelSxWorkCellTaktCollectPlcCfg(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<SxWorkCellTaktCollectPlcCfg> processTorqueManageList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(processTorqueManageList)) sxWorkCellTaktCollectPlcCfgRepository.saveAll(processTorqueManageList);
        }
    }
}
