package com.qmth.themis.business.templete.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qmth.themis.business.bean.cloudmark.StudentScoreParams;
import com.qmth.themis.business.cache.bean.ExamCacheBean;
import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.dao.TSyncExamStudentScoreMapper;
import com.qmth.themis.business.entity.TSyncExamStudentScore;
import com.qmth.themis.business.enums.TaskStatusEnum;
import com.qmth.themis.business.service.TEExamService;
import com.qmth.themis.business.service.TSyncExamStudentScoreService;
import com.qmth.themis.business.templete.TaskSyncCommon;
import com.qmth.themis.business.templete.TaskSyncTemplete;
import com.qmth.themis.business.util.CloudMarkUtil;
import com.qmth.themis.common.contanst.Constants;
import com.qmth.themis.common.util.Result;
import com.qmth.themis.common.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @Description: 同步云阅卷成绩任务
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/10/20
 */
@Service
public class TaskSyncCloudMarkTemplete implements TaskSyncTemplete {

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

    @Resource
    CloudMarkUtil cloudMarkUtil;

    @Resource
    TSyncExamStudentScoreService tSyncExamStudentScoreService;

    @Resource
    TSyncExamStudentScoreMapper tSyncExamStudentScoreMapper;

    @Resource
    TEExamService teExamService;

    /**
     * 同步模版
     *
     * @param map
     * @return
     */
    @Override
    public Result syncTask(Map<String, Object> map) throws IOException {
        log.info("开始同步云阅卷成绩数据");
        long start = System.currentTimeMillis();
        TaskSyncCommon taskSyncCommon = new TaskSyncCommon(map);
        taskSyncCommon.init();
        taskSyncCommon.setTxtList(new ArrayList());
        StringJoiner stringJoiner = null;
        try {
            taskSyncCommon.getTxtList().add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->开始准备同步云阅卷成绩数据");
            Long examId = (Long) map.get(SystemConstant.EXAM_ID);
            ExamCacheBean examCacheBean = teExamService.getExamCacheBean(examId);
            Long cloudMarkExamId = Long.parseLong(examCacheBean.getThirdExamId());
            taskSyncCommon.getTbTaskHistory().setEntityId(cloudMarkExamId);
            Long orgId = Long.parseLong(String.valueOf(map.get(SystemConstant.ORG_ID)));
            Long createId = (Long) map.get(SystemConstant.CREATE_ID);
            String examCode = (String) map.get(SystemConstant.EXAM_CODE);

            boolean oss = (boolean) taskSyncCommon.getOssEnv().get(SystemConstant.OSS);
            stringJoiner = new StringJoiner("");
            if (!oss) {
                stringJoiner.add(SystemConstant.FILES_DIR).add(File.separator);
            }
            stringJoiner = SystemConstant.getDirName(stringJoiner, false);
            taskSyncCommon.getTbTaskHistory().setStatus(TaskStatusEnum.RUNNING);
            taskSyncCommon.getTbTaskHistory().setSummary("正在同步数据");
            taskSyncCommon.getTxtList().add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->" + taskSyncCommon.getTbTaskHistory().getSummary());
            List<Map> finalList = cloudMarkUtil.callStudentScoreApi(new StudentScoreParams(orgId, cloudMarkExamId, examCode));
            if (!CollectionUtils.isEmpty(finalList)) {
                List<TSyncExamStudentScore> tSyncExamStudentScoreList = new ArrayList<>(finalList.size());
                for (Map student : finalList) {
                    student.put("exam_batch_id", examId);
                    student.put(SystemConstant.CREATE_ID, createId);
                    tSyncExamStudentScoreList.add(new TSyncExamStudentScore(student));
                }
                if (tSyncExamStudentScoreList.size() > 0) {
                    tSyncExamStudentScoreService.remove(new QueryWrapper<TSyncExamStudentScore>().lambda().eq(TSyncExamStudentScore::getExamBatchId, examId).eq(TSyncExamStudentScore::getExamId, cloudMarkExamId));
                    tSyncExamStudentScoreMapper.insertBatch(tSyncExamStudentScoreList);
                }

                taskSyncCommon.getTbTaskHistory().setStatus(TaskStatusEnum.FINISH);
                taskSyncCommon.getTbTaskHistory().setSummary("同步了" + finalList.size() + "条数据");
                taskSyncCommon.getTbTaskHistory().setProgress(100D);
                taskSyncCommon.getTxtList().add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->" + taskSyncCommon.getTbTaskHistory().getSummary());
            }
            long end = System.currentTimeMillis();
            log.info("同步云阅卷成绩数据结束,============耗时============:{}秒", (end - start) / 1000);
        } catch (Exception e) {
            log.error("同步云阅卷成绩数据报错", e);
            taskSyncCommon.exception(e, "数据同步时发生异常，请联系系统管理员处理！", taskSyncCommon.getTxtList());
        } finally {
            //这里写入txt文件
            taskSyncCommon.writeSyncResultTxt(stringJoiner.toString(), taskSyncCommon.getTxtList().toString());
        }
        return ResultUtil.ok(true);
    }
}