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.service.ExamTaskService;
import com.qmth.distributed.print.business.templete.importData.AsyncImportTaskTemplete;
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.SysUser;
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 javax.annotation.Resource;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.*;

/**
 * @Description: 考务数据导入模板
 * @Author: CaoZixuan
 * @Date: 2021-04-07
 */
@Service
public class AsyncExaminationImportTemplateService extends AsyncImportTaskTemplete {
    @Resource
    private ExamTaskService examTaskService;

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

    public static final String OBJ_TITLE = "考务数据";

    @Override
    public Result importTask(Map<String, Object> map) throws Exception {
        TBTask tbTask = (TBTask) map.get(SystemConstant.TASK);
        InputStream inputStream = super.getUploadFileInputStream(tbTask);
        map.put("inputStream", inputStream);

        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);

            // 执行导入考务数据
            Map<String, Object> result = taskLogicService.executeImportExaminationLogic(map);

            // 检测是否去生成pdf
            if (Objects.isNull(map.get("examDetailIdList"))) {
                throw ExceptionResultEnum.ERROR.exception("不能获取考务-场次id集合");
            }
            List<Long> examDetailIdList = (List<Long>) map.get("examDetailIdList");
            // 按照考场检验命题任务是否全部完成，完成生成pdf
            SysUser user = (SysUser) map.get(SystemConstant.USER);
            for (Long examDetailId : examDetailIdList) {
                examTaskService.checkDataByExamination(examDetailId, user);
            }

            stringJoinerSummary.add(MessageFormat.format("{0}{1}{2}{3}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), FINISH_TITLE, Long.valueOf(String.valueOf(result.get("dataCount"))), 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());
            super.createTxt(tbTask);
        }
        return ResultUtil.ok(map);
    }
}
