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.bean.MesAntiStaticCheck;
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.MesAntiStaticCheckRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
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.stream.Collectors;

/**
 * @Description:防静电工位
 * @Reference:
 * @Author: wangjie
 * @CreateDate:2019\10\9
 * @Modify:
 **/
@Service
public class SxAntiStaticCheckExcelService implements IExcelImportExtService {

    @Autowired
    private CommonExtService commonExtService;

    @Autowired
    private MesAntiStaticCheckRepository antiStaticCheckRepository;

    @Autowired
    private MesWorkCellRepository workCellRepository;

    /**
     * 防静电工位导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractAntiStaticCheck(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelAntiStaticCheck(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

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

        //MesAntiStaticCheck集合
        List<MesAntiStaticCheck> resultList = new ArrayList<>();

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

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

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

        List<MesAntiStaticCheck> resultDbList = antiStaticCheckRepository.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<MesAntiStaticCheck>> resultDbMap = CollectionUtils.isEmpty(resultDbList) ? null :
                resultDbList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getWorkCenterCode()) && !StringUtils.isEmpty(o.getWorkCellCode())))
                        .collect(Collectors.groupingBy(o -> new StringJoiner(MesExtConstWords.AND).add(o.getWorkCenterCode()).add(o.getWorkCellCode()).toString()));

        //查询工位表
        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, List<MesWorkCell>> workCellDBMap = CollectionUtils.isEmpty(workCellList) ? null :
                workCellList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getWorkCenterCode()) && !StringUtils.isEmpty(o.getWorkCellCode())))
                        .collect(Collectors.groupingBy(o -> new StringJoiner(MesExtConstWords.AND).add(o.getWorkCenterCode()).add(o.getWorkCellCode()).toString()));

        //从excel表的第2行数据开始导入，getFirstRowNum是从0行开始读取
        for (int i = (sheetAt.getFirstRowNum() + 1); 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 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) {
                }
                //工位名称
                String workCellName = null;

                if (StringUtils.isEmpty(workCellCode)) {
                    errorNum ++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                } else {
                    String key = new StringJoiner(MesExtConstWords.AND).add(workCenterCode).add(workCellCode).toString();
                    if(!existMap.containsKey(key)){
                        existMap.put(key, String.valueOf(rowNum));
                        //校验数据库是否已经存在生产线与工位的关联关系
                        if(CollectionUtils.isEmpty(workCellDBMap) || !workCellDBMap.containsKey(key)){
                            errorNum ++;
                            cellNum += "A+B;";
                            errorInfo += "第A+B列数据在工位信息中不存在记录";
                        } else {
                            //校验数据库是否已经存在该记录
                            if(!CollectionUtils.isEmpty(resultDbMap) && resultDbMap.containsKey(key)){
                                errorNum ++;
                                cellNum += "A+B;";
                                errorInfo += "第A+B列数据在防静电工位信息中已存在记录";
                            } else {
                                workCellName = workCellDBMap.get(key).get(0).getWorkCellName();
                            }
                        }
                    }else{
                        errorNum ++;
                        cellNum += "A+B;";
                        errorInfo += "第A+B列数据与第" + existMap.get(key) + "行的A+B列数据重复;";
                    }
                }

                //没有错误的时候，封装MesAntiStaticCheck
                if (errorNum == 0) {
                    MesAntiStaticCheck result = new MesAntiStaticCheck();
                    ConvertBean.serviceModelInitialize(result, userName);
                    result.setWorkCenterCode(workCenterCode);
                    result.setWorkCellCode(workCellCode);
                    result.setWorkCellName(workCellName);
                    result.setOrganizeCode(organizeCode);
                    resultList.add(result);
                    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 : resultList);
        return excelImportResultModel;
    }

    /**
     * 防静电工位导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelAntiStaticCheck(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesAntiStaticCheck> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesAntiStaticCheck result : excelList) {
                    antiStaticCheckRepository.insert(result);
                }
            }
        }
    }
}
