package cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.excel;

import cn.estsh.i3plus.ext.mes.api.base.IExcelImportExtService;
import cn.estsh.i3plus.ext.mes.api.base.IShiftExtService;
import cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.base.CommonExtService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesShiftExt;
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.MesShiftExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.ConvertBeanExt;
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.MesWorkCenter;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkCenterRepository;
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.text.ParseException;
import java.text.SimpleDateFormat;
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-04-23
 * @Modify:
 **/
@Service
public class ShiftExtExcelService implements IExcelImportExtService {

    @Autowired
    private MesShiftExtRepository shiftExtRepository;

    @Autowired
    private IShiftExtService shiftExtService;

    @Autowired
    private MesWorkCenterRepository workCenterRepository;

    @Autowired
    private CommonExtService commonExtService;

    /**
     * 班次扩展导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractMesShiftExt(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesShiftExt(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

    /**
     * 班次扩展导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractMesShiftExt(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //MesShiftExt集合
        List<MesShiftExt> shiftExtList = new ArrayList<>();

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

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

        //用于EXCEL表中的班次代码+生产线唯一校验，key：shiftCode&workCenterCode，value：row
        Map<String,String> shiftCodeAndworkCenterCodeMap = new HashMap<>();

        SimpleDateFormat sdf = new SimpleDateFormat(MesExtConstWords.TIME_TRUNCATE_SECOND_FORMAT);

        //查询班次表
        List<MesShiftExt> shiftExts = shiftExtRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesShiftExt>> shiftExtMap = shiftExts.stream().filter(shift -> null != shift)
                .collect(Collectors.groupingBy(shift -> shift.getShiftCode() + "&" + shift.getWorkCenterCode()));

        //查询生产线表
        Map<String, Object> workCenterCodeEntityMap;
        try {
            workCenterCodeEntityMap = MesCommonUtil.getCodeEntityMap(workCenterRepository, MesExtConstWords.WORK_CENTER_CODE, organizeCode, "生产线表");
        } catch (Exception e) {
            workCenterCodeEntityMap = 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 workCenterCode = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                //班次代码
                String shiftCode = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    shiftCode = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //班次名称
                String shiftName = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    shiftName = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //开班时间
                String startTime = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    startTime = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //下班时间
                String endTime = null;
                try {
                    row.getCell(4).setCellType(CellType.STRING);
                    endTime = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //作业人数
                String workerQty = null;
                try {
                    row.getCell(5).setCellType(CellType.STRING);
                    workerQty = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //班次顺序
                String shiftSeq = null;
                try {
                    row.getCell(6).setCellType(CellType.STRING);
                    shiftSeq = row.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //校验生产线代码
                if (CollectionUtils.isEmpty(workCenterCodeEntityMap) ||
                        (!CollectionUtils.isEmpty(workCenterCodeEntityMap) && !workCenterCodeEntityMap.containsKey(workCenterCode))) {
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据无效;";
                }

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

                boolean isExist = false;
                //校验班次+生产线不重复
                if (!shiftCodeAndworkCenterCodeMap.containsKey(shiftCode + "&" + workCenterCode)) {
                    shiftCodeAndworkCenterCodeMap.put(shiftCode + "&" + workCenterCode, String.valueOf(rowNum));
                    //校验 班次+生产线 是否已经存在数据库
                    if (StringUtils.isEmpty(errorInfo) && !CollectionUtils.isEmpty(shiftExtMap) && shiftExtMap.containsKey(shiftCode + "&" + workCenterCode)) {
                        isExist = true;
                    }
                } else {
                    errorNum ++;
                    cellNum += "AB;";
                    errorInfo += "第A+B列数据跟第" + shiftCodeAndworkCenterCodeMap.get(shiftCode + "&" + workCenterCode) + "行的第A+B列数据重复;";
                }

                //校验班次名称
                if (StringUtils.isEmpty(shiftName)) {
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                }
                //校验开班时间
                if (StringUtils.isEmpty(startTime)) {
                    errorNum ++;
                    cellNum += "D;";
                    errorInfo += "第D列数据必填;";
                } else {
                    try {
                        sdf.parse(startTime);
                        if ((startTime.split(":")).length != 2) {
                            errorNum ++;
                            cellNum += "D;";
                            errorInfo += "第D列[HH:mm]数据格式错误;";
                        }
                    } catch (ParseException e) {
                        errorNum ++;
                        cellNum += "D;";
                        errorInfo += "第D列[HH:mm]数据格式错误;";
                    }
                }
                //校验下班时间
                if (StringUtils.isEmpty(endTime)) {
                    errorNum ++;
                    cellNum += "E;";
                    errorInfo += "第E列数据必填;";
                } else {
                    try {
                        sdf.parse(endTime);
                        if ((endTime.split(":")).length != 2) {
                            errorNum ++;
                            cellNum += "E;";
                            errorInfo += "第E列[HH:mm]数据格式错误;";
                        }
                    } catch (ParseException e) {
                        errorNum ++;
                        cellNum += "E;";
                        errorInfo += "第E列数据格式错误;";
                    }
                }
                //校验作业人数
                if (StringUtils.isEmpty(workerQty)) {
                    errorNum ++;
                    cellNum += "F;";
                    errorInfo += "第F列数据必填;";
                } else {
                    try {
                        if (Integer.valueOf(workerQty).compareTo(0) <= 0) {
                            errorNum ++;
                            cellNum += "F;";
                            errorInfo += "第F列数据无效;";
                        }
                    } catch (NumberFormatException e) {
                        errorNum ++;
                        cellNum += "F;";
                        errorInfo += "第F列数据无效;";
                    }
                }
                //校验班次顺序
                if (!StringUtils.isEmpty(shiftSeq)) {
                    try {
                        Integer.valueOf(shiftSeq);
                    } catch (NumberFormatException e) {
                        errorNum ++;
                        cellNum += "G;";
                        errorInfo += "第G列数据无效;";
                    }
                } else {
                    shiftSeq = "1";
                }

                //没有错误的时候，封装MesShiftExt
                if (errorNum == 0) {
                    MesShiftExt shiftExt;
                    if(isExist){
                        shiftExt = shiftExtMap.get(shiftCode + "&" + workCenterCode).get(0);
                        ConvertBean.serviceModelUpdate(shiftExt,userName);
                    }else{
                        shiftExt = new MesShiftExt();
                        ConvertBean.serviceModelInitialize(shiftExt,userName);
                    }
                    shiftExt.setShiftCode(shiftCode);
                    shiftExt.setShiftName(shiftName);
                    shiftExt.setWorkCenterCode(workCenterCode);
                    shiftExt.setAreaCode(((MesWorkCenter)workCenterCodeEntityMap.get(workCenterCode)).getAreaCode());
                    shiftExt.setStartTime(new StringBuilder().append(startTime).append(MesExtConstWords.APPEND_SECONDS).toString());
                    shiftExt.setEndTime(new StringBuilder().append(endTime).append(MesExtConstWords.APPEND_SECONDS).toString());
                    shiftExt.setWorkTimes(shiftExtService.getShiftWorkTimes(shiftExt.getStartTime(), shiftExt.getEndTime()));
                    shiftExt.setShiftSeq(Integer.valueOf(shiftSeq));
                    shiftExt.setWorkerQty(Double.parseDouble(workerQty));
                    shiftExt.setOrganizeCode(organizeCode);
                    new ConvertBeanExt(shiftExt).convertBean(shiftExt);

                    shiftExtList.add(shiftExt);

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

    /**
     * 班次扩展导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelMesShiftExt(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesShiftExt> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesShiftExt shiftExt : excelList) {
                    if(StringUtils.isEmpty(shiftExt.getId())){
                        shiftExtRepository.insert(shiftExt);
                    }else{
                        shiftExtRepository.save(shiftExt);
                    }
                }
            }
        }
    }
}
