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.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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yangtz.cs.liu.campus.domain.curricula.CurriculaStudent;
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 curriculaVariable
     * @return
     */
    @Override
    @Transactional
    public int insertCurriculaVariable(CurriculaVariable curriculaVariable) {
        int i = 0;
        //判断是否已存在当前级部选课任务
        LambdaQueryWrapper<CurriculaVariable> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CurriculaVariable::getGrade,curriculaVariable.getGrade())
                .eq(CurriculaVariable::getDelFlag,"0");
        List<CurriculaVariable> curriculaVariables = curriculaVariableMapper.selectList(wrapper);
        if (curriculaVariables.size() > 0){
            throw new ServiceException("已存在当前级部的选课任务");
        }
        curriculaVariable.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
        curriculaVariable.setCreateTime(DateUtils.getNowDate());
        //新增选课任务
        i += curriculaVariableMapper.insertCurriculaVariable(curriculaVariable);
        //通过id查询刚新增的选课任务
        CurriculaVariable variable = curriculaVariableMapper.selectById(curriculaVariable.getId());
        //新增学生与选课任务关系
        List<Long> studentIds = curriculaVariableMapper.selectByGrade(variable.getGrade());
        if (studentIds.size() > 0){
            for (Long studentId : studentIds) {
                CurriculaStudent curriculaStudent = new CurriculaStudent();
                curriculaStudent.setStudentId(studentId);
                curriculaStudent.setCurriculaId(curriculaVariable.getId());
                curriculaStudentMapper.insert(curriculaStudent);
            }
        }
        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());
        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 curriculaVariable
     * @return
     */
    @Override
    public int updateCurriculaVariable(CurriculaVariable curriculaVariable) {
        LambdaQueryWrapper<CurriculaVariable> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CurriculaVariable::getGrade,curriculaVariable.getGrade())
                .ne(CurriculaVariable::getId,curriculaVariable.getId())
                .eq(CurriculaVariable::getDelFlag,'0');
        List<CurriculaVariable> curriculaVariables = curriculaVariableMapper.selectList(wrapper);
        if (curriculaVariables.size() > 0){
            throw new ServiceException("已存在当前级部");
        }
        return curriculaVariableMapper.updateById(curriculaVariable);
    }

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