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.MesProcedureProject;
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.MesProcedureProjectRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesProjectSortRepository;
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 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 : 质量巡检项目导入，支持编辑
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-04-23
 * @Modify:
 **/
@Service
public class ProcedureProjectExcelService implements IExcelImportExtService {

    @Autowired
    private MesProcedureProjectRepository procedureProjectRepository;

    @Autowired
    private MesProjectSortRepository projectSortRepository;

    @Autowired
    private CommonExtService commonExtService;

    /**
     * 质量巡检项目导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractMesProcedureProject(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesProcedureProject(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

    /**
     * 质量巡检项目导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractMesProcedureProject(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //MesProcedureProject集合
        List<MesProcedureProject> procedureProjectList = new ArrayList<>();

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

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

        //用于EXCEL表中的项目分类代码+项目代码唯一校验，key：procedureProjectNo&projectCode，value：row
        Map<String, String> existMap = new HashMap<>();

        Map<String, Object> procedureProjectNoMap;
        try {
            procedureProjectNoMap = MesCommonUtil.getCodeEntityMap(this.projectSortRepository, MesExtConstWords.PROJECT_SORT_NO, organizeCode, "质量巡检项目分类");
        } catch (Exception var87) {
            procedureProjectNoMap = null;
        }

        //查询质量巡检项目表
        List<MesProcedureProject> procedureProjects = procedureProjectRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, MesProcedureProject> procedureProjectMap = CollectionUtils.isEmpty(procedureProjects) ? null :
                procedureProjects.stream().filter(o -> null != o).collect(Collectors.toMap(o -> new StringJoiner(MesExtConstWords.AND).add(o.getProjectSortNo()).add(o.getProjectCode()).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 = ""; //错误信息

                String procedureProjectNo = null;
                //项目分类代码
                try {
                    //第一列必须有值，否则跳过
                    row.getCell(0).setCellType(CellType.STRING);
                    procedureProjectNo = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                    continue;
                }
                //项目代码
                String projectCode = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    projectCode = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //项目名称
                String projectName = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    projectName = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //校验项目分类代码
                if (CollectionUtils.isEmpty(procedureProjectNoMap) || !procedureProjectNoMap.containsKey(procedureProjectNo)) {
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据无效;";
                }

                //校验项目代码
                if (StringUtils.isEmpty(projectCode)) {
                    errorNum ++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                }

                boolean isExist = false;
                //校验项目分类代码+项目代码不重复
                String key = procedureProjectNo + "&" + projectCode;
                if (!existMap.containsKey(key)) {
                    existMap.put(key, String.valueOf(rowNum));
                    //校验 项目分类代码+项目代码 是否已经存在数据库

                    if (StringUtils.isEmpty(errorInfo) && !CollectionUtils.isEmpty(procedureProjectMap) && procedureProjectMap.containsKey(key)) {

                        MesProcedureProject mesProcedureProject = procedureProjectMap.get(key);
                        if (mesProcedureProject.getIsValid() == CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()) {
                            errorNum ++;
                            cellNum += "A+B;";
                            errorInfo += "第A+B列数据已存在,状态为禁用;";
                        }

                        isExist = true;
                    }
                } else {
                    errorNum ++;
                    cellNum += "A+B;";
                    errorInfo += "第A+B列数据跟第" + existMap.get(key) + "行的第A+B列数据重复;";
                }

                //校验项目名称
                if (StringUtils.isEmpty(projectName)) {
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                }

                //没有错误的时候，封装MesProcedureProject
                if (errorNum == 0) {
                    MesProcedureProject procedureProject;
                    if(isExist) {
                        procedureProject = procedureProjectMap.get(new StringJoiner(MesExtConstWords.AND).add(procedureProjectNo).add(projectCode).toString());
                        ConvertBean.serviceModelUpdate(procedureProject, userName);
                    }else{
                        procedureProject = new MesProcedureProject();
                        ConvertBean.serviceModelInitialize(procedureProject, userName);
                    }
                    procedureProject.setProjectSortNo(procedureProjectNo);
                    procedureProject.setProjectCode(projectCode);
                    procedureProject.setProjectName(projectName);
                    procedureProject.setOrganizeCode(organizeCode);

                    procedureProjectList.add(procedureProject);

                    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 : procedureProjectList);
        return excelImportResultModel;
    }

    /**
     * 质量巡检项目扩展导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelMesProcedureProject(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesProcedureProject> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesProcedureProject procedureProject : excelList) {
                    if(StringUtils.isEmpty(procedureProject.getId())){
                        procedureProjectRepository.insert(procedureProject);
                    }else{
                        procedureProjectRepository.save(procedureProject);
                    }
                }
            }
        }
    }
}
