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.params.BasicMajorParams;
import com.qmth.teachcloud.common.bean.result.BasicMajorResult;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicClazz;
import com.qmth.teachcloud.common.entity.BasicMajor;
import com.qmth.teachcloud.common.entity.BasicStudent;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.mapper.BasicMajorMapper;
import com.qmth.teachcloud.common.service.BasicClazzService;
import com.qmth.teachcloud.common.service.BasicMajorService;
import com.qmth.teachcloud.common.service.BasicStudentService;
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;

/**
 * <p>
 * 专业字典表 服务实现类
 * </p>
 *
 * @author wangliang
 * @since 2021-10-28
 */
@Service
public class BasicMajorServiceImpl extends ServiceImpl<BasicMajorMapper, BasicMajor> implements BasicMajorService {
    @Resource
    private BasicClazzService basicClazzService;
    @Resource
    private BasicStudentService basicStudentService;

    @Override
    public IPage<BasicMajorResult> basicMajorPage(Long schoolId, String majorName, int pageNumber, int pageSize) {
        majorName = SystemConstant.translateSpecificSign(majorName);
        return this.baseMapper.findBasicMajorPage(new Page<>(pageNumber, pageSize),schoolId,majorName,null);
    }

    @Transactional
    @Override
    public Long saveBasicMajor(BasicMajorParams basicMajorParams,SysUser requestUser) throws IllegalAccessException {
        SystemConstant.verifyDBFields(basicMajorParams,basicMajorParams.getClass());

        Long id = basicMajorParams.getId();
        Long schoolId = requestUser.getSchoolId();
        String majorName = basicMajorParams.getMajorName();
        Long collegeId = basicMajorParams.getCollegeId();

        // 校验专业唯一性（名称在学院下）
        BasicMajor checkName = this.getOne(new QueryWrapper<BasicMajor>().lambda()
                .eq(BasicMajor::getEnable,true)
                .eq(BasicMajor::getSchoolId,schoolId)
                .eq(BasicMajor::getName,majorName));
        if (Objects.nonNull(checkName) && !checkName.getId().equals(id)){
            throw ExceptionResultEnum.ERROR.exception("专业名称【" + majorName + "】重复");
        }
        if (SystemConstant.longNotNull(id)){
            // 编辑
            BasicMajor old = this.getById(id);
            if (Objects.isNull(old) || old.getEnable().equals(false)){
                throw ExceptionResultEnum.ERROR.exception("所选专业不存在或被禁用");
            }
            this.update(new UpdateWrapper<BasicMajor>().lambda()
                    .eq(BasicMajor::getId,id)
                    .set(BasicMajor::getName,majorName)
                    .set(BasicMajor::getBelongOrgId,collegeId));

            // 如果更新了专业所属学院则更新学生级联关系
            if (!collegeId.equals(old.getBelongOrgId())){
                List<BasicStudent> basicStudentList = basicStudentService.list(new QueryWrapper<BasicStudent>().lambda().eq(BasicStudent::getMajorId,id));
                basicStudentList.forEach(e -> e.setBelongOrgId(collegeId));
                basicStudentService.updateBatchById(basicStudentList);
            }

        }else {
            // 新增
            id = SystemConstant.getDbUuid();
            BasicMajor basicMajor = new BasicMajor();
            basicMajor.setId(id);
            basicMajor.setEnable(true);
            basicMajor.setName(majorName);
            basicMajor.setSchoolId(schoolId);
            basicMajor.setCode(null);
            basicMajor.setBelongOrgId(collegeId);
            basicMajor.setOrgId(requestUser.getOrgId());
            this.save(basicMajor);
        }
        return id;
    }

    @Transactional
    @Override
    public boolean deleteBasicMajorByIdList(List<Long> idList) {
        // 判断班级
        List<BasicClazz> basicClazzList = basicClazzService.list(new QueryWrapper<BasicClazz>().lambda().in(BasicClazz::getMajorId,idList));
        if (basicClazzList.size() > 0){
            List<Long> majorIdList = basicClazzList.stream().map(BasicClazz::getMajorId).distinct().collect(Collectors.toList());
            String majorNames = this.list(new QueryWrapper<BasicMajor>().lambda().in(BasicMajor::getId,majorIdList))
                    .stream()
                    .map(BasicMajor::getName)
                    .collect(Collectors.joining(","));
            throw ExceptionResultEnum.ERROR.exception("专业【" + majorNames + "】被班级绑定，无法优先删除");
        }
        // 判断学生
        List<BasicStudent> basicStudentList = basicStudentService.list(new QueryWrapper<BasicStudent>().lambda().in(BasicStudent::getMajorId,idList));
        if (basicStudentList.size() > 0){
            List<Long> majorIdList = basicStudentList.stream().map(BasicStudent::getMajorId).distinct().collect(Collectors.toList());
            String majorNames = this.list(new QueryWrapper<BasicMajor>().lambda().in(BasicMajor::getId,majorIdList))
                    .stream()
                    .map(BasicMajor::getName)
                    .collect(Collectors.joining(","));
            throw ExceptionResultEnum.ERROR.exception("专业【" + majorNames + "】被学生绑定，无法优先删除");
        }
        return this.removeByIds(idList);
    }
}
