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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.result.DictionaryResult;
import com.qmth.distributed.print.business.bean.result.TeachCourseResult;
import com.qmth.distributed.print.business.entity.TeachClazz;
import com.qmth.distributed.print.business.entity.TeachCourse;
import com.qmth.distributed.print.business.mapper.TeachCourseMapper;
import com.qmth.distributed.print.business.service.TeachClazzService;
import com.qmth.distributed.print.business.service.TeachCourseService;
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.service.SysOrgService;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.springframework.beans.BeanUtils;
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.Set;
import java.util.stream.Collectors;

/**
 * @Description: 教学课程服务实现类
 * @Author: CaoZixuan
 * @Date: 2022-02-07
 */
@Service
public class TeachCourseServiceImpl extends ServiceImpl<TeachCourseMapper, TeachCourse> implements TeachCourseService {
    @Resource
    private BasicCourseService basicCourseService;
    @Resource
    private SysOrgService sysOrgService;
    @Resource
    private TeachClazzService teachClazzService;

    @Override
    public IPage<TeachCourseResult> teachCoursePage(String courseName, int pageNumber, int pageSize, Long userId) {
        if (!SystemConstant.longNotNull(userId)) {
            throw ExceptionResultEnum.ERROR.exception("请先登录");
        }
        Long schoolId = SystemConstant.convertIdToLong(ServletUtil.getRequestHeaderSchoolId().toString());
        courseName = SystemConstant.translateSpecificSign(courseName);
        return this.baseMapper.findTeachCoursePage(new Page<>(pageNumber, pageSize), courseName, userId, schoolId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean createTeachCourse(Long basicCourseId, SysUser requestUser) {
        BasicCourse basicCourse = basicCourseService.getById(basicCourseId);
        if (Objects.isNull(basicCourse)) {
            throw ExceptionResultEnum.ERROR.exception("基础课程不存在");
        }
        Long schoolId = basicCourse.getSchoolId();
        Long userId = requestUser.getId();

        // 唯一性检验
        TeachCourse checkUnique = this.getOne(new QueryWrapper<TeachCourse>()
                .lambda()
                .eq(TeachCourse::getSchoolId, schoolId)
                .eq(TeachCourse::getBasicCourseId, basicCourseId)
                .eq(TeachCourse::getUserId, userId));
        if (Objects.nonNull(checkUnique)) {
            throw ExceptionResultEnum.ERROR.exception("用户【" + requestUser.getRealName() + "】已存在课程编号为【"
                    + basicCourse.getCode() + "】课程名称为【" + basicCourse.getName() + "】的教学课程");
        }

        TeachCourse teachCourse = new TeachCourse();
        teachCourse.setSchoolId(schoolId);
        teachCourse.setBasicCourseId(basicCourseId);
        teachCourse.setUserId(userId);
        teachCourse.setEnable(true);
        teachCourse.insertInfo(userId);
        return this.save(teachCourse);
    }

    @Override
    public List<DictionaryResult> findBasicCourseByUser(SysUser requestUser) {
        Long userId = requestUser.getId();
        Set<Long> orgIdSet = sysOrgService.findDeepOrgIdListByUserId(userId);
        List<BasicCourse> basicCourseList = basicCourseService.list(new QueryWrapper<BasicCourse>()
                .lambda()
                .in(BasicCourse::getTeachingRoomId, orgIdSet)
                .eq(BasicCourse::getEnable, true));

        List<DictionaryResult> resultList = new ArrayList<>();
        for (BasicCourse basicCourse : basicCourseList) {
            DictionaryResult dictionaryResult = new DictionaryResult();
            BeanUtils.copyProperties(basicCourse, dictionaryResult);
            resultList.add(dictionaryResult);
        }
        return resultList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteTeachCourseBatch(List<Long> idList) {
        List<TeachClazz> teachClazzList = teachClazzService.list(new QueryWrapper<TeachClazz>().lambda().in(TeachClazz::getTeachCourseId, idList));
        StringBuilder exception = new StringBuilder();
        Set<Long> teachCourseIdSet = teachClazzList.stream().map(TeachClazz::getTeachCourseId).collect(Collectors.toSet());
        for (Long teachCourseId : teachCourseIdSet) {
            String e = "";
            List<TeachClazz> cellList = teachClazzList.stream().filter(cell -> teachCourseId.equals(cell.getTeachCourseId())).collect(Collectors.toList());
            if (cellList.size() > 0) {
                String clazzNameStr = cellList.stream().map(TeachClazz::getTeachClazzName).collect(Collectors.joining(","));
                String courseName = basicCourseService.getById(this.getById(teachCourseId).getBasicCourseId()).getName();
                e = e + "【" + courseName + "】" + "已绑定教学班级【" + clazzNameStr + "】不能删除，请先删除被绑定的教学班级\n";
            }
            exception.append(e);
        }
        if (teachClazzList.size() > 0) {
            throw ExceptionResultEnum.ERROR.exception(exception.toString());
        }
        return this.removeByIds(idList);
    }

}
