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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.distributed.print.business.bean.result.BasicTeachClazzResult;
import com.qmth.teachcloud.common.entity.BasicExamStudent;
import com.qmth.teachcloud.common.entity.BasicTeachClazz;
import com.qmth.distributed.print.business.mapper.BasicTeachClazzMapper;
import com.qmth.distributed.print.business.service.BasicExamStudentService;
import com.qmth.distributed.print.business.service.BasicTeachClazzService;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 基础教学班表 服务实现类
 * </p>
 *
 * @author CaoZixuan
 * @since 2024-02-22
 */
@Service
public class BasicTeachClazzServiceImpl extends ServiceImpl<BasicTeachClazzMapper, BasicTeachClazz> implements BasicTeachClazzService {

    @Resource
    private BasicExamStudentService basicExamStudentService;

    @Transactional
    @Override
    public BasicTeachClazz findOrCreateBasicTeachClazz(SysUser requestUser, Long examId, String courseCode, String teachClazzName) {
        Long schoolId = requestUser.getSchoolId();
        Long userId = requestUser.getId();
        BasicTeachClazz basicTeachClazz;
        basicTeachClazz = this.getOne(
                new QueryWrapper<BasicTeachClazz>().lambda().eq(BasicTeachClazz::getSchoolId, schoolId)
                        .eq(BasicTeachClazz::getExamId, examId).eq(BasicTeachClazz::getClazzName, teachClazzName).last(SystemConstant.LIMIT1));

        if (Objects.isNull(basicTeachClazz)) {
            basicTeachClazz = new BasicTeachClazz();
            basicTeachClazz.setSchoolId(schoolId);
            basicTeachClazz.setClazzName(teachClazzName);
            basicTeachClazz.setCourseCode(courseCode);
            basicTeachClazz.setExamId(examId);
            basicTeachClazz.insertInfo(userId);
            this.save(basicTeachClazz);
        }
        return basicTeachClazz;
    }

    @Override
    public List<BasicTeachClazzResult> findAllTeachClazz(Long examId, String courseCode, String clazzName) {
        clazzName = SystemConstant.translateSpecificSign(clazzName);
        return this.baseMapper.findTeachClazzList(examId, courseCode, clazzName);
    }

    @Transactional
    @Override
    public void deleteFreeClazz(Long basicTeachClazzId) {
        if (basicExamStudentService.count(
                new QueryWrapper<BasicExamStudent>().lambda().eq(BasicExamStudent::getClazzId, basicTeachClazzId))
                == 0) {
            this.removeById(basicTeachClazzId);
        }
    }
}