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.google.common.collect.Maps;
import com.yonge.cooleshow.biz.dal.entity.*;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.ImGroupMemberRoleType;
import com.yonge.cooleshow.biz.dal.enums.MessageTypeEnum;
import com.yonge.cooleshow.biz.dal.mapper.SysUserMapper;
import com.yonge.cooleshow.biz.dal.service.ImGroupMemberService;
import com.yonge.cooleshow.biz.dal.service.ImGroupService;
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 com.yonge.toolset.base.util.ThreadPool;
import com.yonge.toolset.thirdparty.message.MessageSenderPluginContext;
import io.rong.models.group.GroupMember;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yonge.cooleshow.biz.dal.dao.StudentStarDao;
import com.yonge.cooleshow.biz.dal.service.StudentStarService;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class StudentStarServiceImpl extends ServiceImpl<StudentStarDao, StudentStar> implements StudentStarService {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private StudentTotalService studentTotalService;
    @Autowired
    private TeacherTotalService teacherTotalService;
    @Autowired
    private ImGroupMemberService imGroupMemberService;
    @Autowired
    private ImGroupService imGroupService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysMessageServiceImpl sysMessageService;

    @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);

            // 关注老师，自动加入老师粉丝群
            studentAutoJoinTeacherFansGroup(studentId, teacherId);

        } 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.totalStudentTotalById(studentId);
        teacherTotalService.totalTeacherTotalById(teacherId);
        return HttpResponseResult.succeed(true);
    }

    /**
     * 学生关注老师，自动加入粉丝群
     * @param studentId 学生ID
     * @param teacherId 老师ID
     */
    private void studentAutoJoinTeacherFansGroup(Long studentId, Long teacherId) {
        ThreadPool.getExecutor().submit(() -> {

            try {

                // 查询老师粉丝群
                ImGroup imGroup = imGroupService.lambdaQuery()
                        .eq(ImGroup::getCreateBy, teacherId)
                        .eq(ImGroup::getAutoPassFlag, true)
                        .one();

                if (Objects.nonNull(imGroup)) {

                    //处理本地群成员
                    List<ImGroupMember> groupMembers = imGroupMemberService.initGroupMember(imGroup.getId(),
                            studentId, false, ImGroupMemberRoleType.STUDENT);
                    //同步群成员数量
                    imGroupService.getDao().updateMemberNum(imGroup.getId());

                    //加入融云群
                    imGroupMemberService.join(groupMembers, imGroup.getId());

                    // 发送通知消息
                    SysUser student = sysUserMapper.selectById(studentId);

                    if (Objects.nonNull(student)) {

                        Map<Long, String> receivers = Maps.newHashMap();
                        receivers.put(student.getId(), student.getPhone());

                        sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.STUDENT_AUTOJOIN_FANSGROUP,
                                receivers, null, 0, null, ClientEnum.STUDENT.getCode(), imGroup.getName());
                    }

                }

            } catch (Exception e) {
                log.error("StudentStar studentId={}, teacherId={}", studentId, teacherId);
            }

        });
    }
}