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

import cn.estsh.i3plus.ext.mes.api.base.ICommonExtService;
import cn.estsh.i3plus.ext.mes.api.base.IExcelImportExtService;
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.MesExtEnumUtil;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.util.SpringContextsUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @Description : 通用功能服务方法调度类
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-08-26
 * @Modify:
 **/
@Service
public class CommonExtService implements ICommonExtService {

    public static final Logger LOGGER = LoggerFactory.getLogger(CommonExtService.class);

    /**
     * mes导入
     *
     * @param file
     * @param module
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(MultipartFile file, Integer module) {
        ExcelImportResultExtModel excelImportResultExtModel;
        InputStream inputStream = null;
        Workbook workbook = null;

        try {
            inputStream = file.getInputStream();
            workbook = WorkbookFactory.create(inputStream);
            IExcelImportExtService excelImportExtService = (IExcelImportExtService) SpringContextsUtil.getBean(MesExtEnumUtil.MES_EXT_EXCEL.valueOfService(module));
            if (null == excelImportExtService) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("没有找到业务实现类")
                        .build();
            }
            excelImportResultExtModel = excelImportExtService.insertDataByExcel(workbook, AuthUtil.getOrganize().getOrganizeCode(), AuthUtil.getSessionUser().getUserName());
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("文件异常，请重新上传EXCEL文件")
                    .build();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("文件异常，请重新上传EXCEL文件" + e.getMessage())
                    .build();
        } finally {
            try {
                workbook.close();
                inputStream.close();
            } catch (IOException e) {
                LOGGER.error("IOException!", e);
            }
        }

        return excelImportResultExtModel;
    }

    /**
     * 封装错误行信息ExcelImportErrorExtModel
     *
     * @param excelImportErrorExtModels
     * @param rowNum
     * @param errorNum
     * @param cellNum
     * @param errorInfo
     * @return
     */
    public List<ExcelImportErrorExtModel> getExcelImportErrorModels(List<ExcelImportErrorExtModel> excelImportErrorExtModels,
                                                                 int rowNum, int errorNum, String cellNum, String errorInfo) {
        ExcelImportErrorExtModel excelImportErrorExtModel = new ExcelImportErrorExtModel();
        excelImportErrorExtModel.setRowNum(rowNum);
        excelImportErrorExtModel.setErrorNum(errorNum);
        excelImportErrorExtModel.setCellNum(StringUtils.isEmpty(cellNum) ? null : cellNum.substring(0, cellNum.length() - 1));
        excelImportErrorExtModel.setErrorInfo(StringUtils.isEmpty(errorInfo) ? null : errorInfo.substring(0, errorInfo.length() - 1));
        excelImportErrorExtModels.add(excelImportErrorExtModel);
        return excelImportErrorExtModels;
    }

    /**
     * 校验EXCEL数据
     *
     * @param failRowNum
     * @param successRowNum
     * @param errorRows
     */
    public void checkExcelData(Integer failRowNum, Integer successRowNum, String errorRows) {
        if (failRowNum == 0 && successRowNum == 0 && StringUtils.isEmpty(errorRows)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("请检查EXCEL数据，没有数据可以导入")
                    .build();
        }
    }

    /**
     * 封装返回结果
     *
     * @param failRowNum
     * @param successRowNum
     * @param excelImportErrorExtModels
     * @param errorRows
     * @return
     */
    public ExcelImportResultExtModel getExcelImportResultModel(Integer failRowNum, Integer successRowNum,
                                                            List<ExcelImportErrorExtModel> excelImportErrorExtModels, String errorRows) {
        ExcelImportResultExtModel excelImportResultExtModel = new ExcelImportResultExtModel();
        excelImportResultExtModel.setResult((failRowNum > 0) ? false : true);
        excelImportResultExtModel.setSuccessRowNum(successRowNum);
        excelImportResultExtModel.setFailRowNum(failRowNum);
        excelImportResultExtModel.setExcelImportErrorModels(excelImportErrorExtModels);
        excelImportResultExtModel.setErrorRows(StringUtils.isEmpty(errorRows) ? null : errorRows.substring(0, errorRows.length() - 1));
        return excelImportResultExtModel;
    }


}
