package com.yida.data.school.exam.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.entity.CurrentUser;
import com.yida.data.common.core.entity.constant.CoreAverageConstant;
import com.yida.data.common.core.entity.exam.*;
import com.yida.data.common.core.entity.user.EduTeacherDept;
import com.yida.data.school.dto.exam.FindClassExaminationDTO;
import com.yida.data.school.dto.exam.SelectClassScoreDTO;
import com.yida.data.school.exam.mapper.*;
import com.yida.data.school.exam.service.CoreExaminationTeacherService;
import com.yida.data.school.vo.exam.EduStudentExamVO;
import com.yida.data.user.feign.RemoteStaffService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@Transactional(readOnly = true)
public class CoreExaminationTeacherServiceImpl extends ServiceImpl<CoreExaminationTeacherMapper,
        CoreExaminationTeacher> implements CoreExaminationTeacherService {

    @Resource
    private CoreExaminationTeacherMapper coreExaminationTeacherMapper;

    @Resource
    private CoreExaminationTeacherDetailImpl coreExaminationTeacherDetail;

    @Resource
    private CoreExaminationMapper coreExaminationMapper;

    @Resource
    private CoreExaminationTeacherDetailMapper coreExaminationTeacherDetailMapper;

    @Resource
    private CoreExaminationCourseMapper coreExaminationCourseMapper;

    @Resource
    private CoreExaminationCoreAverageMapper coreExaminationCoreAverageMapper;

    @Resource
    private CoreExaminationStudentCourseMapper coreExaminationStudentCourseMapper;

    @Resource
    private RemoteStaffService remoteStaffService;

    @Resource
    private CoreExaminationPublishRecordMapper coreExaminationPublishRecordMapper;

    /**
     * 查询本次考试对应的监考老师列表数据
     */
    @Override
    public IPage<CoreExaminationTeacher> findExaminationTeacherPageList(Integer pageNum,Integer pageSize,Integer examId, String teachaerName) {
        return coreExaminationTeacherMapper.findExaminationTeacherPageList(new Page(pageNum,pageSize),examId, teachaerName);
    }

    @Override
    @Transactional()
    public void saveExaminationTeacher(CoreExaminationTeacher coreExaminationTeacher, CurrentUser currentUser) {


        //登录用户id
        Long userId = 1L;
        if (Optional.ofNullable(currentUser).map(o -> o.getUserId()).isPresent()) {
            userId = currentUser.getUserId();
        }


        //判断是新增还是修改
        if (coreExaminationTeacher.getId() == null) {
            coreExaminationTeacher.setUpdateId(userId);
            coreExaminationTeacherMapper.insert(coreExaminationTeacher);
        } else {
            //删除监考老师详细信息
            coreExaminationTeacherDetailMapper.delete(Wrappers.lambdaQuery(new CoreExaminationTeacherDetail()).eq(CoreExaminationTeacherDetail::getCoreExaminationTeacherId, coreExaminationTeacher.getId()));
        }
        //保存考试监考老师信息
        saveOrUpdate(coreExaminationTeacher);
        List<CoreExaminationTeacherDetail> saveList = coreExaminationTeacher.getTeacherDetailList();
        //保存对应的监考老师关联信息
        for (CoreExaminationTeacherDetail detail : saveList) {
            //监考老师主键id
            detail.setCoreExaminationTeacherId(coreExaminationTeacher.getId());
        }
        coreExaminationTeacherDetail.saveBatch(saveList);

    }

    @Override
    public CoreExaminationTeacher findExaminationTeacher(Integer examinationTeacherId) {
        CoreExaminationTeacher coreExaminationTeacher = getById(examinationTeacherId);
        if (coreExaminationTeacher != null) {
            coreExaminationTeacher.setTeacherDetailList(coreExaminationTeacherDetailMapper.selectList(Wrappers.lambdaQuery(new CoreExaminationTeacherDetail()).eq(CoreExaminationTeacherDetail::getCoreExaminationTeacherId, examinationTeacherId)));
        }
        return coreExaminationTeacher;
    }

    @Override
    @Transactional
    public void delExaminationTeacherBatch(List<Integer> examinationTeacherIds) {
        //批量删除监考老师详细信息
        coreExaminationTeacherDetailMapper.deleteByTeacherIds(examinationTeacherIds);
        //批量删除监考老师信息
        removeByIds(examinationTeacherIds);
    }


    /**
     * 手机端查询考试列表
     *
     * @param gradeId
     * @return
     */
    @Override
    public IPage<CoreExamination> findExaminationList(Page page, Long gradeId, String name, Long teacherId) {

        List<LocalDateTime> date = findDate();
        LocalDateTime star = date.get(0);
        LocalDateTime end = date.get(1);
        //更具时间和年级id
        ArrayList<Long> list = new ArrayList<>();
        if (gradeId == null) {
            List<EduTeacherDept> data = remoteStaffService.findTeacherRole(teacherId, null).getData();

            for (EduTeacherDept datum : data) {
                list.add(datum.getGradeId());
            }
        }
        if (gradeId != null) {
            list.add(gradeId);
        }

        return coreExaminationMapper.selectGradeList(page, list, star, end, name);
    }

    /**
     * 查询考试概况
     *
     * @param findClassExaminationDTO
     * @return 概况
     */
    @Override
    @Transactional
    public EduStudentExamVO findClassExamination(FindClassExaminationDTO findClassExaminationDTO) {

        LocalDateTime star = findDate().get(0);
        LocalDateTime end = findDate().get(1);
        EduStudentExamVO classExamination = new EduStudentExamVO();
        CoreExaminationCoreAverage coreExaminationCoreAverage = coreExaminationCoreAverageMapper.selectOne(Wrappers.lambdaQuery
                (new CoreExaminationCoreAverage()).eq(CoreExaminationCoreAverage::getTeacherId, findClassExaminationDTO.getTeacherId())
                .eq(CoreExaminationCoreAverage::getCoreExaminationId, findClassExaminationDTO.getExamId()));
        if (ObjectUtil.isEmpty(coreExaminationCoreAverage)) {
            CoreExaminationCoreAverage coreExaminationCoreAverage1 = new CoreExaminationCoreAverage();
            coreExaminationCoreAverage1.setTeacherId(findClassExaminationDTO.getTeacherId());
            coreExaminationCoreAverage1.setCoreExaminationId(findClassExaminationDTO.getExamId());
            coreExaminationCoreAverage1.setGreat(CoreAverageConstant.AVERAGE_GREAT);
            coreExaminationCoreAverage1.setGood(CoreAverageConstant.AVERAGE_GOOD);
            coreExaminationCoreAverage1.setPass(CoreAverageConstant.AVERAGE_PASS);
            coreExaminationCoreAverage1.setPoor(CoreAverageConstant.AVERAGE_POOR);
            coreExaminationCoreAverageMapper.insert(coreExaminationCoreAverage1);
             coreExaminationCoreAverage = new CoreExaminationCoreAverage();
            BeanUtils.copyProperties(coreExaminationCoreAverage1, coreExaminationCoreAverage);
        }
        if (ObjectUtil.isNotEmpty(findClassExaminationDTO.getCourseId())) {
            //查询单科
            classExamination = coreExaminationMapper.findOneClassExamination(findClassExaminationDTO.getExamId(), findClassExaminationDTO.getCourseId(),
                    findClassExaminationDTO.getClassId(), star, end);
            CoreExaminationCoreAverage coreExaminationCoreAverage1 = new CoreExaminationCoreAverage();
            coreExaminationCoreAverage1 = coreExaminationMapper.findOneScoringRate(findClassExaminationDTO.getExamId(), coreExaminationCoreAverage.getGreat(),
                    coreExaminationCoreAverage.getGood(), coreExaminationCoreAverage.getPass(), coreExaminationCoreAverage.getPoor(), findClassExaminationDTO.getCourseId());
            classExamination.setAverage(coreExaminationCoreAverage1);
            if (ObjectUtil.isEmpty(classExamination)) {
                EduStudentExamVO classExamination1 = new EduStudentExamVO();
                classExamination1.setAverage(coreExaminationCoreAverage1);
                return classExamination1;
            }
            classExamination.setAverage(coreExaminationCoreAverage1);
            return classExamination;
        } else if (ObjectUtil.isEmpty(findClassExaminationDTO.getCourseId())) {
            //全查
            classExamination = coreExaminationMapper.findClassExamination(findClassExaminationDTO.getExamId(), findClassExaminationDTO.getCourseId(),
                    findClassExaminationDTO.getClassId(), star, end);
            CoreExaminationCoreAverage coreExaminationCoreAverage1 = new CoreExaminationCoreAverage();
            coreExaminationCoreAverage1 = coreExaminationMapper.findAllScoringRate(findClassExaminationDTO.getExamId(), coreExaminationCoreAverage.getGreat(),
                    coreExaminationCoreAverage.getGood(), coreExaminationCoreAverage.getPass(), coreExaminationCoreAverage.getPoor());
            if (ObjectUtil.isEmpty(classExamination)) {
                EduStudentExamVO classExamination1 = new EduStudentExamVO();
                classExamination1.setAverage(coreExaminationCoreAverage1);
                return classExamination1;
            }
            classExamination.setAverage(coreExaminationCoreAverage1);
            return classExamination;
        }
        return classExamination;
    }


    /**
     * 查询考试科目
     *
     * @param examId
     * @return
     */
    @Override
    public List<CoreExaminationCourse> findExaminationCourseList(Long examId, Long teacherId, Long schoolId) {

        List<Long> data = remoteStaffService.findTeacherCourseId(teacherId, schoolId).getData();
        if (data.size() == 0) {
            return null;
        }
        return coreExaminationCourseMapper.selectCourseList(examId, data);
    }

    @Override
    public List<CoreExaminationStudentCourse> selectStudentScore(Long studentId, Long examId, Long courseId) {
        if (ObjectUtil.isEmpty(courseId)) {
            return coreExaminationStudentCourseMapper.selectList(Wrappers.lambdaQuery(
                    new CoreExaminationStudentCourse()).eq(CoreExaminationStudentCourse::getCoreExaminationId, examId)
                    .eq(CoreExaminationStudentCourse::getCoreExaminationStudentId, studentId));
        }
        return coreExaminationStudentCourseMapper.selectList(Wrappers.lambdaQuery(
                new CoreExaminationStudentCourse()).eq(CoreExaminationStudentCourse::getCoreExaminationId, examId)
                .eq(CoreExaminationStudentCourse::getCoreExaminationStudentId, studentId).eq(CoreExaminationStudentCourse::getCoreExaminationCourseId, courseId));
    }

    /**
     * 查询老师对应班级成绩单
     *
     * @return
     */
    @Override
    public IPage<CoreExaminationStudent> selectClassScore(SelectClassScoreDTO dto) {
        List<Long> classId = dto.getClassId();
        Long examId = dto.getExamId();
        if (dto.getCourseId() == null) {
            return coreExaminationMapper.selectClassScore(new Page(dto.getPageNum(),
                    dto.getPageSize()), classId, examId, dto.getStudentName());
        } else {
            return coreExaminationPublishRecordMapper.findStudentScore(new Page(dto.getPageNum(),
                            dto.getPageSize()), dto.getCourseId(), dto.getExamId(),
                    dto.getStudentName(), classId);
        }
    }


    /**
     * 通过当前时间找到对应学期
     *
     * @return
     */
    public List<LocalDateTime> findDate() {
        ArrayList<LocalDateTime> list = new ArrayList<>();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime ldt = LocalDateTime.parse(now.getYear() + "-08-31 00:00:00", df);
        LocalDateTime ltt = LocalDateTime.parse(now.getYear() + "-03-01 00:00:00", df);
        LocalDateTime star = null;
        LocalDateTime end = null;

        if (now.isAfter(ltt) && now.isBefore(ldt)) {
            star = LocalDateTime.parse(now.getYear() + "-03-01 00:00:00", df);
            end = LocalDateTime.parse(now.getYear() + "-08-31 23:59:59", df);
        } else {
            star = LocalDateTime.parse((now.getYear() - 1) + "-08-31 23:59:59", df);
            end = LocalDateTime.parse(now.getYear() + "-03-01 00:00:00", df);
        }
        list.add(star);
        list.add(end);
        return list;
    }
}

