package com.qmth.distributed.print.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.distributed.print.business.bean.params.TeachClazzParams;
import com.qmth.distributed.print.business.bean.result.DictionaryResult;
import com.qmth.distributed.print.business.bean.result.TeachClazzResult;
import com.qmth.distributed.print.business.entity.TeachClazz;
import com.qmth.distributed.print.business.entity.TeachCourse;
import com.qmth.distributed.print.business.entity.TeachStudent;
import com.qmth.distributed.print.business.mapper.TeachClazzMapper;
import com.qmth.distributed.print.business.service.TeachClazzService;
import com.qmth.distributed.print.business.service.TeachCourseService;
import com.qmth.distributed.print.business.service.TeachStudentService;
import com.qmth.teachcloud.common.base.BaseEntity;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicCourse;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.service.BasicCourseService;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 教学班服务实现类
 * @Author: CaoZixuan
 * @Date: 2022-02-09
 */
@Service
public class TeachClazzServiceImpl extends ServiceImpl<TeachClazzMapper,TeachClazz> implements TeachClazzService {
    @Resource
    private TeachStudentService teachStudentService;
    @Resource
    private TeachCourseService teachCourseService;
    @Resource
    private BasicCourseService basicCourseService;

    @Override
    public IPage<TeachClazzResult> teachClazzPage(Long teachCourseId, String teachClazzName, int pageNumber, int pageSize) {
        Long schoolId = SystemConstant.convertIdToLong(ServletUtil.getRequestHeaderSchoolId().toString());
        teachClazzName = SystemConstant.translateSpecificSign(teachClazzName);
        IPage<TeachClazzResult> resultIPage = this.baseMapper.findTeachClazzPage(new Page<>(pageNumber, pageSize), teachCourseId, teachClazzName, schoolId);
        List<TeachClazzResult> teachClazzResultList = resultIPage.getRecords();

        for (TeachClazzResult teachClazzResult : teachClazzResultList) {
            Long id = teachClazzResult.getId();
            int count = teachStudentService.count(new QueryWrapper<TeachStudent>().lambda().eq(TeachStudent::getTeachClazzId, id));
            teachClazzResult.setTeachStudentCount(count);
        }
        return resultIPage;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean editTeachClazz(TeachClazzParams teachClazzParams, SysUser requestUser) {
        Long id = teachClazzParams.getId();
        Long teachCourseId = teachClazzParams.getTeachCourseId();
        String teachClazzName = teachClazzParams.getTeachClazzName();
        boolean result;

        if (SystemConstant.isOneNull(teachClazzName, teachCourseId)) {
            throw ExceptionResultEnum.ERROR.exception("参数异常");
        }
        if (SystemConstant.longNotNull(id)) {
            // 重命名课程
            result = this.update(new UpdateWrapper<TeachClazz>().lambda().eq(TeachClazz::getId, id).set(TeachClazz::getTeachClazzName, teachClazzName));
        } else {
            TeachCourse teachCourse = teachCourseService.getById(teachCourseId);
            if (Objects.isNull(teachCourse)) {
                throw ExceptionResultEnum.ERROR.exception("教学课程不存在");
            }
            if (!Objects.equals(teachCourse.getUserId(), requestUser.getId())) {
                throw ExceptionResultEnum.ERROR.exception("用户身份信息异常");
            }

            Long schoolId = SystemConstant.convertIdToLong(ServletUtil.getRequestHeaderSchoolId().toString());
            TeachClazz check = this.getOne(new QueryWrapper<TeachClazz>()
                    .lambda()
                    .eq(TeachClazz::getSchoolId, schoolId)
                    .eq(TeachClazz::getTeachClazzName, teachClazzName));

            if (Objects.nonNull(check)) {
                throw ExceptionResultEnum.ERROR.exception("教学课程【" + basicCourseService.getById(teachCourseService.getById(check.getTeachCourseId()).getBasicCourseId()).getName()
                        + "】中已存在班级名称为【" + check.getTeachClazzName() + "】的班级");
            }

            TeachClazz teachClazz = new TeachClazz();
            teachClazz.setSchoolId(schoolId);
            teachClazz.setTeachClazzName(teachClazzName);
            teachClazz.setUserId(teachCourse.getUserId());
            teachClazz.setTeachCourseId(teachCourseId);
            teachClazz.insertInfo(requestUser.getId());
            result = this.save(teachClazz);
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteTeachClazzBatch(List<Long> idList) {
        // TODO: 2022/2/10 删除逻辑不确定 先直接删除 （同时删除下级所有学生）
        List<TeachStudent> teachStudentList = teachStudentService.list(new QueryWrapper<TeachStudent>().lambda().eq(TeachStudent::getTeachClazzId, idList));
        // 删除教学学生
        teachStudentService.deleteTeachStudentBatch(teachStudentList.stream().map(BaseEntity::getId).distinct().collect(Collectors.toList()));
        return this.removeByIds(idList);
    }

    @Override
    public List<DictionaryResult> findTeachCourseByUserId(Long userId) {
        Long schoolId = SystemConstant.convertIdToLong(String.valueOf(ServletUtil.getRequestHeaderSchoolId()));
        List<TeachCourse> teachCourseList = teachCourseService.list(new QueryWrapper<TeachCourse>().lambda()
                .eq(TeachCourse::getUserId, userId)
                .eq(TeachCourse::getSchoolId, schoolId)
                .orderByDesc(TeachCourse::getCreateTime));
        List<DictionaryResult> dictionaryResultList = new ArrayList<>();
        for (TeachCourse teachCourse : teachCourseList) {
            BasicCourse basicCourse = basicCourseService.getById(teachCourse.getBasicCourseId());
            if (basicCourse.getEnable()){
                DictionaryResult dictionaryResult = new DictionaryResult();
                dictionaryResult.setId(teachCourse.getId());
                dictionaryResult.setCode(basicCourse.getCode());
                dictionaryResult.setName(basicCourse.getName());
                dictionaryResultList.add(dictionaryResult);
            }
        }
        return dictionaryResultList;
    }
}
