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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.themis.business.bean.admin.OrgSummaryBean;
import com.qmth.themis.business.cache.bean.ExamCacheBean;
import com.qmth.themis.business.dao.TEOrgSummaryMapper;
import com.qmth.themis.business.entity.TBOrg;
import com.qmth.themis.business.entity.TEExam;
import com.qmth.themis.business.entity.TEExamSummary;
import com.qmth.themis.business.entity.TEOrgSummary;
import com.qmth.themis.business.service.TEExamService;
import com.qmth.themis.business.service.TEOrgSummaryService;
import com.qmth.themis.business.service.ThemisCacheService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 超管统计表 服务实现类
 * </p>
 *
 * @author wangliang
 * @since 2023-10-27
 */
@Service
public class TEOrgSummaryServiceImpl extends ServiceImpl<TEOrgSummaryMapper, TEOrgSummary> implements TEOrgSummaryService {

    @Resource
    ThemisCacheService themisCacheService;

    @Resource
    TEExamService teExamService;

    @Resource
    TEOrgSummaryService teOrgSummaryService;

    /**
     * 保存机构统计信息公用
     *
     * @param orgId
     * @param examIdSet
     */
    @Override
    public void orgSummary(Long orgId, List<Long> examIdSet) {
        if (orgId.longValue() == 0) {//全局机构
            OrgSummaryBean orgSummaryBean = this.baseMapper.orgSummary(orgId, examIdSet, false);
            this.updateOrgSummary(orgId, orgSummaryBean.getOnlineCount(), orgSummaryBean.getExamCount());
        } else {
            LinkedMultiValueMap<Long, Long> orgExamIdMap = new LinkedMultiValueMap<>();
            boolean reloadDb = false;
            //先查询考试批次统计缓存
            for (Long l : examIdSet) {
                List<TEExamSummary> teExamSummaryList = themisCacheService.getExamSummaryCache(l);
                if (!CollectionUtils.isEmpty(teExamSummaryList)) {//如果没有该批次的考试统计缓存信息，则自己从数据库取
                    ExamCacheBean examCacheBean = teExamService.getExamCacheBean(l);
                    TBOrg tbOrg = themisCacheService.addOrgCache(examCacheBean.getOrgId());
                    orgExamIdMap.add(tbOrg.getId(), l);
                } else {
                    reloadDb = true;
                    break;
                }
            }
            if (reloadDb) {//没有该批次的考试统计缓存信息，则从数据库取数据
                OrgSummaryBean orgSummaryBean = this.baseMapper.orgSummary(orgId, examIdSet, false);
                this.updateOrgSummary(orgId, orgSummaryBean.getOnlineCount(), orgSummaryBean.getExamCount());
            } else {
                orgExamIdMap.forEach((k, v) -> {//从考试批次缓存信息里拿取在线人数、考试人数、完成考生数
                    Integer onlineCount = 0, examCount = 0;
                    for (Long l : v) {
                        List<TEExamSummary> teExamSummaryList = themisCacheService.getExamSummaryCache(l);
                        for (TEExamSummary t : teExamSummaryList) {
                            onlineCount = onlineCount + t.getOnlineCount();
                            examCount = examCount + t.getExamCount();
                        }
                    }
                    this.updateOrgSummary(orgId, onlineCount, examCount);
                });
            }
        }
        themisCacheService.updateOrgSummaryCache(orgId);
    }

    /**
     * 根据机构id统计信息
     *
     * @param orgId
     */
    @Override
    public void orgSummary(Long orgId) {
        List<Long> examIdSet = null;
        if (orgId.longValue() != 0) {//全局机构
            List<TEExam> teExamList = teExamService.list(new QueryWrapper<TEExam>().lambda().eq(TEExam::getOrgId, orgId));
            if (!CollectionUtils.isEmpty(teExamList)) {
                examIdSet = teExamList.stream().map(s -> s.getId()).collect(Collectors.toList());
            } else {
                examIdSet = Arrays.asList(-1L);
            }
        }
        OrgSummaryBean orgSummaryBean = this.baseMapper.orgSummary(orgId, examIdSet, true);
        Integer finishStudentCount = this.baseMapper.orgSummaryByFinishStudentCount(orgId, examIdSet);
        orgSummaryBean.setFinishStudentCount(finishStudentCount);
        TEOrgSummary teOrgSummary = new TEOrgSummary(orgId, orgSummaryBean);
        teOrgSummaryService.save(teOrgSummary);
        themisCacheService.updateOrgSummaryCache(orgId);
    }

    /**
     * 更新全局机构考试完成数量和考生完成数量
     *
     * @param orgId
     * @param finishStudentCount
     */
    @Override
    @Transactional
    public void updateOrgZeroSummary(Long orgId, Integer finishStudentCount) {
        this.baseMapper.updateOrgZeroSummary(orgId, finishStudentCount);
    }

    /**
     * 根据机构id更新在线和考试人数
     *
     * @param orgId
     * @param onlineCount
     * @param examCount
     */
    @Override
    public void updateOrgSummary(Long orgId, Integer onlineCount, Integer examCount) {
        UpdateWrapper<TEOrgSummary> teOrgSummaryUpdateWrapper = new UpdateWrapper<>();
        teOrgSummaryUpdateWrapper.lambda().set(TEOrgSummary::getOnlineCount, onlineCount)
                .set(TEOrgSummary::getExamCount, examCount)
                .eq(TEOrgSummary::getOrgId, orgId);
        teOrgSummaryService.update(teOrgSummaryUpdateWrapper);
    }
}