package com.qmth.sop.business.templete.syncData;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.sop.business.entity.TBTask;
import com.qmth.sop.business.service.TBTaskService;
import com.qmth.sop.business.util.ImportExportUtil;
import com.qmth.sop.common.contant.SpringContextHolder;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.TaskResultEnum;
import com.qmth.sop.common.enums.TaskStatusEnum;
import com.qmth.sop.common.util.Result;
import com.qmth.sop.common.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;

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

/**
 * @Description: 同步数据任务模板
 * @Author: CaoZixuan
 * @Date: 2023-10-27
 */
public abstract class AsyncSyncDataTaskTemplate {

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

    public static final String BEGIN_TITLE = "->开始准备处理同步的";

    public static final String EXCEPTION_TITLE = "->数据处理发生异常!";

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

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

    public static final String SUCCESS_TITLE = "条数据，其中成功处理了";

    public static final String FINISH_SIZE = "条数据。";

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

    public static final String ERROR_DATA = "->失败原因如下：";

    public static final String FINISH_TOTAL_SIZE = "条数据，成功";

    public static final String FINISH_SUCCESS_SIZE = "条数据，失败";

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

    /**
     * 异步同步数据任务
     *
     * @param map 数据
     * @return 返回值
     * @throws IOException 异常
     */
    @Async
    public abstract Result syncData(Map<String, Object> map) throws Exception;

    /**
     * 创建txt文件
     *
     * @param tbTask tbTask
     */
    public void createTxt(TBTask tbTask) throws IOException {
        try {
            ImportExportUtil importExportUtil = SpringContextHolder.getBean(ImportExportUtil.class);
            JSONObject json = importExportUtil.createTxt(tbTask.getSummary());
            tbTask.setReportFilePath(json.toJSONString());
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            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()));

            tbTask.setSummary(stringJoinerSummary.toString());
            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);
            tbTask.updateInfo(tbTask.getCreateId());
            tbTaskService.updateById(tbTask);
        }
    }
}