package com.qmth.themis.task.quartz;

import cn.hutool.core.date.DateUtil;
import com.qmth.themis.business.bean.admin.ExamListBean;
import com.qmth.themis.business.cache.bean.ExamActivityCacheBean;
import com.qmth.themis.business.cache.bean.ExamCacheBean;
import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.entity.TBOrg;
import com.qmth.themis.business.service.*;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description: 考试统计
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2023/10/27
 */
@Component
public class ExamSummaryJob extends QuartzJobBean {
    private final static Logger log = LoggerFactory.getLogger(ExamSummaryJob.class);

    @Resource
    ThemisCacheService themisCacheService;

    @Resource
    TEExamSummaryService teExamSummaryService;

    @Resource
    TEExamService teExamService;

    @Resource
    TEExamActivityService teExamActivityService;

    @Resource
    TEOrgSummaryService teOrgSummaryService;

    @Resource
    TERegionSummaryService teRegionSummaryService;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info("ExamSummaryJob进来了,context:{}", context);
        Map<String, List<ExamListBean>> examListMap = themisCacheService.getCurrentExamListCache();
        //获取当天考试列表
        if (!CollectionUtils.isEmpty(examListMap)) {
            LinkedMultiValueMap<Long, Long> orgExamIdMap = new LinkedMultiValueMap<>();//机构/考试批次id列表map
            for (Map.Entry<String, List<ExamListBean>> entry : examListMap.entrySet()) {
                Long examId = Long.parseLong(entry.getKey());
                ExamCacheBean examCacheBean = teExamService.getExamCacheBean(examId);
                //不在考试时间范围内或者禁用，则删除当前考试批次id，更新缓存
                if (examCacheBean.getEndTime().longValue() <= System.currentTimeMillis()) {
                    themisCacheService.removeCurrentExamListCache(entry.getKey());
                    continue;
                }
                TBOrg tbOrg = themisCacheService.addOrgCache(examCacheBean.getOrgId());
                orgExamIdMap.add(tbOrg.getId(), examId);

                List<ExamListBean> examListBeanList = themisCacheService.getCurrentExamListCache(entry.getKey());
                if (!CollectionUtils.isEmpty(examListBeanList)) {
                    for (ExamListBean e : examListBeanList) {
                        Set<String> roomCodeSet = new HashSet<>(Arrays.asList(e.getRoomCode().split(", ")));
                        //换算开始时间和结束时间
                        ExamActivityCacheBean ac = teExamActivityService.getExamActivityCacheBean(e.getExamActivityId());
                        Long startTime = ac.getStartTime() - (ac.getPrepareSeconds() * 1000);
                        Long endTime = ac.getFinishTime() + SystemConstant.FINISH_DELAY_TIME;
                        long timestamp = System.currentTimeMillis();
                        //当考试场次开始时间和场次结束时间在范围内，则统计
                        log.info("examSummaryJob examId:{},examActivityId:{},startTime:{},endTime:{}", examId, e.getExamActivityId(), DateUtil.format(new Date(startTime), "yyyy-MM-dd HH:mm:ss"), DateUtil.format(new Date(endTime), "yyyy-MM-dd HH:mm:ss"));
                        if (startTime <= timestamp && endTime >= timestamp) {
                            log.info("examSummaryJob examId:{},examActivityId:{},roomCodeSet:{} 开始统计", examId, e.getExamActivityId(), roomCodeSet);
                            boolean change = teExamSummaryService.examSummary(examId, e.getExamActivityId(), roomCodeSet, false);
                            if (change) {
                                teRegionSummaryService.regionSummary(examId, e.getExamActivityId());
                                //统计机构信息
                                if (orgExamIdMap.size() > 0) {
                                    List<Long> examIdAll = new ArrayList<>();
                                    orgExamIdMap.forEach((k, v) -> {
                                        teOrgSummaryService.orgSummary(k, v);
                                        examIdAll.addAll(v);
                                    });
                                    teOrgSummaryService.orgSummary(0L, examIdAll);
                                }
                            }
                        } else if (endTime <= timestamp) {//超过考试结束时间则删除考试场次缓存
                            themisCacheService.removeCurrentExamListCache(entry.getKey(), e.getExamActivityId());
                        }
                    }
                } else {
                    themisCacheService.removeCurrentExamListCache(entry.getKey());
                }
            }
        }
    }
}
