package com.xhkjedu.sexam.service.paperstudent;

import com.xhkjedu.sexam.mapper.exam.EBaseMapper;
import com.xhkjedu.sexam.mapper.exam.EClassMapper;
import com.xhkjedu.sexam.mapper.exam.EClassStudentMapper;
import com.xhkjedu.sexam.mapper.paper.EPaperQtypeQuestionMapper;
import com.xhkjedu.sexam.mapper.paperstudent.EPaperStudentMapper;
import com.xhkjedu.sexam.mapper.paperstudent.EPaperStudentQuestionMapper;
import com.xhkjedu.sexam.mapper.paperstudent.EPsqbatchDetailMapper;
import com.xhkjedu.sexam.mapper.paperstudent.EPsqbatchMapper;
import com.xhkjedu.sexam.model.paperstudent.EPaperStudentQuestion;
import com.xhkjedu.sexam.model.paperstudent.EPsqbatch;
import com.xhkjedu.sexam.model.paperstudent.EPsqbatchDetail;
import com.xhkjedu.sexam.utils.PoiUtils;
import com.xhkjedu.sexam.vo.paperstudent.EPsqbatchStuVo;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @Description 学生试卷信息
 * @Author ywx
 * Date 2022/11/21 14:12
 **/
@Service
@Slf4j
public class EPsqbatchService {
    @Resource
    private EPsqbatchMapper ePsqbatchMapper;
    @Resource
    private EPaperQtypeQuestionMapper ePaperQtypeQuestionMapper;
    @Resource
    private EClassStudentMapper eClassStudentMapper;
    @Resource
    private EPaperStudentQuestionMapper ePaperStudentQuestionMapper;
    @Resource
    private EPaperStudentMapper ePaperStudentMapper;
    @Resource
    private EBaseMapper eBaseMapper;
    @Resource
    private EPsqbatchDetailMapper ePsqbatchDetailMapper;
    @Resource
    private EClassMapper eClassMapper;

    /**
     * @Description 获取考试科目
     * @Param [exmaid]
     * @Return java.util.List<java.util.Map>
     * @Author wn
     * @Date 2022/11/21 14:37
     **/
    public List<Map> listSubjectsByExamid(Integer exmaid){
        return ePsqbatchMapper.listSubjectsByExamid(exmaid);
    }

    //考试基本信息
    public Map getExamInfo(Integer examid){
        return eBaseMapper.findById(examid);
    }

    /**
     * @Description 考试补录成绩批次信息
     * @Param [exmaid]
     * @Return java.util.List<java.util.Map>
     * @Author wn
     * @Date 2022/11/21 14:49
     **/
    public List<Map> listPsqBatchsByExamid(Integer exmaid){
        return ePsqbatchMapper.listPsqBatchsByExamid(exmaid);
    }

    /*
     * 补录成绩导入
     * @Param [file, batch]
     * @Author ywx
     * @Date 2022/11/21 15:14
     * @return com.xhkjedu.vo.ResultVo
     **/
    public ResultVo importRecord(MultipartFile file, EPsqbatch batch) {
        Integer epid = batch.getEpid();
        Integer examid = batch.getExamid();
        try {
            List<Map> students = eClassStudentMapper.listStuByExamId(examid);//考试学生列表
            List<Map> qns = ePaperQtypeQuestionMapper.listQnByEpid(epid);
            List<Map> classes = eClassMapper.listByExamId(examid);
            Map<String, Object> map = PoiUtils.readExcelRecord(file, qns, students, classes);
            Integer code = (Integer) map.get("code");
            if (code != 0) return new ResultVo(1, map.get("msg").toString());
            LinkedHashMap<Integer, List<String>> errMsg = (LinkedHashMap<Integer, List<String>>) map.get("errMsg");
            if (errMsg.size() != 0) return new ResultVo(1, null, errMsg);
            List<EPsqbatchStuVo> stus = (List<EPsqbatchStuVo>) map.get("stus");
            batch.setStunum(stus.size());
            batch.setCreatetime(N_Utils.getSecondTimestamp());
            ePsqbatchMapper.insertUseGeneratedKeys(batch);
            for (EPsqbatchStuVo stu : stus) {
                saveEPsqbatchDetail(stu, batch);
            }
        } catch (Exception e) {
            log.error("导入补录学生成绩失败",e);
            return new ResultVo(1,e.getMessage());
        }
        return new ResultVo(0,"导入成功");
    }

    //补录学生成绩
    @Transactional(rollbackFor = Exception.class)
    @Async("asyncPoolTaskExecutor")
    public void saveEPsqbatchDetail(EPsqbatchStuVo stu, EPsqbatch batch) {
        try {
            int timestamp = N_Utils.getSecondTimestamp();
            Integer batchId = batch.getId();
            Integer teacherid = batch.getTeacherid();
            Integer epid = batch.getEpid();
            Integer studentid = stu.getStudentid();
            List<EPsqbatchDetail> details = stu.getDetails();
            //获取试卷中所有试题
            List<Integer> eptqids = details.stream().map(d -> d.getEptqid()).collect(Collectors.toList());
            List<EPaperStudentQuestion> questions = ePaperStudentQuestionMapper.listQuestionByStu(studentid, eptqids);
            for (int i = 0; i < details.size(); i++) {
                EPsqbatchDetail detail = details.get(i);
                EPaperStudentQuestion question = questions.get(i);
                detail.setStuscore(question.getStuscore());
                question.setStuscore(detail.getNewscore());
                detail.setBatchid(batchId);
                detail.setStudentid(studentid);
                detail.setEpid(epid);
                detail.setEpsqid(question.getEpsqid());
                detail.setQn(question.getQn());
                detail.setTeacherid(teacherid);
                detail.setCreatetime(timestamp);
            }
            ePsqbatchDetailMapper.insertList(details);//保存考试补录成绩详情
            ePaperStudentQuestionMapper.updateBatchStuQuestionSore(questions);//更改单个学生试题分值
            Integer epsid = questions.get(0).getEpsid();
            ePaperStudentMapper.updateStuScoreAndStateEpsid(epsid);//更改单个学生试卷分值和状态
        } catch (Exception e) {
            log.error("补录学生成绩失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException("补录学生成绩失败");
        }
    }

    /**
     * @Description 补录成绩批次详情
     * @Param [ePsqbatchDetail]
     * @Return java.util.List<java.util.Map>
     * @Author wn
     * @Date 2022/11/21 15:29
     **/
    public List<Map> listPsqBatchDetail(EPsqbatchDetail ePsqbatchDetail){
        return ePsqbatchMapper.listPsqBatchDetail(ePsqbatchDetail);
    }
}
