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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.config.RongCloudConfig;
import com.yonge.cooleshow.biz.dal.dao.*;
import com.yonge.cooleshow.biz.dal.dto.ImGroupResultDto;
import com.yonge.cooleshow.biz.dal.dto.ImGroupSearchDto;
import com.yonge.cooleshow.biz.dal.entity.CourseGroup;
import com.yonge.cooleshow.biz.dal.entity.ImGroup;
import com.yonge.cooleshow.biz.dal.entity.ImGroupMember;
import com.yonge.cooleshow.biz.dal.service.CourseGroupService;
import com.yonge.cooleshow.biz.dal.service.ImGroupMemberService;
import com.yonge.cooleshow.biz.dal.service.ImGroupService;
import com.yonge.cooleshow.biz.dal.service.ImUserFriendService;
import com.yonge.cooleshow.common.exception.BizException;
import io.rong.models.Result;
import io.rong.models.group.GroupMember;
import io.rong.models.group.GroupModel;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 即时通讯群组(ImGroup)表服务实现类
 *
 * @author zx
 * @since 2022-03-22 10:45:57
 */
@Service("imGroupService")
public class ImGroupServiceImpl extends ServiceImpl<ImGroupDao, ImGroup> implements ImGroupService {

    private final static Logger log = LoggerFactory.getLogger(ImGroupServiceImpl.class);

    @Resource
    private CourseGroupService courseGroupService;
    @Resource
    private ImUserFriendService imUserFriendService;
    @Resource
    private ImGroupMemberService imGroupMemberService;
    @Resource
    private ImGroupMemberAuditDao imGroupMemberAuditDao;
    @Resource
    private SysUserFeignService sysUserFeignService;
    @Resource
    private CourseScheduleStudentPaymentDao courseScheduleStudentPaymentDao;

    @Override
    public ImGroupDao getDao() {
        return this.baseMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(ImGroup imGroup) throws Exception {
        //创建本地群聊
        Date now = new Date();
        imGroup.setType(ImGroup.ImGroupType.FAN);
        imGroup.setMemberNum(1);
        imGroup.setCreateTime(now);
        imGroup.setUpdateTime(now);
        String imGroupId = UUID.randomUUID().toString() + imGroup.getType().getCode();
        imGroup.setId(imGroupId);
        this.baseMapper.insert(imGroup);
        //处理本地群成员列表
        List<GroupMember> groupMembers = imGroupMemberService.initGroupMember(imGroupId, imGroup.getCreateBy(), true, ImGroupMember.ImGroupMemberRoleType.TEACHER);
        //创建融云群
        this.rtcCreate(imGroup.getCreateBy(),imGroupId,imGroup.getName());
        //加入融云群
        imGroupMemberService.join(groupMembers,imGroupId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void autoCreate(Long courseGroupId,String courseGroupType) throws Exception {
        //获取课程组
        CourseGroup courseGroup = courseGroupService.getById(courseGroupId);
        if(courseGroup.getTeacherId() == null){
            return;
        }
        //获取学员列表
        Set<Long> studentIds = courseScheduleStudentPaymentDao.queryStudentIds(courseGroupId, courseGroupType);
        studentIds.removeAll(Collections.singleton(null));
        if(CollectionUtils.isEmpty(studentIds)){
            return;
        }
        Date now = new Date();
        Long teacherId = courseGroup.getTeacherId();
        //创建群聊
        ImGroup imGroup = new ImGroup();
        imGroup.setCreateBy(teacherId);
        imGroup.setAutoPassFlag(false);
        imGroup.setMemberNum(studentIds.size() + 1);
        imGroup.setName(courseGroup.getName());
        imGroup.setType(ImGroup.ImGroupType.COURSE);
        imGroup.setCreateTime(now);
        imGroup.setUpdateTime(now);
        String imGroupId = UUID.randomUUID().toString() + imGroup.getType().getCode();
        imGroup.setId(imGroupId);
        this.baseMapper.insert(imGroup);
        //保存老师学员关联的通讯录
        imUserFriendService.saveUserFriend(teacherId,studentIds);
        //处理本地群成员列表
        List<GroupMember> groupMembers = imGroupMemberService.initGroupMember(imGroupId, imGroup.getCreateBy(), true, ImGroupMember.ImGroupMemberRoleType.TEACHER);
        groupMembers.addAll(imGroupMemberService.initGroupMembers(imGroupId,studentIds,ImGroupMember.ImGroupMemberRoleType.STUDENT));
        //创建融云群
        this.rtcCreate(courseGroup.getTeacherId(),imGroupId,imGroup.getName());
        //加入融云群
        imGroupMemberService.join(groupMembers,imGroupId);
    }

    //创建融云群
    private void rtcCreate(Long userId,String imGroupId,String imGroupName) throws Exception {
        //创建融云群
        GroupMember[] groupMembers = new GroupMember[]{new GroupMember(userId.toString(),imGroupId,null)};
        GroupModel groupModel = new GroupModel(imGroupId,0);
        groupModel.setMembers(groupMembers);
        groupModel.setName(imGroupName);
        Result result = RongCloudConfig.rongCloud.group.create(groupModel);
        if(!result.code.equals(200)){
            log.error("创建群聊失败:{}",result.errorMessage);
            throw new BizException("创建群聊失败，请联系管理员");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dismiss(String groupId) throws Exception {
        ImGroup imGroup = this.baseMapper.selectById(groupId);
        if(Objects.isNull(imGroup)){
            throw new BizException("操作失败：群组不存在");
        }
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(!sysUser.getId().equals(imGroup.getCreateBy())){
            throw new BizException("操作失败：您没有操作权限");
        }
        //删除入群申请
        imGroupMemberAuditDao.delByGroupId(groupId);
        //获取所有群成员
        List<GroupMember> groupMembers = imGroupMemberService.getDao().queryGroupMember(groupId);
        //销毁成功，删除群
        this.baseMapper.deleteById(groupId);
        //删除群成员
        imGroupMemberService.delByGroupId(groupId);
        //解散融云群
        GroupModel groupModel = new GroupModel(groupId,0);
        GroupMember[] groupMembersArr = groupMembers.toArray(new GroupMember[groupMembers.size()]);
        groupModel.setMembers(groupMembersArr);
        Result result = RongCloudConfig.rongCloud.group.dismiss(groupModel);
        if(!result.code.equals(200)){
            log.error("解散群聊失败:{}",result.errorMessage);
            throw new BizException("解散群聊失败，请联系管理员");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncGroupMemberNum(String groupId) throws Exception {
        ImGroup imGroup = baseMapper.selectById(groupId);
        Integer memberNum = imGroupMemberService.getBaseMapper().
                selectCount(new QueryWrapper<ImGroupMember>().eq("group_id_",groupId));
        imGroup.setMemberNum(memberNum);
        baseMapper.updateById(imGroup);
    }

    @Override
    public List<ImGroup> queryAll(ImGroupSearchDto imGroupSearchDto) {
        return baseMapper.findAll(imGroupSearchDto);
    }

    @Override
    public List<ImGroupResultDto> queryTeacherFun(ImGroupSearchDto imGroupSearchDto) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        imGroupSearchDto.setUserId(sysUser.getId());
        return baseMapper.queryTeacherFun(imGroupSearchDto);
    }
}

