package com.qmth.teachcloud.common.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.teachcloud.common.bean.dto.DataPermissionRule;
import com.qmth.teachcloud.common.bean.params.BasicCollegeParams;
import com.qmth.teachcloud.common.bean.result.BasicCollegeResult;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.*;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.mapper.BasicCollegeMapper;
import com.qmth.teachcloud.common.service.*;
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.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 学生学院服务实现类
 * @Author: CaoZixuan
 * @Date: 2022-08-17
 */
@Service
public class BasicCollegeServiceImpl extends ServiceImpl<BasicCollegeMapper, BasicCollege> implements BasicCollegeService {
    @Resource
    private BasicMajorService basicMajorService;
    @Resource
    private BasicStudentService basicStudentService;
    @Resource
    private CommonCacheService commonCacheService;
    @Resource
    private BasicRoleDataPermissionService basicRoleDataPermissionService;

    @Override
    public IPage<BasicCollegeResult> basicCollegePage(Long schoolId, String collegeName, int pageNumber, int pageSize) {
        collegeName = SystemConstant.translateSpecificSign(collegeName);
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionRule dpr = basicRoleDataPermissionService.findDataPermission(schoolId,requestUser.getId(),ServletUtil.getRequest().getServletPath());
        return this.baseMapper.findBasicCollegePage(new Page<>(pageNumber, pageSize), schoolId, collegeName, dpr);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long saveBasicCollege(BasicCollegeParams basicCollegeParams, SysUser requestUser) throws IllegalAccessException {
        SystemConstant.verifyDBFields(basicCollegeParams, basicCollegeParams.getClass());

        Long id = basicCollegeParams.getId();
        Long schoolId = requestUser.getSchoolId();
        String collegeName = basicCollegeParams.getCollegeName();
        // 检验学院名称一定和二级机构（学院级机构）名称一致 
        List<SysOrg> collegeOrgList = commonCacheService.addOrgCollegeLevelCache(schoolId);
        if (collegeOrgList.stream().noneMatch(e -> collegeName.equals(e.getName()))){
            throw ExceptionResultEnum.ERROR.exception("学生所在的学院名称【" + collegeName + "】不在学院机构中");
        }

        // 校验专业唯一性（名称在学院下）
        BasicCollege checkName = this.getOne(new QueryWrapper<BasicCollege>().lambda()
                .eq(BasicCollege::getSchoolId, schoolId)
                .eq(BasicCollege::getCollegeName, collegeName));
        if (Objects.nonNull(checkName) && !checkName.getId().equals(id)) {
            throw ExceptionResultEnum.ERROR.exception("学生学院名称【" + collegeName + "】重复");
        }
        if (SystemConstant.longNotNull(id)) {
            // 编辑
            BasicCollege old = this.getById(id);
            if (Objects.isNull(old)) {
                throw ExceptionResultEnum.ERROR.exception("所选学生学院不存在");
            }
            this.update(new UpdateWrapper<BasicCollege>().lambda()
                    .eq(BasicCollege::getId, id)
                    .set(BasicCollege::getCollegeName, collegeName)
                    .set(BasicCollege::getUpdateId,requestUser.getId()));

        } else {
            // 新增
            id = SystemConstant.getDbUuid();
            BasicCollege basicCollege = new BasicCollege();
            basicCollege.setId(id);
            basicCollege.setCollegeName(collegeName);
            basicCollege.setSchoolId(schoolId);
            basicCollege.setOrgId(requestUser.getOrgId());
            basicCollege.setCreateId(requestUser.getId());
            this.save(basicCollege);
        }
        return id;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteBasicCollegeByIdList(List<Long> idList) {
        // 判断专业
        List<BasicMajor> basicMajorList = basicMajorService.list(new QueryWrapper<BasicMajor>().lambda().in(BasicMajor::getBelongOrgId, idList));
        if (basicMajorList.size() > 0) {
            List<Long> collegeIdList = basicMajorList.stream().map(BasicMajor::getBelongOrgId).distinct().collect(Collectors.toList());
            String collegeNames = this.list(new QueryWrapper<BasicCollege>()
                            .lambda()
                            .in(BasicCollege::getId, collegeIdList))
                    .stream()
                    .map(BasicCollege::getCollegeName)
                    .collect(Collectors.joining(","));
            throw ExceptionResultEnum.ERROR.exception("学生学院【" + collegeNames + "】被专业绑定，无法优先删除");
        }

        // 判断学生
        List<BasicStudent> basicStudentList = basicStudentService.list(new QueryWrapper<BasicStudent>().lambda().in(BasicStudent::getBelongOrgId, idList));
        if (basicStudentList.size() > 0) {
            List<Long> collegeIdList = basicStudentList.stream().map(BasicStudent::getBelongOrgId).distinct().collect(Collectors.toList());
            String collegeNames = this.list(new QueryWrapper<BasicCollege>().lambda().in(BasicCollege::getId, collegeIdList))
                    .stream()
                    .map(BasicCollege::getCollegeName)
                    .collect(Collectors.joining(","));
            throw ExceptionResultEnum.ERROR.exception("学生学院【" + collegeNames + "】被学生绑定，无法优先删除");
        }
        return this.removeByIds(idList);
    }
}
