package com.xhkjedu.sexam.service.paper;

import com.xhkjedu.sexam.mapper.exam.EClassMapper;
import com.xhkjedu.sexam.mapper.paper.EPaperCorrectclassMapper;
import com.xhkjedu.sexam.mapper.paper.EPaperCorrectquestionMapper;
import com.xhkjedu.sexam.mapper.paper.EPaperMapper;
import com.xhkjedu.sexam.model.paper.EPaperCorrectclass;
import com.xhkjedu.utils.N_Utils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class EPaperCorrectclassService {
    @Resource
    private EPaperCorrectclassMapper ePaperCorrectclassMapper;
    @Resource
    private EClassMapper eClassMapper;
    @Resource
    private EPaperMapper ePaperMapper;
    @Resource
    private EPaperCorrectquestionMapper ePaperCorrectquestionMapper;

    //设置批阅人
    @Transactional(rollbackFor = Exception.class)
    public void setTeacher(Integer epid, Integer createid, List<EPaperCorrectclass> teachers) {
        ePaperCorrectclassMapper.delByEpId(epid);//删除批阅人
        ePaperCorrectquestionMapper.delByEpId(epid);//删除批阅人
        int timestamp = N_Utils.getSecondTimestamp();
        teachers.forEach(t -> {
            t.setEpid(epid);
            t.setCreateid(createid);
            t.setCreatetime(timestamp);
        });
        ePaperCorrectclassMapper.insertList(teachers);//添加批阅人
        ePaperMapper.updateCorrectType(epid, 1);//修改批阅设置
    }

    //查看批阅人
    public List<Map> listByEpId(Integer epid) {
        Integer examId = ePaperMapper.getExamIdByEpId(epid);
        List<Map> list = eClassMapper.listByExamId(examId);//考试班级
        List<Map> users = ePaperCorrectclassMapper.listByEpId(epid);//试卷批阅人
        for (Map map : list) {
            List<Map> teachers = users.stream().filter(u -> u.get("classid").equals(map.get("classid"))).collect(Collectors.toList());
            map.put("teachers", teachers);
        }
        return list;
    }

    //根据试卷id获取考试科目基本信息
    public Map getESubjectByEpId(Integer epid) {
        return ePaperMapper.getESubjectByEpId(epid);
    }

    //删除批阅人
    @Transactional(rollbackFor = Exception.class)
    public void deleteByEpId(Integer epid) {
        ePaperCorrectclassMapper.delByEpId(epid);//删除批阅人
        ePaperCorrectquestionMapper.delByEpId(epid);//删除批阅人
        ePaperMapper.updateCorrectType(epid,0);
    }
}
