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.service.TBTaskHistoryService;
import com.qmth.themis.business.util.OssUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

/**
 * @Description: 导入任务公用
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/7/19
 */
public class TaskImportCommon {
    private final static Logger log = LoggerFactory.getLogger(TaskImportCommon.class);
    private String mode = null;//mode
    private Map<String, Object> map = null;
    private Long orgId = null;
    private Long createId = null;
    private Long examId = null;
    private TBTaskHistoryService tbTaskHistoryService = null;
    private String type = null;
    private String path = null;
    private Integer uploadType = null;
    private OssUtil ossUtil = null;
    private Map<String, Object> ossEnv = null;
    private TBTaskHistory tbTaskHistory = null;
    private String timeFormat = null;
    private boolean exception = false;
    private List<String> txtList = null;

    public TaskImportCommon() {

    }

    public TaskImportCommon(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("mode"))) {
            this.mode = String.valueOf(this.map.get("mode"));
        }
        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")));
        if (Objects.nonNull(this.map.get("examId"))) {
            this.examId = Long.parseLong(String.valueOf(this.map.get("examId")));
        }
        JSONObject remarkJs = JSONObject.parseObject(String.valueOf(this.map.get("remark")));
        this.type = String.valueOf(remarkJs.get("type"));
        this.path = String.valueOf(remarkJs.get("path"));
        this.uploadType = Integer.parseInt(String.valueOf(remarkJs.get("uploadType")));
        this.ossUtil = SpringContextHolder.getBean(OssUtil.class);
        this.ossEnv = systemConfig.getOssEnv(this.uploadType);
        Map tbTaskHistoryMap = (Map) this.map.get("tbTaskHistory");
        this.tbTaskHistory = gson.fromJson(gson.toJson(tbTaskHistoryMap), TBTaskHistory.class);
        this.tbTaskHistoryService = SpringContextHolder.getBean(TBTaskHistoryService.class);
        this.timeFormat = "yyyy-MM-dd HH:mm:ss";
        map.put("tbTaskHistory", tbTaskHistory);
        map.put("timeFormat", timeFormat);
    }

    /**
     * 获取上传的文件
     *
     * @return
     */
    public File getUploadFile() {
        File file = null;
        if (Objects.nonNull(this.type) && Objects.equals(this.type, SystemConstant.LOCAL)) {
            StringJoiner localPath = new StringJoiner("").add(SystemConstant.FILES_DIR).add(File.separator).add(this.path);
            file = new File(localPath.toString());
        } else {
            try {
                file = this.ossUtil.ossDownload(this.ossEnv, this.path, this.path);
            } catch (IOException e) {
                log.error("请求出错", e);
            }
        }
        return file;
    }

    /**
     * 写入txt文件
     *
     * @param txtStr
     * @param excelFile
     * @throws IOException
     */
    public void writeImportResultTxt(String txtStr, File excelFile) throws IOException {
        FileWriter fileWriter = null;
        try {
            if (Objects.equals(this.type, SystemConstant.LOCAL)) {
                this.path = SystemConstant.FILES_DIR + File.separator + this.path;
            }
            this.path = this.path.substring(0, this.path.lastIndexOf(File.separator) + 1);
            File file = new File(this.path + 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();
            json.put("path", file.getPath());
            json.put("type", this.type);
            this.tbTaskHistory.setReportFilePath(json.toJSONString());
            if (Objects.equals(this.type, SystemConstant.OSS)) {
                this.ossUtil.ossUpload(this.ossEnv, file.getPath(), txtStr);
                file.delete();
                if (Objects.nonNull(excelFile)) {
                    excelFile.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 List<String> getTxtList() {
        return txtList;
    }

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

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

    public boolean isException() {
        return exception;
    }

    public String getTimeFormat() {
        return timeFormat;
    }

    public String getMode() {
        return mode;
    }

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

    public Long getOrgId() {
        return orgId;
    }

    public Long getCreateId() {
        return createId;
    }

    public Long getExamId() {
        return examId;
    }

    public TBTaskHistoryService getTbTaskHistoryService() {
        return tbTaskHistoryService;
    }

    public String getType() {
        return type;
    }

    public String getPath() {
        return path;
    }

    public Integer getUploadType() {
        return uploadType;
    }

    public OssUtil getOssUtil() {
        return ossUtil;
    }

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

    public TBTaskHistory getTbTaskHistory() {
        return tbTaskHistory;
    }
}
