package com.qmth.distributed.print.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.distributed.print.business.entity.TSyncExamLog;
import com.qmth.distributed.print.business.entity.TSyncStmmsExam;
import com.qmth.distributed.print.business.mapper.TSyncExamLogMapper;
import com.qmth.distributed.print.business.service.TSyncExamLogService;
import com.qmth.distributed.print.business.service.TSyncStmmsExamService;
import com.qmth.distributed.print.business.templete.execute.AsyncScorePushService;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.TaskStatusEnum;
import com.qmth.teachcloud.common.service.TeachcloudCommonService;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

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

@Service
public class TSyncExamLogServiceImpl extends ServiceImpl<TSyncExamLogMapper, TSyncExamLog> implements TSyncExamLogService {

    @Resource
    AsyncScorePushService asyncScorePushService;

    @Resource
    private TSyncStmmsExamService tSyncStmmsExamService;

    @Resource
    private TeachcloudCommonService teachcloudCommonService;

    @Override
    public IPage<TSyncExamLog> list(Page<TSyncExamLog> iPage, Long semesterId, Long examId) {
        if (semesterId == null) {
            throw ExceptionResultEnum.ERROR.exception("请选择学期");
        }
        if (examId == null) {
            throw ExceptionResultEnum.ERROR.exception("请选择考试");
        }

        Long schoolId = Long.parseLong(ServletUtil.getRequestHeaderSchoolId().toString());
        IPage<TSyncExamLog> examLogResultIPage = this.baseMapper.list(iPage, semesterId, examId);
        for (TSyncExamLog record : examLogResultIPage.getRecords()) {
            TSyncExamLog tSyncExamLog = this.selectBySchoolIdAndSemesterIdAndExamId(schoolId, semesterId, examId, record.getThirdRelateId());
            if (tSyncExamLog == null) {
                TSyncStmmsExam tSyncStmmsExam = tSyncStmmsExamService.getBySchoolIdAndExamId(schoolId, null, examId);
                if (tSyncStmmsExam != null) {
                    record.setExamName(tSyncStmmsExam.getExamName());
                }
            } else {
                BeanUtils.copyProperties(tSyncExamLog, record);
            }
            // 拼接错误日志访问url
            if (StringUtils.isNotBlank(record.getErrorFilePath())) {
                record.setErrorFileUrl(teachcloudCommonService.filePreview(record.getErrorFilePath()));
            }
        }
        return examLogResultIPage;
    }

    @Override
    public void syncStudentScore(Long semesterId, Long examId, Long thirdRelateId) {
        if (semesterId == null) {
            throw ExceptionResultEnum.ERROR.exception("请选择学期");
        }
        if (examId == null) {
            throw ExceptionResultEnum.ERROR.exception("请选择考试");
        }

        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();

        // 校验任务是否进行中
        QueryWrapper<TSyncExamLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TSyncExamLog::getSemesterId, semesterId)
                .eq(TSyncExamLog::getExamId, examId)
                .eq(TSyncExamLog::getThirdRelateId, thirdRelateId);
        List<TSyncExamLog> tSyncExamLogList = this.list(queryWrapper);
        if (!tSyncExamLogList.isEmpty()) {
            List<TSyncExamLog> notFinishTsyncExamLogList = tSyncExamLogList.stream().filter(m -> !TaskStatusEnum.FINISH.equals(m.getStatus())).collect(Collectors.toList());
            if (!notFinishTsyncExamLogList.isEmpty()) {
                throw ExceptionResultEnum.ERROR.exception("当前考试有同步任务未结束，请稍候再试");
            }

            // 刪除历史数据
            List<TSyncExamLog> finishTsyncExamLogList = tSyncExamLogList.stream().filter(m -> TaskStatusEnum.FINISH.equals(m.getStatus())).collect(Collectors.toList());
            if (!finishTsyncExamLogList.isEmpty()) {
                UpdateWrapper<TSyncExamLog> updateWrapper = new UpdateWrapper<>();
                updateWrapper.lambda().eq(TSyncExamLog::getSchoolId, sysUser.getSchoolId())
                        .eq(TSyncExamLog::getSemesterId, semesterId)
                        .eq(TSyncExamLog::getExamId, examId)
                        .eq(TSyncExamLog::getThirdRelateId, thirdRelateId);
                this.remove(updateWrapper);
            }
        }

        TSyncStmmsExam tSyncStmmsExam = tSyncStmmsExamService.getBySchoolIdAndExamId(sysUser.getSchoolId(), null, thirdRelateId);
        String examName = tSyncStmmsExam == null ? null : tSyncStmmsExam.getExamName();
        TSyncExamLog tSyncExamLog = new TSyncExamLog(sysUser.getSchoolId(), semesterId, examId, thirdRelateId, examName, TaskStatusEnum.INIT, sysUser.getId(), System.currentTimeMillis());
        boolean isSave = this.save(tSyncExamLog);
        if (!isSave) {
            throw ExceptionResultEnum.ERROR.exception("创建同步任务失败，请联系管理员");
        }
        asyncScorePushService.pushTask(tSyncExamLog);
    }

    @Override
    public TSyncExamLog selectBySchoolIdAndSemesterIdAndExamId(Long schoolId, Long semesterId, Long examId, Long thirdRleateId) {
        QueryWrapper<TSyncExamLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TSyncExamLog::getSchoolId, schoolId)
                .eq(TSyncExamLog::getSemesterId, semesterId)
                .eq(TSyncExamLog::getExamId, examId)
                .eq(TSyncExamLog::getThirdRelateId, thirdRleateId);
        return this.getOne(queryWrapper);
    }
}
