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

import cn.hutool.core.date.DateUtil;
import com.qmth.distributed.print.business.templete.importData.SyncImportTaskTemplate;
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.springframework.stereotype.Service;

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

/**
 * @Description: 试卷主观题结构导入同步任务
 * @Author: CaoZixuan
 * @Date: 2024/04/09
 */
@Service
public class SyncSubjectiveStructImportService extends SyncImportTaskTemplate {

    public static final String OBJ_TITLE = "主观题结构导入";

    @Override
    public Result importTask(Map<String, Object> map) throws Exception {
        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 (InputStream inputStream = super.getUploadFileInputStream(tbTask)) {
            map.put("inputStream", inputStream);
            TaskLogicService taskLogicService = SpringContextHolder.getBean(TaskLogicService.class);
            // 执行导入考务数据
            taskLogicService.executeImportSubjectiveStructLogic(map);
            tbTask.setResult(TaskResultEnum.SUCCESS);
            stringJoinerSummary.add("导入主观题结构成功");
        } catch (Exception e) {
            // 导入异常错误信息写入summary
            stringJoinerSummary.add("导入主观题结构失败," + EXCEPTION_DATA + System.lineSeparator() + e.getMessage());
            tbTask.setResult(TaskResultEnum.ERROR);
            throw ExceptionResultEnum.ERROR.exception("导入主观题结构失败,请通过'导入结果查询'查看错误原因");
        } finally {//生成文件
            tbTask.setSummary(stringJoinerSummary.toString());
            tbTask.setStatus(TaskStatusEnum.FINISH);
            tbTaskService.updateById(tbTask);
        }
        return ResultUtil.ok();
    }
}
