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

import cn.hutool.core.date.DateUtil;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.distributed.print.business.templete.callback.CallbackCreatePdf;
import com.qmth.distributed.print.business.templete.create.AsyncCreateTaskTemplete;
import com.qmth.distributed.print.business.templete.service.TaskLogicService;
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.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.TaskResultEnum;
import com.qmth.teachcloud.common.enums.TaskStatusEnum;
import com.qmth.teachcloud.common.service.TBTaskService;
import com.qmth.teachcloud.common.util.Result;
import com.qmth.teachcloud.common.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.*;

/**
 * @Description: 创建pdf模版
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2021/4/9
 */
@Service
public class AsyncCreatePdfTempleteService extends AsyncCreateTaskTemplete {
    private final static Logger log = LoggerFactory.getLogger(AsyncCreatePdfTempleteService.class);

    static final String OBJ_TITLE = "pdf数据";

    /**
     * 创建pdf
     *
     * @param map
     * @param callbackCreatePdf
     * @return
     * @throws IOException
     */
    @Override
    public Result createPdf(Map<String, Object> map, CallbackCreatePdf callbackCreatePdf) throws IOException {
        TBTask tbTask = (TBTask) map.get(SystemConstant.TASK);
        Boolean manual = (Boolean) map.get(SystemConstant.MANUAL);
        StringJoiner stringJoinerSummary = new StringJoiner("\n").add(MessageFormat.format("{0}{1}{2}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), BEGIN_TITLE, OBJ_TITLE));
        TBTaskService tbTaskService = SpringContextHolder.getBean(TBTaskService.class);
        TBTask dbTask = tbTaskService.getById(tbTask.getId());
        if (Objects.isNull(manual) && (Objects.nonNull(dbTask) && dbTask.getStatus() == TaskStatusEnum.FINISH && Objects.nonNull(dbTask.getResult()))) {//无需重新生成pdf
            return ResultUtil.ok();
        }
        tbTask.setStatus(TaskStatusEnum.RUNNING);
        tbTaskService.updateById(tbTask);
        try {
            TaskLogicService taskLogicService = SpringContextHolder.getBean(TaskLogicService.class);
            taskLogicService.createPdfPrepose(map);
            taskLogicService.executeCreatePdfLogic(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);
//            TBTask dbTask = tbTaskService.getById(tbTask.getId());
//            if (tbTask.getVersion() == dbTask.getVersion()) {
//                tbTask.setResetCount(new AtomicInteger(tbTask.getResetCount()).incrementAndGet());
//            }
            if (e instanceof ApiException) {
                if (((ApiException) e).getCode() == ExceptionResultEnum.PAPER_ERROR.getCode()
                        || ((ApiException) e).getCode() == ExceptionResultEnum.PAPER_TYPE_ERROR.getCode()
                        || ((ApiException) e).getCode() == ExceptionResultEnum.ATTACHMENT_IS_NULL.getCode()
                        || ((ApiException) e).getCode() == ExceptionResultEnum.EXAM_PRINT_IS_NULL.getCode()
                        || ((ApiException) e).getCode() == ExceptionResultEnum.EXAM_RULE_IS_NULL.getCode()
                        || ((ApiException) e).getCode() == ExceptionResultEnum.EXAM_DETAIL_IS_NULL.getCode()
                        || ((ApiException) e).getCode() == ExceptionResultEnum.EXAM_CARD_IS_NULL.getCode()
                        || ((ApiException) e).getCode() == ExceptionResultEnum.EXAM_TASK_IS_NULL.getCode()) {
                    tbTask.setErrorMessage(e.getMessage());
                }
                ResultUtil.error((ApiException) e, e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        } finally {//生成txt文件
            tbTask.setSummary(stringJoinerSummary.toString());
            super.createTxt(tbTask);
            if (Objects.nonNull(callbackCreatePdf)) {
                callbackCreatePdf.callback(map);
            }
        }
        return ResultUtil.ok(map);
    }

    @Override
    public Result importTask(Map<String, Object> map) throws IOException {
        return null;
    }
}
