package com.yonge.cooleshow.biz.dal.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.biz.dal.entity.StudentTotal;
import com.yonge.cooleshow.biz.dal.entity.TeacherTotal;
import com.yonge.cooleshow.biz.dal.service.StudentTotalService;
import com.yonge.cooleshow.biz.dal.service.TeacherTotalService;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yonge.cooleshow.biz.dal.entity.StudentStar;
import com.yonge.cooleshow.biz.dal.dao.StudentStarDao;
import com.yonge.cooleshow.biz.dal.service.StudentStarService;


@Service
public class StudentStarServiceImpl extends ServiceImpl<StudentStarDao, StudentStar> implements StudentStarService {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private StudentTotalService studentTotalService;
    @Autowired
    private TeacherTotalService teacherTotalService;

    @Override
    public StudentStar getByStudentIdAndTeacherId(Long studentId, Long teacherId) {
        return baseMapper.getByStudentIdAndTeacherId(studentId, teacherId);
    }

    @Override
    public HttpResponseResult<Boolean> starOrUnStar(Long studentId, Long teacherId, YesOrNoEnum starStatus) {
        StudentStar studentStar = getByStudentIdAndTeacherId(studentId, teacherId);
        StudentTotal studentTotal = studentTotalService.getTotalById(studentId);
        TeacherTotal teacherTotal = teacherTotalService.getTotalById(teacherId);
        if (YesOrNoEnum.YES.equals(starStatus) && null == studentStar) {
            studentStar = new StudentStar();
            studentStar.setStudentId(studentId);
            studentStar.setTeacherId(teacherId);
            save(studentStar);
            studentTotal.setStarTeacherNum(studentTotal.getStarTeacherNum() + 1);
            teacherTotal.setFansNum(teacherTotal.getFansNum() + 1);
        } else if (YesOrNoEnum.NO.equals(starStatus) && null != studentStar) {
            remove(Wrappers.<StudentStar>lambdaQuery()
                    .eq(StudentStar::getStudentId, studentId)
                    .eq(StudentStar::getTeacherId, teacherId)
            );
            studentTotal.setStarTeacherNum(studentTotal.getStarTeacherNum() > 0 ? (studentTotal.getStarTeacherNum() - 1) : 0);
            teacherTotal.setFansNum(teacherTotal.getFansNum() > 0 ? (teacherTotal.getFansNum() - 1) : 0);
        }
        studentTotalService.updateTotalCache(studentTotal);
        teacherTotalService.updateTotalCache(teacherTotal);
        return HttpResponseResult.succeed(true);
    }
}