package org.dromara.system.service.impl;

import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.dto.RoleDTO;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.FormalParentsStudent;
import org.dromara.system.domain.FormalTeacherClass;
import org.dromara.system.domain.SysRole;
import org.dromara.system.domain.bo.FormalParentsStudentBo;
import org.dromara.system.domain.bo.FormalTeacherClassBo;
import org.dromara.system.domain.bo.SysDeptBo;
import org.dromara.system.domain.vo.FormalParentsStudentVo;
import org.dromara.system.domain.vo.FormalTeacherClassVo;
import org.dromara.system.domain.vo.SysDeptVo;
import org.dromara.system.mapper.FormalParentsStudentMapper;
import org.dromara.system.mapper.SysDeptMapper;
import org.dromara.system.service.IFormalParentsStudentService;
import org.dromara.system.service.IFormalTeacherClassService;
import org.dromara.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.CourseChangeBo;
import org.dromara.system.domain.vo.CourseChangeVo;
import org.dromara.system.domain.CourseChange;
import org.dromara.system.mapper.CourseChangeMapper;
import org.dromara.system.service.ICourseChangeService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 调课Service业务层处理
 *
 * @author Lion Li
 * @date 2023-08-16
 */
@RequiredArgsConstructor
@Service
public class CourseChangeServiceImpl implements ICourseChangeService {

    private final CourseChangeMapper baseMapper;

    private final IFormalTeacherClassService formalTeacherClassService;

    private final IFormalParentsStudentService formalParentsStudentService;
    private final ISysDeptService sysDeptService;

    /**
     * 查询调课
     */
    @Override
    public CourseChangeVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询调课列表
     */
    @Override
    public TableDataInfo<CourseChangeVo> queryPageList(CourseChangeBo bo, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<RoleDTO> roles = loginUser.getRoles();
        boolean bl = false;
        for (RoleDTO role : roles) {
            if ("teacher".equals(role.getRoleKey())) {
                bl = true;
                break;
            }
        }
        //角色是老师
        if (bl) {
            //查询老师班级
            FormalTeacherClassBo formalTeacherClass = new FormalTeacherClassBo();
            formalTeacherClass.setTeacherId(loginUser.getUserId());
            List<FormalTeacherClassVo> formalTeacherClassList = formalTeacherClassService.queryList(formalTeacherClass);

            List<Long> classIds = formalTeacherClassList.stream().map(FormalTeacherClassVo::getClassId).collect(Collectors.toList());
            bo.setSubjectClassIds(classIds);
            bo.setApplyId(loginUser.getUserId());
            bo.setBePersonnelId(loginUser.getUserId());
        }

        LambdaQueryWrapper<CourseChange> lqw = buildQueryWrapper(bo);
        Page<CourseChangeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询调课列表
     */
    @Override
    public List<CourseChangeVo> queryList(CourseChangeBo bo) {
        LambdaQueryWrapper<CourseChange> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<CourseChange> buildQueryWrapper(CourseChangeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<CourseChange> lqw = Wrappers.lambdaQuery();
        if(bo.getApplyId() != null && bo.getApplyId() != 0L) {
            lqw.and(wrapper -> wrapper.eq( CourseChange::getApplyId, bo.getApplyId())
                .or()
                .eq( CourseChange::getBePersonnelId, bo.getBePersonnelId())
            );
        }
        lqw.like(StringUtils.isNotBlank(bo.getApplyName()), CourseChange::getApplyName, bo.getApplyName());
        lqw.eq(bo.getApplyTime() != null, CourseChange::getApplyTime, bo.getApplyTime());
        lqw.eq(bo.getSubjectClassId()!= null, CourseChange::getSubjectClassId, bo.getSubjectClassId());
        lqw.eq(StringUtils.isNotBlank(bo.getSubjectClass()), CourseChange::getSubjectClass, bo.getSubjectClass());
        lqw.eq(StringUtils.isNotBlank(bo.getSubject()), CourseChange::getSubject, bo.getSubject());
        lqw.eq(StringUtils.isNotBlank(bo.getIsNum()), CourseChange::getIsNum, bo.getIsNum());
        lqw.eq(bo.getSubjectTime() != null, CourseChange::getSubjectTime, bo.getSubjectTime());
        lqw.eq(StringUtils.isNotBlank(bo.getSubjectWeek()), CourseChange::getSubjectWeek, bo.getSubjectWeek());
        lqw.eq(StringUtils.isNotBlank(bo.getBePersonnel()), CourseChange::getBePersonnel, bo.getBePersonnel());
        lqw.eq(StringUtils.isNotBlank(bo.getBeSubject()), CourseChange::getBeSubject, bo.getBeSubject());
        lqw.eq(StringUtils.isNotBlank(bo.getBeIsNum()), CourseChange::getBeIsNum, bo.getBeIsNum());
        lqw.eq(bo.getBeSubjectTime() != null, CourseChange::getBeSubjectTime, bo.getBeSubjectTime());
        lqw.eq(StringUtils.isNotBlank(bo.getWeek()), CourseChange::getWeek, bo.getWeek());
        lqw.eq(StringUtils.isNotBlank(bo.getIsPass()), CourseChange::getIsPass, bo.getIsPass());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), CourseChange::getContent, bo.getContent());
        lqw.eq(bo.getAuditId() != null, CourseChange::getAuditId, bo.getAuditId());
        lqw.eq(StringUtils.isNotBlank(bo.getAuditUser()), CourseChange::getAuditUser, bo.getAuditUser());
        lqw.eq(StringUtils.isNotBlank(bo.getOpinion()), CourseChange::getOpinion, bo.getOpinion());
        lqw.eq(bo.getSchoolId()!= null, CourseChange::getSchoolId, bo.getSchoolId());
        lqw.like(StringUtils.isNotBlank(bo.getSchoolName()), CourseChange::getSchoolName, bo.getSchoolName());
        lqw.in((bo.getSubjectClassIds()!=null && bo.getSubjectClassIds().size()>0),CourseChange::getSubjectClassId,bo.getSubjectClassIds());
        lqw.orderByDesc(CourseChange::getCreateTime);
        return lqw;
    }

    /**
     * 新增调课
     */
    @Override
    public R<Void> insertByBo(CourseChangeBo bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        //判断修改课程属不属于当前老师
        FormalTeacherClassBo formalTeacherClass = new FormalTeacherClassBo();
        formalTeacherClass.setTeacherId(loginUser.getUserId());
        List<FormalTeacherClassVo> formalTeacherClassList = formalTeacherClassService.queryList(formalTeacherClass);
        Boolean bl = false;
        for (FormalTeacherClassVo teacherClass : formalTeacherClassList) {
            if(bo.getSubjectClassId().equals(teacherClass.getClassId()) && bo.getSubject().equals(teacherClass.getDiscipline())){
                bl = true;
                break;
            }
        }
        if(!bl){
            return R.fail("请选择属于自己的课程。");
        }

        bo.setSchoolId(formalTeacherClassList.get(0).getSchoolId());
        bo.setSchoolName(formalTeacherClassList.get(0).getSchoolName());
        bo.setApplyId(loginUser.getUserId());
        bo.setApplyName(formalTeacherClassList.get(0).getTeacherName());
        bo.setCreateTime(DateUtils.getNowDate());
        //查询被调课的老师信息
        FormalTeacherClassBo formalTeacherClassBe = new FormalTeacherClassBo();
        formalTeacherClassBe.setClassId(bo.getSubjectClassId());
        formalTeacherClassBe.setDiscipline(bo.getBeSubject());
        List<FormalTeacherClassVo> formalTeacherClassBeList = formalTeacherClassService.queryList(formalTeacherClassBe);
        if(formalTeacherClassBeList==null || formalTeacherClassBeList.size()<=0){
            return R.fail();
        }
        bo.setBePersonnel(formalTeacherClassBeList.get(0).getTeacherName());
        bo.setBePersonnelId(formalTeacherClassBeList.get(0).getTeacherId());
        CourseChange add = MapstructUtils.convert(bo, CourseChange.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            return R.ok();
        }
        return R.fail();
    }

    /**
     * 修改调课
     */
    @Override
    public Boolean updateByBo(CourseChangeBo bo) {
        //查询被调课的老师信息
        FormalTeacherClassBo formalTeacherClassBe = new FormalTeacherClassBo();
        formalTeacherClassBe.setClassId(bo.getSubjectClassId());
        formalTeacherClassBe.setDiscipline(bo.getBeSubject());
        List<FormalTeacherClassVo> formalTeacherClassBeList = formalTeacherClassService.queryList(formalTeacherClassBe);
        if(formalTeacherClassBeList==null || formalTeacherClassBeList.size()<=0){
            return false;
        }
        bo.setBePersonnel(formalTeacherClassBeList.get(0).getTeacherName());
        bo.setBePersonnelId(formalTeacherClassBeList.get(0).getTeacherId());
        CourseChange update = MapstructUtils.convert(bo, CourseChange.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CourseChange entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除调课
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<CourseChangeVo> courseList(CourseChangeBo bo, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<RoleDTO> roles = loginUser.getRoles();
        List<Long> classIdList = new ArrayList<>();
        for (RoleDTO role : roles) {
            if ("teacher".equals(role.getRoleKey())) {

                //查询老师班级
                FormalTeacherClassBo formalTeacherClass = new FormalTeacherClassBo();
                formalTeacherClass.setTeacherId(loginUser.getUserId());
                List<FormalTeacherClassVo> formalTeacherClassList = formalTeacherClassService.queryList(formalTeacherClass);
                List<Long> classIds = formalTeacherClassList.stream().map(FormalTeacherClassVo::getClassId).collect(Collectors.toList());
                classIdList.addAll(classIds);

            }
            if("parents".equals(role.getRoleKey())){
                FormalParentsStudentBo formalParentsStudent = new FormalParentsStudentBo();
                formalParentsStudent.setParentsId(loginUser.getUserId());
                List<FormalParentsStudentVo> formalParentsStudentList = formalParentsStudentService.queryList(formalParentsStudent);
                List<Long> classIds = formalParentsStudentList.stream().map(FormalParentsStudentVo::getClassId).collect(Collectors.toList());
                classIdList.addAll(classIds);
            }
            if("school".equals(role.getRoleKey())){
                SysDeptBo dept = new SysDeptBo();
                dept.setParentId(loginUser.getDeptId());
                List<SysDeptVo> depts = sysDeptService.selectDeptList(dept);
                List<Long> classIds = depts.stream().map(SysDeptVo::getDeptId).collect(Collectors.toList());
                classIdList.addAll(classIds);
            }
        }
        bo.setSubjectClassIds(classIdList);
        LambdaQueryWrapper<CourseChange> lqw = buildQueryWrapper(bo);
        Page<CourseChangeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public R<Void> updateCourseChangeReply(CourseChangeBo bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        //判断当前老师是否有权限回复该信息
        FormalTeacherClassBo formalTeacherClass = new FormalTeacherClassBo();
        formalTeacherClass.setTeacherId(loginUser.getUserId());
        formalTeacherClass.setClassId(bo.getSubjectClassId());
        formalTeacherClass.setDiscipline(bo.getBeSubject());
        List<FormalTeacherClassVo> formalTeacherClassList = formalTeacherClassService.queryList(formalTeacherClass);
        if (formalTeacherClassList == null || formalTeacherClassList.size() <= 0) {
            return R.fail("请回复自己授课的班级与课程");
        }
        bo.setAuditId(loginUser.getUserId());
        bo.setAuditUser(loginUser.getNickname());
        bo.setCreateTime(DateUtils.getNowDate());
        CourseChange update = MapstructUtils.convert(bo, CourseChange.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update)>0 ? R.ok() : R.fail();
    }
}
