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.entity.TBSyncTask;
import com.qmth.distributed.print.business.entity.TSyncExamLog;
import com.qmth.distributed.print.business.service.TBSyncTaskService;
import com.qmth.distributed.print.business.service.TSyncExamLogService;
import com.qmth.distributed.print.business.templete.push.AsyncPushTaskTemplate;
import com.qmth.distributed.print.business.templete.service.PushLogicService;
import com.qmth.teachcloud.common.contant.SpringContextHolder;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.enums.TaskResultEnum;
import com.qmth.teachcloud.common.enums.TaskStatusEnum;
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.text.MessageFormat;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;

/**
 * @Description: 成绩查询推送模板
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2021/11/2
 */
@Service
public class AsyncScorePushService extends AsyncPushTaskTemplate {

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

    public static final String OBJ_TITLE = "成绩信息";

    @Override
    public Result pushTask(TSyncExamLog tSyncExamLog) {
        StringJoiner stringJoinerSummary = new StringJoiner("\n")
                .add(MessageFormat.format("{0}{1}{2}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), BEGIN_TITLE, OBJ_TITLE));
        tSyncExamLog.setStatus(TaskStatusEnum.RUNNING);
        tSyncExamLog.setStartTime(System.currentTimeMillis());
        TSyncExamLogService tSyncExamLogService = SpringContextHolder.getBean(TSyncExamLogService.class);
        tSyncExamLogService.updateById(tSyncExamLog);
        try {
            PushLogicService pushLogicService = SpringContextHolder.getBean(PushLogicService.class);
            Map<String, Object> result = pushLogicService.executeScorePushLogic(tSyncExamLog);
            // 总考生数
            Integer count = Integer.parseInt(String.valueOf(result.get("count")));
            tSyncExamLog.setTotalStudents(count);

            // 成功考生数
            Integer correct = Integer.parseInt(String.valueOf(result.get("correct")));
            tSyncExamLog.setSuccessStudents(correct);
            // 失败考生数
            if(result.containsKey("errorCount")){
                Integer errorCount = Integer.parseInt(String.valueOf(result.get("errorCount")));
                tSyncExamLog.setFailStudents(errorCount);
            } else {
                tSyncExamLog.setFailStudents(0);
            }

            // 总课程数
            Integer courses = Integer.parseInt(String.valueOf(result.get("courses")));
            tSyncExamLog.setTotalCourses(courses);

            stringJoinerSummary.add(MessageFormat.format("{0}{1}{2}{3}{4}{5}{6}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), FINISH_TITLE, count, SUCCESS_TITLE, Integer.parseInt(String.valueOf(result.get("correct"))), FINISH_SIZE, Objects.nonNull(result.get("error")) ? (String) result.get("error") : ""));
            tSyncExamLog.setEndTime(System.currentTimeMillis());
            tSyncExamLog.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()));
            tSyncExamLog.setEndTime(System.currentTimeMillis());
            tSyncExamLog.setResult(TaskResultEnum.ERROR);
            if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        } finally {//生成txt文件
            tSyncExamLog.setSummary(stringJoinerSummary.toString());
            super.createTxt(tSyncExamLog);
        }
        return ResultUtil.ok(tSyncExamLog);
    }
}
