package yangtz.cs.liu.wechat.service.impl.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.core.utils.HolidayDateUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.MpLoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yangtz.cs.liu.campus.domain.student.SchoolStudent;
import yangtz.cs.liu.campus.domain.student.SchoolStudentParent;
import com.ruoyi.common.core.domain.entity.SchoolTeacher;
import yangtz.cs.liu.campus.mapper.student.SchoolStudentMapper;
import yangtz.cs.liu.campus.mapper.student.SchoolStudentParentMapper;
import yangtz.cs.liu.campus.mapper.teacher.SchoolTeacherMapper;
import yangtz.cs.liu.wechat.domain.WxLoginBody;
import yangtz.cs.liu.wechat.service.api.IWxLoginService;

import static yangtz.cs.liu.wechat.constant.LoginTypeConstant.*;

/**
 * @author lyric
 * @date 2022/10/16 20:31
 */
@Service
public class WxLoginServiceImpl implements IWxLoginService {

    @Autowired
    private SchoolTeacherMapper schoolTeacherMapper;

    @Autowired
    private SchoolStudentParentMapper schoolStudentParentMapper;

    @Autowired
    private SchoolStudentMapper schoolStudentMapper;

    @Autowired
    private SysUserMapper userMapper;


    private Logger log = LoggerFactory.getLogger(WxLoginServiceImpl.class);
    @Override
    public MpLoginUser ddApplogin(WxLoginBody wxLoginBody) {
        MpLoginUser mpLoginUser = null;
        if (TEACHER_LOGIN.equals(wxLoginBody.getType())) {
            SysUser sysUser = new SysUser();
            sysUser.setUserLoginType(TEACHER_LOGIN);
            sysUser.setPhonenumber(wxLoginBody.getPhonenumber());
            SysUser user = userMapper.getUser(sysUser);
            // 教职工登录
            mpLoginUser = loadUserB(wxLoginBody, user);
        } else if (PARENT_LOGIN.equals(wxLoginBody.getType())) {
            SchoolStudentParent schoolStudentParent = schoolStudentParentMapper.selectUserByParentTel(wxLoginBody.getParentTelephone());
            if(StringUtils.isNull(schoolStudentParent)){
                throw new ServiceException("家长手机号输入有误，请检查后重试");
            }
            SysUser sysUser = new SysUser();
            sysUser.setUserLoginType(PARENT_LOGIN);
            sysUser.setPhonenumber(wxLoginBody.getPhonenumber());
            SysUser user = userMapper.getUser(sysUser);
            mpLoginUser = loadUserByParent(wxLoginBody, schoolStudentParent,user);
        }
        return mpLoginUser;
    }

    public MpLoginUser loadUserB(WxLoginBody wxLoginBody, SysUser user) {
        if (StringUtils.isNull(user)) {
            throw new ServiceException("登录用户：" + wxLoginBody.getPhonenumber() + " 不存在");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getDelFlag())) {
            throw new ServiceException("对不起，登录用户：" + wxLoginBody.getPhonenumber() + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            throw new ServiceException("对不起，登录用户：" + wxLoginBody.getPhonenumber() + " 已停用");
        }
        LambdaQueryWrapper<SchoolTeacher> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolTeacher::getId, user.getUserId());
        SchoolTeacher schoolTeacher = schoolTeacherMapper.selectOne(lqw);
        MpLoginUser loginUser = new MpLoginUser();
        loginUser.setOpenId(wxLoginBody.getOpenId());
        loginUser.setType(TEACHER_LOGIN);
        loginUser.setEmployeeType(user.getEmployeeType());
        loginUser.setUserId(user.getUserId());
        loginUser.setTeacherId(schoolTeacher.getId());
        loginUser.setTeacherName(schoolTeacher.getTeacherName());
        loginUser.setTeacherIdCard(schoolTeacher.getIdCard());
        loginUser.setTeacherPhonenumber(schoolTeacher.getTeacherTel());
        loginUser.setAvatar(user.getAvatar());

        /** 更新老师openId */
        schoolTeacher.setOpenId(wxLoginBody.getOpenId());
        schoolTeacherMapper.updateById(schoolTeacher);

        /** 更新用户表openId */
        SysUser sysUser = new SysUser();
        sysUser.setUserId(user.getUserId());
        sysUser.setOpenId(wxLoginBody.getOpenId());
        userMapper.updateUser(sysUser);

        return loginUser;
    }
    @Override
    public MpLoginUser login(WxLoginBody wxLoginBody) {
        MpLoginUser mpLoginUser = null;
        if (TEACHER_LOGIN.equals(wxLoginBody.getType())) {
            SysUser sysUser = new SysUser();
            sysUser.setUserLoginType(TEACHER_LOGIN);
            sysUser.setPhonenumber(wxLoginBody.getPhonenumber());
            SysUser user = userMapper.getUser(sysUser);
            // 教职工登录
            mpLoginUser = loadUserByTeacher(wxLoginBody, user);
        } else if (PARENT_LOGIN.equals(wxLoginBody.getType())) {
            //当前家长登录用手机号密码登录
            SchoolStudentParent schoolStudentParent = schoolStudentParentMapper.selectUserByParentTel(wxLoginBody.getParentTelephone());
            if(StringUtils.isNull(schoolStudentParent)){
                throw new ServiceException("家长信息不存在，请检查后重试");
            }
            SysUser sysUser = new SysUser();
            sysUser.setUserLoginType(PARENT_LOGIN);
            sysUser.setPhonenumber(wxLoginBody.getParentTelephone());
            SysUser user = userMapper.getUser(sysUser);
            mpLoginUser = loadUserByParent(wxLoginBody, schoolStudentParent,user);
        }
        return mpLoginUser;
    }

    public MpLoginUser loadUserByTeacher(WxLoginBody wxLoginBody, SysUser user) {
        if (StringUtils.isNull(user)) {
            throw new ServiceException("登录用户：" + wxLoginBody.getPhonenumber() + " 不存在");
        }
        if (!SecurityUtils.matchesPassword(wxLoginBody.getPassword(), user.getPassword())) {
            throw new ServiceException("密码错误");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getDelFlag())) {
            throw new ServiceException("对不起，登录用户：" + wxLoginBody.getPhonenumber() + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            throw new ServiceException("对不起，登录用户：" + wxLoginBody.getPhonenumber() + " 已停用");
        }
        LambdaQueryWrapper<SchoolTeacher> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolTeacher::getId, user.getUserId());
        SchoolTeacher schoolTeacher = schoolTeacherMapper.selectOne(lqw);
        MpLoginUser loginUser = new MpLoginUser();
        loginUser.setOpenId(wxLoginBody.getOpenId());
        loginUser.setType(TEACHER_LOGIN);
        loginUser.setEmployeeType(user.getEmployeeType());
        loginUser.setUserId(user.getUserId());
        loginUser.setTeacherId(schoolTeacher.getId());
        loginUser.setTeacherName(schoolTeacher.getTeacherName());
        loginUser.setTeacherIdCard(schoolTeacher.getIdCard());
        loginUser.setTeacherPhonenumber(schoolTeacher.getTeacherTel());
        loginUser.setAvatar(user.getAvatar());

        /** 更新老师openId */
        schoolTeacher.setOpenId(wxLoginBody.getOpenId());
        schoolTeacherMapper.updateById(schoolTeacher);

        /** 更新用户表openId */
        SysUser sysUser = new SysUser();
        sysUser.setUserId(user.getUserId());
        sysUser.setOpenId(wxLoginBody.getOpenId());
        userMapper.updateUser(sysUser);

        return loginUser;
    }

//    public MpLoginUser loadUserByTeacher(WxLoginBody wxLoginBody, SchoolTeacher schoolTeacher) {
//        String teacherName = wxLoginBody.getTeacherName();
//        if (StringUtils.isNull(schoolTeacher)) {
//            throw new ServiceException("登录用户：" + teacherName + " 不存在");
//        } else if (UserStatus.DISABLE.getCode().equals(schoolTeacher.getDelFlag())) {
//            throw new ServiceException("对不起，登录用户：" + teacherName + " 已停用");
//        } else if (!schoolTeacher.getTeacherName().equals(teacherName)) {
//            throw new ServiceException("对不起，登录用户：" + teacherName + " 查询失败");
//        } else if (schoolTeacher.getTeacherName().equals(teacherName)) {
//            MpLoginUser user = new MpLoginUser();
//            user.setOpenId(schoolTeacher.getOpenId());
//            user.setType(TEACHER_LOGIN);
//            user.setTeacherId(schoolTeacher.getId());
//            user.setTeacherName(schoolTeacher.getTeacherName());
//            user.setTeacherIdCard(schoolTeacher.getIdCard());
//
//            //更新老师openId
//            SchoolTeacher teacher = new SchoolTeacher();
//            teacher.setId(schoolTeacher.getId());
//            teacher.setOpenId(wxLoginBody.getOpenId());
//            schoolTeacherMapper.updateById(teacher);
//
//            return user;
//        } else {
//            return null;
//        }
//    }

    public MpLoginUser loadUserByParent(WxLoginBody loginBody, SchoolStudentParent schoolStudentParent, SysUser users) {
        String parentName = loginBody.getParentName();
        SchoolStudent schoolStudent = schoolStudentMapper.selectById(schoolStudentParent.getStudentId());
        if (!SecurityUtils.matchesPassword(loginBody.getPassword(), users.getPassword())) {
            throw new ServiceException("密码错误");
        }
         if (UserStatus.DISABLE.getCode().equals(schoolStudent.getDelFlag())) {
            throw new ServiceException("对不起，您的账号：" + parentName + " 已停用");
        }else if(GRADUATION.equals(schoolStudent.getStudentStatus())){
            throw new ServiceException("学生姓名：" + loginBody.getStudentName() + " 已毕业，无法登陆");
        } else if (schoolStudent.getId().equals(schoolStudentParent.getStudentId())) {
            //判断学生是否处于毕业，但学生表学生状态没有改，根据学生届/级enrollment_year来进行判断
            if(StringUtils.isNotNull(schoolStudent.getEnrollmentYear()) && !"".equals(schoolStudent.getEnrollmentYear())){
                boolean flag = HolidayDateUtil.isGraduation(schoolStudent.getEnrollmentYear());
                //flag值为TRUE表示学生已毕业
                if(flag){
                    schoolStudent.setStudentStatus(GRADUATION);
                    schoolStudentMapper.updateById(schoolStudent);
                    throw new ServiceException("学生姓名：" + loginBody.getStudentName() + " 已毕业，无法登陆");
                }
            }
            MpLoginUser user = new MpLoginUser();
            user.setOpenId(loginBody.getOpenId());
            user.setType(PARENT_LOGIN);
            user.setParentId(schoolStudentParent.getId());
            user.setUserId(schoolStudentParent.getUserId());
            user.setStudentId(schoolStudent.getId());
            user.setParentName(schoolStudentParent.getParentName());
            user.setStudentName(schoolStudent.getStudentName());
            user.setAvatar(schoolStudent.getAvatar());
            //更新家长openId
//            SchoolStudentParent parent = new SchoolStudentParent();
//            parent.setId(schoolStudentParent.getId());
//            parent.setOpenId(loginBody.getOpenId());
//            schoolStudentParentMapper.updateById(parent);
//
//            /** 更新用户表openId */
//            SysUser u = new SysUser();
//            u.setUserId(schoolStudentParent.getUserId());
//            u.setOpenId(loginBody.getOpenId());
//            userMapper.updateUser(u);
            return user;
        } else {
            return null;
        }
    }
}
