package yangtz.cs.liu.campus.service.impl.curricula;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yangtz.cs.liu.campus.domain.curricula.CurriculaStudent;
import yangtz.cs.liu.campus.domain.curricula.CurriculaSub;
import yangtz.cs.liu.campus.domain.curricula.CurriculaVariable;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGrade;
import yangtz.cs.liu.campus.mapper.curricula.CurriculaStudentMapper;
import yangtz.cs.liu.campus.mapper.curricula.CurriculaVariableMapper;
import yangtz.cs.liu.campus.mapper.schoolgrade.SchoolGradeMapper;
import yangtz.cs.liu.campus.service.curricula.ICurriculaVariableService;
import yangtz.cs.liu.campus.vo.curricula.CurriculaVariableVo;
import static com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CurriculaVariableServiceImpl extends ServiceImpl<CurriculaVariableMapper, CurriculaVariable> implements ICurriculaVariableService {

    @Autowired
    private CurriculaVariableMapper curriculaVariableMapper;
    @Autowired
    private CurriculaStudentMapper curriculaStudentMapper;
    @Autowired
    private SchoolGradeMapper schoolGradeMapper;
    /**
     * 查询选课任务列表
     * @param curriculaVariable
     * @return
     */
    @Override
    public List<CurriculaVariableVo> selectCurriculaVariableList(CurriculaVariableVo curriculaVariable) {
        List<CurriculaVariableVo> list = new ArrayList<>();
        LambdaQueryWrapper<CurriculaVariable> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(isNotBlank(curriculaVariable.getTaskName()),CurriculaVariable::getTaskName,curriculaVariable.getTaskName())
                .eq(isNotBlank(curriculaVariable.getGrade()),CurriculaVariable::getGrade,curriculaVariable.getGrade())
                .eq(CurriculaVariable::getDelFlag,"0")
                .orderByDesc(CurriculaVariable::getGrade);
        List<CurriculaVariable> curriculaVariables = curriculaVariableMapper.selectList(wrapper);
        //循环选课任务列表，计算总人数和已选人数
        curriculaVariables.forEach(curriculaVariable1 -> {
            CurriculaVariableVo curriculaVariableVo = new CurriculaVariableVo();
            BeanUtils.copyProperties(curriculaVariable1,curriculaVariableVo);
            Map<String, Long> map = curriculaStudentMapper.countNum(curriculaVariableVo.getId());
            Long zrs = map.get("zrs");
            Long yxrs = map.get("yxrs");
            curriculaVariableVo.setYxrs(zrs.intValue());
            curriculaVariableVo.setZrs(yxrs.intValue());
            list.add(curriculaVariableVo);
        });
        return list;
    }

    /**
     * 新增选课任务
     * @param curriculaVariableVo
     * @return
     */
    @Override
    @Transactional
    public int insertCurriculaVariable(CurriculaVariableVo curriculaVariableVo) {
        int i = 0;
        //判断是否已存在当前级部选课任务
//        LambdaQueryWrapper<CurriculaVariable> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(CurriculaVariable::getGrade,curriculaVariableVo.getGrade())
//                .eq(CurriculaVariable::getDelFlag,"0");
//        List<CurriculaVariable> curriculaVariables = curriculaVariableMapper.selectList(wrapper);
//        if (curriculaVariables.size() > 0){
//            throw new ServiceException("已存在当前级部的选课任务");
//        }
        curriculaVariableVo.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
        curriculaVariableVo.setCreateTime(DateUtils.getNowDate());
        //新增选课任务
        i += curriculaVariableMapper.insertCurriculaVariable(curriculaVariableVo);
        //通过id查询刚新增的选课任务
        CurriculaVariable variable = curriculaVariableMapper.selectById(curriculaVariableVo.getId());
        //新增学生与选课任务关系
        List<Long> studentIds = curriculaVariableMapper.selectByGrade(variable.getGrade());

        if (studentIds.size() > 0){
            List<CurriculaStudent> curriculaStudents = new ArrayList<>();
            for (Long studentId : studentIds) {
                CurriculaStudent curriculaStudent = new CurriculaStudent();
                curriculaStudent.setStudentId(studentId);
                curriculaStudent.setCurriculaId(curriculaVariableVo.getId());
                curriculaStudents.add(curriculaStudent);
            }
            curriculaStudentMapper.batchInsertCurriculaStudent(curriculaStudents);
        }
        //新增选课与科目关系
        insertCurriculaSub(curriculaVariableVo);
        return i;
    }

    /**
     * 获取选课任务详细信息
     * @param id
     * @return
     */
    @Override
    public CurriculaVariableVo selectCurriculaVariableById(Long id) {
        //通过id查询选课任务
        CurriculaVariable curriculaVariable = curriculaVariableMapper.selectById(id);
        //转vo
        CurriculaVariableVo curriculaVariableVo = new CurriculaVariableVo();
        BeanUtils.copyProperties(curriculaVariable,curriculaVariableVo);
        //计算总人数和已选人数
        Map<String, Long> map = curriculaStudentMapper.countNum(id);
        Long zrs = map.get("zrs");
        Long yxrs = map.get("yxrs");
        curriculaVariableVo.setYxrs(zrs.intValue());
        curriculaVariableVo.setZrs(yxrs.intValue());
        //查询选课与科目关系
        CurriculaSub cj = new CurriculaSub();
        cj.setCurriculaId(id);
        cj.setDictType("specialty");
        List<CurriculaSub> cjs = curriculaVariableMapper.selectCurriculaSubList(cj);
        if (cjs.size() > 0){
            curriculaVariableVo.setCjkmList(cjs);
        }
        CurriculaSub xj = new CurriculaSub();
        xj.setCurriculaId(id);
        xj.setDictType("summer_course");
        List<CurriculaSub> xjs = curriculaVariableMapper.selectCurriculaSubList(xj);
        if (xjs.size() > 0){
            curriculaVariableVo.setXjkmList(xjs);
        }
        CurriculaSub yt = new CurriculaSub();
        yt.setCurriculaId(id);
        yt.setDictType("art_subject");
        List<CurriculaSub> yts = curriculaVariableMapper.selectCurriculaSubList(yt);
        if (yts.size() > 0){
            curriculaVariableVo.setYtkmList(yts);
        }
        return curriculaVariableVo;
    }

    /**
     * 获取当前最新级部
     * @return
     */
    @Override
    public Map<String, String> getNewGrade() {
        LambdaQueryWrapper<SchoolGrade> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SchoolGrade::getDelFlag,'0')
                .orderByDesc(SchoolGrade::getGradeYear).last("LIMIT 1");
        SchoolGrade schoolGrade = schoolGradeMapper.selectOne(wrapper);
        Map<String,String> map = new HashMap<>();
        map.put("grade",schoolGrade.getGradeYear());
        return map;
    }

    /**
     * 获取班级下拉框
     * @param grade
     * @return
     */
    @Override
    public List<Map<String, String>> selectClass(String grade) {
        return curriculaVariableMapper.selectClass(grade);
    }

    /**
     * 修改选课任务
     * @param curriculaVariableVo
     * @return
     */
    @Override
    public int updateCurriculaVariable(CurriculaVariableVo curriculaVariableVo) {
        LambdaQueryWrapper<CurriculaVariable> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CurriculaVariable::getGrade,curriculaVariableVo.getGrade())
                .ne(CurriculaVariable::getId,curriculaVariableVo.getId())
                .eq(CurriculaVariable::getDelFlag,'0');
        List<CurriculaVariable> curriculaVariables = curriculaVariableMapper.selectList(wrapper);
        if (curriculaVariables.size() > 0){
            throw new ServiceException("已存在当前级部");
        }
        CurriculaVariable curriculaVariable = new CurriculaVariable();
        BeanUtils.copyProperties(curriculaVariableVo,curriculaVariable);
        //删除选课与科目关联
        curriculaVariableMapper.deleteCurriculaSubByCurriculaId(curriculaVariableVo.getId());
        //新增选课与科目关联
        insertCurriculaSub(curriculaVariableVo);
        return curriculaVariableMapper.updateById(curriculaVariable);
    }

    /**
     * 新增选课与科目关联
     * @param curriculaVariableVo
     */
    public void insertCurriculaSub(CurriculaVariableVo curriculaVariableVo){
        List<CurriculaSub> cjkmList = curriculaVariableVo.getCjkmList();
        List<CurriculaSub> xjkmList = curriculaVariableVo.getXjkmList();
        List<CurriculaSub> ytkmList = curriculaVariableVo.getYtkmList();
        if (cjkmList.size() > 0){
            List<CurriculaSub> cjkmList1 = new ArrayList<>();
            for (CurriculaSub cjkm : cjkmList) {
                cjkm.setCurriculaId(curriculaVariableVo.getId());
                cjkm.setCreateBy(SecurityUtils.getUsername());
                cjkm.setCreateTime(DateUtils.getNowDate());
                cjkmList1.add(cjkm);
            }
            //批量新增春季选课科目
            curriculaVariableMapper.batchInsetCurriculaSubs(cjkmList1);
        }
        if (xjkmList.size() > 0){
            List<CurriculaSub> xjkmList1 = new ArrayList<>();
            for (CurriculaSub xjkm : xjkmList) {
                xjkm.setCurriculaId(curriculaVariableVo.getId());
                xjkm.setCreateBy(SecurityUtils.getUsername());
                xjkm.setCreateTime(DateUtils.getNowDate());
                xjkmList1.add(xjkm);
            }
            //批量新增春季选课科目
            curriculaVariableMapper.batchInsetCurriculaSubs(xjkmList1);
        }
        if (ytkmList.size() > 0){
            List<CurriculaSub> ytkmList1 = new ArrayList<>();
            for (CurriculaSub ytkm : ytkmList) {
                ytkm.setCurriculaId(curriculaVariableVo.getId());
                ytkm.setCreateBy(SecurityUtils.getUsername());
                ytkm.setCreateTime(DateUtils.getNowDate());
                ytkmList1.add(ytkm);
            }
            //批量新增春季选课科目
            curriculaVariableMapper.batchInsetCurriculaSubs(ytkmList1);
        }
    }

    /**
     * 获取选课任务下拉框
     * @return
     */
    @Override
    public List<Map<String, String>> getGrade() {
        Long teacherId = SecurityUtils.getLoginUser().getUser().getUserId();
        return curriculaVariableMapper.getGrade(teacherId);
    }

    /**
     * 获取春季，夏季，艺体科目
     * @return
     */
    @Override
    public List<SysDictType> selectXkTypeList() {
        return curriculaVariableMapper.selectXkTypeList();
    }
}
