package com.qmth.themis.business.templete;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.qmth.themis.business.config.SystemConfig;
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.UploadFileEnum;
import com.qmth.themis.business.service.TBAttachmentService;
import com.qmth.themis.business.service.TBTaskHistoryService;
import com.qmth.themis.business.util.OssUtil;
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.*;
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 String timeFormat = 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() {
        SystemConfig systemConfig = SpringContextHolder.getBean(SystemConfig.class);
        Gson gson = new Gson();
        if (Objects.nonNull(this.map.get("orgId"))) {
            this.orgId = Long.parseLong(String.valueOf(this.map.get("orgId")));
        }
        this.createId = Long.parseLong(String.valueOf(this.map.get("createId")));
        this.ossUtil = SpringContextHolder.getBean(OssUtil.class);
        this.ossEnv = systemConfig.getOssEnv(UploadFileEnum.file.ordinal());
        this.type = (boolean) this.ossEnv.get("oss") ? SystemConstant.OSS : SystemConstant.LOCAL;
        Map tbTaskHistoryMap = (Map) this.map.get("tbTaskHistory");
        this.tbTaskHistory = gson.fromJson(gson.toJson(tbTaskHistoryMap), TBTaskHistory.class);
        this.tbTaskHistoryService = SpringContextHolder.getBean(TBTaskHistoryService.class);
        this.tbAttachmentService = SpringContextHolder.getBean(TBAttachmentService.class);
        this.timeFormat = "yyyy-MM-dd HH:mm:ss";
        map.put("tbTaskHistory", tbTaskHistory);
        map.put("timeFormat", timeFormat);
    }

    /**
     * 创建文件
     *
     * @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(String.valueOf(UUID.randomUUID()).replaceAll("-", ""))
                .add(SystemConstant.EXCEL_PREFIX).toString());
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        return file;
    }

    /**
     * oss上传
     *
     * @param file
     * @throws FileNotFoundException
     */
    public void ossUpload(File file) throws FileNotFoundException {
        boolean oss = (boolean) this.getOssEnv().get(SystemConstant.OSS);
        if (oss) {//上传至oss
            this.ossUtil.ossUpload(this.ossEnv, file.getPath().replaceAll("\\\\", "/"), new FileInputStream(file));
            file.delete();
        }
    }

    /**
     * 创建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 excelFile
     * @throws IOException
     */
    public void writeExportResultTxt(String path, String txtStr, File excelFile) throws IOException {
        FileWriter fileWriter = null;
        try {
            File file = new File(path + File.separator + String.valueOf(UUID.randomUUID()).replaceAll("-", "") + SystemConstant.TXT_PREFIX);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            fileWriter = new FileWriter(file);
            fileWriter.write(txtStr);
            JSONObject json = new JSONObject();
            if (Objects.equals(this.type, SystemConstant.OSS)) {
                json.put("path", file.getPath().replaceAll("\\\\", "/"));
            } else {
                json.put("path", file.getPath());
            }
            json.put("type", this.type);
            this.tbTaskHistory.setReportFilePath(json.toJSONString());
            if (Objects.nonNull(excelFile)) {
                JSONObject excelJson = new JSONObject();
                if (Objects.equals(this.type, SystemConstant.OSS)) {
                    excelJson.put("path", excelFile.getPath().replaceAll("\\\\", "/"));
                } else {
                    excelJson.put("path", excelFile.getPath());
                }

                excelJson.put("type", this.type);
                this.tbTaskHistory.setResultFilePath(excelJson.toJSONString());
            }
            if (Objects.equals(this.type, SystemConstant.OSS)) {
                this.ossUtil.ossUpload(this.ossEnv, file.getPath().replaceAll("\\\\", "/"), txtStr);
                file.delete();
            }
            tbTaskHistoryService.updateById(this.tbTaskHistory);
        } catch (IOException e) {
            log.error("请求出错", e);
        } finally {
            if (Objects.nonNull(fileWriter)) {
                fileWriter.flush();
                fileWriter.close();
            }
        }
    }

    /**
     * 异常处理
     *
     * @param min
     * @param y
     * @param e
     * @param txtList
     * @return
     */
    public List<String> exception(int min, int y, Exception e, List<String> txtList) {
        this.exception = true;
        String exceptionStr = "数据导出到第" + (y == 0 ? y + 1 : y) + "条时发生异常，请联系系统管理员处理！";
        txtList.add(DateUtil.format(new Date(), this.timeFormat) + "->" + exceptionStr);
        this.tbTaskHistory.setSummary(exceptionStr);
        return txtList;
    }

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

    public boolean isException() {
        return exception;
    }

    public String getTimeFormat() {
        return timeFormat;
    }

    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);
    }
}
