package com.qmth.distributed.print.business.templete.importData;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.teachcloud.common.contant.SpringContextHolder;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.TBTask;
import com.qmth.teachcloud.common.enums.TaskResultEnum;
import com.qmth.teachcloud.common.enums.TaskStatusEnum;
import com.qmth.teachcloud.common.enums.TaskTypeEnum;
import com.qmth.teachcloud.common.enums.UploadFileEnum;
import com.qmth.teachcloud.common.service.TBTaskService;
import com.qmth.teachcloud.common.util.FileStoreUtil;
import com.qmth.teachcloud.common.util.Result;
import com.qmth.teachcloud.common.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;

/**
 * @Description: 同步导入模版
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2021/3/29
 */
public abstract class SyncImportTaskTemplate {
    private final static Logger log = LoggerFactory.getLogger(SyncImportTaskTemplate.class);
    public static final String BEGIN_TITLE = "->开始准备处理导入的";

    public static final String FINISH_TITLE = "数据处理结束，共处理了";

    public static final String FINISH_TOTAL_SIZE = "条数据，正常";

    public static final String FINISH_SUCCESS_SIZE = "条数据，异常";

    public static final String FINISH_ERROR_SIZE = "条数据";

    public static final String EXCEPTION_DATA = "错误信息:";

    public static final String EXCEPTION_CREATE_TXT_TITLE = "->创建导出日志时发生异常!";

    /**
     * 同步导入任务
     *
     * @param map 参数集
     * @return 结果
     * @throws IOException,NoSuchFieldException 异常
     */
    public abstract Result importTask(Map<String, Object> map) throws Exception;

    /**
     * 获取上传的文件
     *
     * @param tbTask 任务
     * @return InputStream
     * @throws IOException 异常
     */
    public InputStream getUploadFileInputStream(TBTask tbTask) throws Exception {
        FileStoreUtil fileStoreUtil = SpringContextHolder.getBean(FileStoreUtil.class);
        JSONObject jsonObject = JSONObject.parseObject(tbTask.getImportFilePath());
        String path = (String) jsonObject.get(SystemConstant.PATH);
        String type = (String) jsonObject.get(SystemConstant.TYPE);
        UploadFileEnum uploadType = Enum.valueOf(UploadFileEnum.class, (String) jsonObject.get(SystemConstant.UPLOAD_TYPE));
        InputStream inputStream;
        if (Objects.equals(type, SystemConstant.OSS)) {
            inputStream = fileStoreUtil.ossDownloadIs(path, uploadType.getFssType());
        } else {
            inputStream = new FileInputStream(path);
        }
        return inputStream;
    }

    /**
     * 创建txt文件
     *
     * @param tbTask 任务
     */
    public void createTxt(TBTask tbTask) throws IOException {
        try {
            JSONObject json = SystemConstant.createTxt(tbTask.getSummary());
            tbTask.setReportFilePath(json.toJSONString());
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e.getMessage());
            StringJoiner stringJoinerSummary = new StringJoiner("").add(tbTask.getSummary()).add("\n");
            stringJoinerSummary.add(MessageFormat.format("{0}{1}{2}{3}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), EXCEPTION_CREATE_TXT_TITLE, EXCEPTION_DATA, e.getMessage()));

            String summary = stringJoinerSummary.toString();
            if (summary.length() >= 65535) {
                summary = "Data too long : " + summary.substring(0, 100) + "......" + summary.substring(summary.length() - 100);
            }

            tbTask.setSummary(summary);
            tbTask.setResult(TaskResultEnum.ERROR);
            if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, ((ApiException) e).getCode(), e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        } finally {
            TBTaskService tbTaskService = SpringContextHolder.getBean(TBTaskService.class);
            tbTask.setStatus(TaskStatusEnum.FINISH);
            tbTaskService.updateById(tbTask);
        }
    }
}
