package com.qmth.paper.library.business.templete.execute;

import cn.hutool.core.date.DateUtil;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.paper.library.business.templete.export.AsyncExportTaskTemplate;
import com.qmth.paper.library.business.templete.service.TaskLogicService;
import com.qmth.paper.library.common.contant.SpringContextHolder;
import com.qmth.paper.library.common.contant.SystemConstant;
import com.qmth.paper.library.common.entity.TBTask;
import com.qmth.paper.library.common.enums.TaskResultEnum;
import com.qmth.paper.library.common.enums.TaskStatusEnum;
import com.qmth.paper.library.common.service.TBTaskService;
import com.qmth.paper.library.common.util.Result;
import com.qmth.paper.library.common.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

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

/**
 * 异步下载试卷
 */
@Service
public class AsyncDownloadPaperService extends AsyncExportTaskTemplate {
    private static final Logger log = LoggerFactory.getLogger(AsyncDownloadPaperService.class);

    static final String OBJ_TITLE = "zip数据";

    /**
     * 下载pdf
     */
    @Override
    public Result exportTask(Map<String, Object> map) {
        TBTask tbTask = (TBTask) map.get(SystemConstant.TASK);
        StringJoiner stringJoinerSummary = new StringJoiner("\n").add(MessageFormat.format("{0}{1}{2}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), BEGIN_TITLE, OBJ_TITLE));
        tbTask.setStatus(TaskStatusEnum.RUNNING);
        TBTaskService tbTaskService = SpringContextHolder.getBean(TBTaskService.class);
        tbTaskService.updateById(tbTask);
        try {
            TaskLogicService taskLogicService = SpringContextHolder.getBean(TaskLogicService.class);
            taskLogicService.executeDownloadPaperLogic(map);
            stringJoinerSummary.add(MessageFormat.format("{0}{1}{2}{3}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), FINISH_TITLE, map.get("size"), FINISH_SIZE));
            tbTask.setResult(TaskResultEnum.SUCCESS);
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            stringJoinerSummary.add(MessageFormat.format("{0}{1}{2}{3}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), EXCEPTION_TITLE, EXCEPTION_DATA, e.getMessage()));
            tbTask.setResult(TaskResultEnum.ERROR);
            if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        } finally {
            //生成txt文件
            tbTask.setSummary(stringJoinerSummary.toString());
            tbTask.setStatus(TaskStatusEnum.FINISH);
            tbTaskService.updateById(tbTask);
        }
        return ResultUtil.ok(map);
    }
}
