package com.qmth.themis.business.templete;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.qmth.themis.business.constant.SpringContextHolder;
import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.entity.TBTaskHistory;
import com.qmth.themis.business.enums.TaskStatusEnum;
import com.qmth.themis.business.enums.UploadFileEnum;
import com.qmth.themis.business.service.TBAttachmentService;
import com.qmth.themis.business.service.TBTaskHistoryService;
import com.qmth.themis.business.util.OssUtil;
import com.qmth.themis.common.contanst.Constants;
import com.qmth.themis.common.util.GsonUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @Description: 导出任务公用
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/7/19
 */
public class TaskExportCommon {

    private final static Logger log = LoggerFactory.getLogger(TaskExportCommon.class);

    private Map<String, Object> map = null;

    private Long orgId = null;

    private Long createId = null;

    private TBTaskHistoryService tbTaskHistoryService = null;

    private OssUtil ossUtil = null;

    private Map<String, Object> ossEnv = null;

    private TBTaskHistory tbTaskHistory = null;

    private boolean exception = false;

    private TBAttachmentService tbAttachmentService = null;

    private String type = null;

    private List<String> txtList = null;

    public TaskExportCommon() {

    }

    public TaskExportCommon(Map<String, Object> map) {
        this.map = map;
    }

    /**
     * 初始化
     */
    public void init() {
        OssUtil ossUtil = SpringContextHolder.getBean(OssUtil.class);
        if (Objects.nonNull(this.map.get(SystemConstant.ORG_ID))) {
            this.orgId = Long.parseLong(String.valueOf(this.map.get(SystemConstant.ORG_ID)));
        }
        this.createId = Long.parseLong(String.valueOf(this.map.get(SystemConstant.CREATE_ID)));
        this.ossUtil = SpringContextHolder.getBean(OssUtil.class);
        this.ossEnv = ossUtil.getAliYunOssPrivateDomain().getMap();
        this.type = (boolean) this.ossEnv.get(SystemConstant.OSS) ? SystemConstant.OSS : SystemConstant.LOCAL;
        Map tbTaskHistoryMap = (Map) this.map.get("tbTaskHistory");
        this.tbTaskHistory = GsonUtil.fromJson(GsonUtil.toJson(tbTaskHistoryMap), TBTaskHistory.class);
        this.tbTaskHistoryService = SpringContextHolder.getBean(TBTaskHistoryService.class);
        this.tbAttachmentService = SpringContextHolder.getBean(TBAttachmentService.class);
        map.put("tbTaskHistory", tbTaskHistory);
    }

    /**
     * 创建文件
     *
     * @param path
     * @return
     * @throws IOException
     */
    public File createExcel(String path) throws IOException {
        StringJoiner stringJoiner = new StringJoiner("");
        File file = new File(
                stringJoiner.add(path).add(File.separator).add(SystemConstant.getNanoId())
                        .add(SystemConstant.EXCEL_PREFIX).toString());
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        return file;
    }

    /**
     * oss上传
     *
     * @param inputStream
     * @param path
     * @throws FileNotFoundException
     */
    public String ossUpload(InputStream inputStream, String path) throws IOException {
        StringJoiner stringJoiner = new StringJoiner("");
        boolean oss = (boolean) this.getOssEnv().get(SystemConstant.OSS);
        if (oss) {//上传至oss
            stringJoiner.add(path).add(File.separator).add(SystemConstant.getNanoId())
                    .add(SystemConstant.EXCEL_PREFIX).toString();
            this.ossUtil.upload(false, stringJoiner.toString(), inputStream, null);
        }
        return stringJoiner.toString();
    }

    /**
     * 创建excel列
     *
     * @param sxssfRow
     * @param cellIndex
     * @param excelValue
     * @param style
     */
    public void createExcelCell(Row sxssfRow, int cellIndex, Object excelValue, CellStyle style) {
        Cell cell = sxssfRow.createCell(cellIndex);
        cell.setCellValue((String) excelValue);
        cell.setCellStyle(style);
    }

    /**
     * 写入txt文件
     *
     * @param path
     * @param txtStr
     * @param excelFilePath
     * @throws IOException
     */
    public void writeExportResultTxt(String path, String txtStr, String excelFilePath) {
        try {
            JSONObject json = SystemConstant.createTxt(path, this.type, txtStr);
            this.tbTaskHistory.setReportFilePath(json.toJSONString());
            if (Objects.nonNull(excelFilePath)) {
                JSONObject excelJson = new JSONObject();
                excelJson.put(SystemConstant.PATH, excelFilePath);
                excelJson.put(SystemConstant.TYPE, this.type);
                excelJson.put(SystemConstant.UPLOAD_TYPE, UploadFileEnum.file.ordinal());
                this.tbTaskHistory.setResultFilePath(excelJson.toJSONString());
            }
            tbTaskHistoryService.updateById(this.tbTaskHistory);
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
        }
    }

    /**
     * 异常处理
     *
     * @param line
     * @param e
     * @param txtList
     * @return
     */
    public List<String> exception(int line, Exception e, List<String> txtList) {
        this.exception = true;
        String exceptionStr = "数据导出到第" + (line == 0 ? line + 1 : line) + "条时发生异常，请联系系统管理员处理！";
        txtList.add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->" + exceptionStr + "错误信息:[" + e.getMessage() + "]");
        this.tbTaskHistory.setSummary(exceptionStr);
        this.tbTaskHistory.setStatus(TaskStatusEnum.FINISH);
        return txtList;
    }

    public void setException(boolean exception) {
        this.exception = exception;
    }

    public boolean isException() {
        return exception;
    }

    public Map<String, Object> getMap() {
        return map;
    }

    public Long getOrgId() {
        return orgId;
    }

    public Long getCreateId() {
        return createId;
    }

    public TBTaskHistoryService getTbTaskHistoryService() {
        return tbTaskHistoryService;
    }

    public OssUtil getOssUtil() {
        return ossUtil;
    }

    public Map<String, Object> getOssEnv() {
        return ossEnv;
    }

    public TBTaskHistory getTbTaskHistory() {
        return tbTaskHistory;
    }

    public TBAttachmentService getTbAttachmentService() {
        return tbAttachmentService;
    }

    public List<String> getTxtList() {
        return txtList;
    }

    public void setTxtList(List<String> txtList) {
        this.txtList = txtList;
        map.put("txtList", txtList);
    }
}