package yangtz.cs.liu.campus.service.impl.student;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.UserInfoUtil;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yangtz.cs.liu.campus.domain.schoolClass.SchoolClass;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGrade;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGradeMentor;
import yangtz.cs.liu.campus.domain.student.SchoolStudent;
import yangtz.cs.liu.campus.domain.student.SchoolStudentParent;
import yangtz.cs.liu.campus.mapper.schoolClass.SchoolClassMapper;
import yangtz.cs.liu.campus.mapper.schoolgrade.SchoolGradeMapper;
import yangtz.cs.liu.campus.mapper.schoolgrade.SchoolGradeMentorMapper;
import yangtz.cs.liu.campus.mapper.student.SchoolStudentMapper;
import yangtz.cs.liu.campus.mapper.student.SchoolStudentParentMapper;
import yangtz.cs.liu.campus.service.student.ISchoolStudentParentService;
import yangtz.cs.liu.campus.vo.student.SchoolStudentParentVO;
import yangtz.cs.liu.wechat.vo.userInfo.UserInfoVo;

import java.util.ArrayList;
import java.util.List;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull;
import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNull;
import static com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank;
import static com.ruoyi.common.utils.SecurityUtils.getUserId;
import static yangtz.cs.liu.campus.constant.UserType.PARENT;

@Service
public class SchoolStudentParentServiceImpl extends ServiceImpl<SchoolStudentParentMapper, SchoolStudentParent> implements ISchoolStudentParentService {
    @Autowired
    private SchoolStudentParentMapper schoolStudentParentMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private UserInfoUtil userInfoUtil;

    @Autowired
    private SchoolStudentMapper schoolStudentMapper;

    @Autowired
    private SchoolClassMapper schoolClassMapper;

    @Autowired
    private SchoolGradeMentorMapper schoolGradeMentorMapper;

    @Autowired
    private SchoolGradeMapper schoolGradeMapper;


    @Override
    public List<SchoolStudentParent> queryList(SchoolStudentParent schoolStudentParent) {
        LambdaQueryWrapper<SchoolStudentParent> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolStudentParent::getStudentId, schoolStudentParent.getStudentId()).orderByAsc(SchoolStudentParent::getRelationship);
        return schoolStudentParentMapper.selectList(lqw);
    }

    /**
     * 公众号，获取用户信息
     *
     * @param studentId
     * @return
     */
    @Override
    public List<UserInfoVo> getUserInfo(Long studentId) {
        return schoolStudentParentMapper.getUserInfo(studentId);
    }

    /**
     * 公众号添加监护人
     *
     * @param schoolStudentParent
     * @return
     */
    @Override
    public int additional(SchoolStudentParent schoolStudentParent) {
        //根据电话去查询是否已经存在监护人
        SchoolStudentParent studentParent = schoolStudentParentMapper.selectByPhone(schoolStudentParent);
        if (StringUtils.isNotNull(studentParent)) {
            throw new ServiceException("已经存在该监护人");
        }
        schoolStudentParent.setStudentId(userInfoUtil.getStudentId());
        return schoolStudentParentMapper.insert(schoolStudentParent);
    }

    /**
     * 公众号，切换子女准备
     *
     * @param phone
     * @return
     */
    @Override
    public List<SchoolStudent> changePrepare(String phone) {
        return schoolStudentParentMapper.selectByParentId(phone);
    }

    @Override
    public int saveStudentParent(SchoolStudentParent schoolStudentParent) {
        //通过电话号码去user_id表中去寻找是否存在该用户
        SysUser sysUser = userMapper.selectUserByPhonenumber(schoolStudentParent.getTelephone());
        if (isNull(sysUser)) {      //用户表中不存在用户
            SysUser user = new SysUser();
            user.setUserName(schoolStudentParent.getParentName());
            user.setPhonenumber(schoolStudentParent.getTelephone());
            userMapper.insertUser(user);
        }
        SysUser userByPhonenumber = userMapper.selectUserByPhonenumber(schoolStudentParent.getTelephone());
        schoolStudentParent.setUserId(userByPhonenumber.getUserId());
        return schoolStudentParentMapper.insert(schoolStudentParent);
    }

    @Override
    public int updateStudentParent(SchoolStudentParent schoolStudentParent) {
        //修改user表
        SysUser sysUser = userMapper.selectUserById(schoolStudentParent.getUserId());
        sysUser.setUserName(schoolStudentParent.getParentName());
        sysUser.setPhonenumber(schoolStudentParent.getTelephone());
        userMapper.updateUser(sysUser);
        return schoolStudentParentMapper.updateById(schoolStudentParent);
    }

    @Override
    public int removeParent(List<Long> ids) {
        //对于用户表处理
        for (Long id : ids) {
            SchoolStudentParent parent = schoolStudentParentMapper.selectById(id);
            String telephone = parent.getTelephone();
            List<SchoolStudentParent> studentParents = schoolStudentParentMapper.selectByTelePhone(telephone);
            if (studentParents.size() <= 1) {   //数量小于等于1时，删除用户表中的数据
                userMapper.deleteUserById(parent.getUserId());
            }
        }
        return schoolStudentParentMapper.deleteBatchIds(ids);
    }

    /**
     *
     * @author lyric
     * @date 2022/11/19 20:33
     * 新增学生家长
     */
    @Override
    public int addParent(Long studentId, SchoolStudentParent schoolStudentParent) {
        LambdaQueryWrapper<SchoolStudentParent> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolStudentParent::getStudentId, studentId).eq(SchoolStudentParent::getTelephone, schoolStudentParent.getTelephone());
        SchoolStudentParent parent = schoolStudentParentMapper.selectOne(lqw);
        if (StringUtils.isNotNull(parent)) {
            throw new ServiceException("家长手机号已存在");
        }

        if(isNotNull(schoolStudentParent.getRelationship())){
            LambdaQueryWrapper<SchoolStudentParent> byShip = new LambdaQueryWrapper<>();
            byShip.eq(SchoolStudentParent::getStudentId, studentId).eq(SchoolStudentParent::getRelationship, schoolStudentParent.getRelationship());
            SchoolStudentParent p = schoolStudentParentMapper.selectOne(byShip);
            if (StringUtils.isNotNull(p)) {
                throw new ServiceException("该关系已存在");
            }
        }


        /** 新增进用户表 */
        SysUser user = new SysUser();
        user.setUserLoginType(PARENT);
        user.setUserName(schoolStudentParent.getParentName());
        user.setPhonenumber(schoolStudentParent.getTelephone());
        user.setStudentId(studentId);
        userService.insertUser(user);

        /** 新增进家长表 */
        schoolStudentParent.setUserId(user.getUserId());
        return schoolStudentParentMapper.insert(schoolStudentParent);
    }

    /**
     *
     * @author lyric
     * @date 2022/11/19 20:36
     * 修改学生家长
     */
    @Override
    public int updateParent(Long studentId, SchoolStudentParent schoolStudentParent) {

        /** 校验电话号码唯一性 */
        LambdaQueryWrapper<SchoolStudentParent> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolStudentParent::getId, studentId).eq(SchoolStudentParent::getTelephone, schoolStudentParent.getTelephone());
        SchoolStudentParent parent = schoolStudentParentMapper.selectOne(lqw);
        if (StringUtils.isNotNull(parent) && !parent.getId().equals(schoolStudentParent.getId())) {
            throw new ServiceException("家长手机号已存在");
        }

        if(isNotNull(schoolStudentParent.getRelationship())){
            LambdaQueryWrapper<SchoolStudentParent> byShip = new LambdaQueryWrapper<>();
            byShip.eq(SchoolStudentParent::getStudentId, studentId)
                    .eq(SchoolStudentParent::getRelationship, schoolStudentParent.getRelationship());
            SchoolStudentParent p = schoolStudentParentMapper.selectOne(byShip);
            if (StringUtils.isNotNull(p) && !p.getId().equals(schoolStudentParent.getId())) {
                throw new ServiceException("该关系已存在");
            }
        }

        /** 修改用户表 */
        SysUser user = new SysUser();
        user.setUserId(schoolStudentParent.getUserId());
        user.setUserLoginType(PARENT);
        user.setUserName(schoolStudentParent.getParentName());
        user.setPhonenumber(schoolStudentParent.getTelephone());
        userService.updateUser(user);

        /** 修改家长表 */
        return schoolStudentParentMapper.updateById(schoolStudentParent);
    }

    /**
     * 查询级部工作-所有家长信息(手动过滤)
     * */
    @Override
    public List<SchoolStudentParentVO> getAllParent( List<Long> gradeIdList,SchoolStudentParentVO schoolStudentParentVO) {
       /* List<SchoolStudentParentVO> parentVOList = schoolStudentParentMapper.getAllParent(schoolStudentParentVO);
        Integer gradeValue = gradeValue();
        List<SchoolStudentParentVO> list = new ArrayList<>();
        for (SchoolStudentParentVO studentParentVO : parentVOList) {
            String studentIdCard = studentParentVO.getStuIdCard();
            //通过studentIdCard->classId->gradeId
            LambdaQueryWrapper<SchoolStudent> lqw = new LambdaQueryWrapper<>();
            lqw.eq(isNotBlank(studentIdCard), SchoolStudent::getIdCard, studentIdCard);
            SchoolStudent student = schoolStudentMapper.selectOne(lqw);
            SchoolClass schoolClass= schoolClassMapper.selectById(student.getClassId());
            if (gradeValue.equals(schoolClass.getGradeValue())){
                list.add(studentParentVO);
            }
        }
        return list;*/
       /* List<SchoolStudentParentVO> list = schoolStudentParentMapper.getParentVoByGradeId(gradeId);
        return list;*/

        return new ArrayList<>();
    }

    //教务管理->全部家长信息查询
    @Override
    public List<SchoolStudentParentVO> selectAllParent(SchoolStudentParentVO schoolStudentParentVO) {
        return  schoolStudentParentMapper.getAllParent(schoolStudentParentVO);
    }

    //教师工作，级部工作->家长信息查询（根据班级id，查，）
    @Override
    public List<SchoolStudentParentVO> selectTeacherParent(List<Long> classIds, SchoolStudentParentVO schoolStudentParentVO) {
        return schoolStudentParentMapper.selectTeacherParent(schoolStudentParentVO,classIds);
    }

    /**
     * 级部过滤，拿到gradeValue
     * @return
     */
    @Override
    public Integer gradeValue(){
        //通过teacherId去过滤
        Long teacherId = getUserId();
        LambdaQueryWrapper<SchoolGradeMentor> mentorLqw = new LambdaQueryWrapper<>();
        mentorLqw.select(SchoolGradeMentor::getGradeId).eq(SchoolGradeMentor::getTeacherId, teacherId);
        SchoolGradeMentor mentor = schoolGradeMentorMapper.selectOne(mentorLqw);
        //当前登录人不是级部成员
        if(StringUtils.isNull(mentor)){
            return -1;
        }
        SchoolGrade schoolGrade = schoolGradeMapper.selectById(mentor.getGradeId());
        return schoolGrade.getGradeValue();
    }

    @Override
    public String getOpenIdById(Long id) {
        return schoolStudentParentMapper.getOpenIdById(id);
    }
}
