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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.biz.dal.config.RongCloudConfig;
import com.yonge.cooleshow.biz.dal.dao.CourseScheduleStudentPaymentDao;
import com.yonge.cooleshow.biz.dal.dao.ImGroupDao;
import com.yonge.cooleshow.biz.dal.dao.ImGroupMemberAuditDao;
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.enums.ImGroupMemberRoleType;
import com.yonge.cooleshow.biz.dal.enums.ImGroupType;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.toolset.base.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 SysUserService sysUserService;
    @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(ImGroupType.FAN);
        imGroup.setMemberNum(1);
        imGroup.setCreateTime(now);
        imGroup.setUpdateTime(now);
        String imGroupId = UUID.randomUUID() + imGroup.getType().getCode();
        imGroup.setId(imGroupId);
        this.baseMapper.insert(imGroup);
        //处理本地群成员列表
        List<GroupMember> groupMembers = imGroupMemberService.initGroupMember(imGroupId, imGroup.getCreateBy(), true, ImGroupMemberRoleType.TEACHER);
        //创建融云群
        this.rtcCreate(imGroup.getCreateBy(),imGroupId,imGroup.getName());
        //加入融云群
        imGroupMemberService.join(groupMembers,imGroupId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String autoCreate(Long courseGroupId, String courseGroupType) throws Exception {
        //获取课程组
        CourseGroup courseGroup = courseGroupService.getById(courseGroupId);
        if (courseGroup.getTeacherId() == null) {
            return null;
        }
        //获取学员列表
        Set<Long> studentIds = courseScheduleStudentPaymentDao.queryStudentIds(courseGroupId, courseGroupType);
        studentIds.removeAll(Collections.singleton(null));
        if (CollectionUtils.isEmpty(studentIds)) {
            return null;
        }
        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(ImGroupType.COURSE);
        imGroup.setCreateTime(now);
        imGroup.setUpdateTime(now);
        String imGroupId = UUID.randomUUID() + imGroup.getType().getCode();
        imGroup.setId(imGroupId);
        imGroup.setCourseGroupId(courseGroupId);
        this.baseMapper.insert(imGroup);
        //保存老师学员关联的通讯录
        imUserFriendService.saveUserFriend(teacherId, studentIds);
        //处理本地群成员列表
        List<GroupMember> groupMembers = imGroupMemberService.initGroupMember(imGroupId, imGroup.getCreateBy(), true, ImGroupMemberRoleType.TEACHER);
        groupMembers.addAll(imGroupMemberService.initGroupMembers(imGroupId, studentIds, ImGroupMemberRoleType.STUDENT));
        //创建融云群
        this.rtcCreate(courseGroup.getTeacherId(), imGroupId, imGroup.getName());
        //加入融云群
        imGroupMemberService.join(groupMembers, imGroupId);
        return 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 {
        Long createBy = Optional.ofNullable(this.baseMapper.selectById(groupId)).
                map(ImGroup::getCreateBy).
                orElseThrow(() -> new BizException("操作失败：群组不存在"));
        if(!sysUserService.getUserId().equals(createBy)){
            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
    public List<ImGroup> queryAll(ImGroupSearchDto imGroupSearchDto) {
        return baseMapper.findAll(imGroupSearchDto);
    }

    @Override
    public List<ImGroupResultDto> queryTeacherFun(ImGroupSearchDto imGroupSearchDto) {
        imGroupSearchDto.setUserId(sysUserService.getUserId());
        return baseMapper.queryTeacherFun(imGroupSearchDto);
    }

    @Override
    public ImGroup getByCourseGroupId(Long courseGroupId) {
        return this.lambdaQuery()
                .eq(ImGroup::getCourseGroupId,courseGroupId)
                .last("limit 1")
                .one();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void quit(String groupId, Long userId) throws Exception {
        if(imGroupMemberService.getDao().delByGroupIdAndUserId(groupId, userId) < 1){
            throw new BizException("操作失败：用户不在此群组");
        }
        //修改群成员数
        baseMapper.updateMemberNum(groupId);
        GroupModel groupModel = new GroupModel(groupId,0);
        GroupMember[] groupMembers = new GroupMember[]{new GroupMember(userId.toString(),groupId,null)};
        groupModel.setMembers(groupMembers);
        Result result = RongCloudConfig.rongCloud.group.quit(groupModel);
        if(!result.code.equals(200)){
            log.error("退出群聊失败:{}",result.errorMessage);
            throw new BizException("退出群聊失败，请联系管理员");
        }
    }
}

