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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.biz.dal.entity.TeacherTotal;
import com.yonge.cooleshow.biz.dal.enums.CacheNameEnum;
import com.yonge.cooleshow.biz.dal.enums.YesOrNoEnum;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
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;
    @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);
        TeacherTotal total = (TeacherTotal) redissonClient.getBucket(CacheNameEnum.TEACHER_TOTAL.getRedisKey(teacherId)).get();

        if (YesOrNoEnum.YES.equals(starStatus) && null == studentStar) {
            studentStar = new StudentStar();
            studentStar.setStudentId(studentId);
            studentStar.setTeacherId(teacherId);
            save(studentStar);
            total.setFansNum(total.getFansNum() + 1);
        } else if (YesOrNoEnum.NO.equals(starStatus) && null != studentStar) {
            remove(Wrappers.<StudentStar>lambdaQuery()
                    .eq(StudentStar::getStudentId, studentId)
                    .eq(StudentStar::getTeacherId, teacherId)
            );
            total.setFansNum(total.getFansNum() - 1);
        }
        redissonClient.getBucket(CacheNameEnum.TEACHER_TOTAL.getRedisKey(teacherId))
                .set(total);
        return HttpResponseResult.succeed(true);
    }
}