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.ImGroupDao;
import com.yonge.cooleshow.biz.dal.dao.ImGroupMemberDao;
import com.yonge.cooleshow.biz.dal.dao.TeacherDao;
import com.yonge.cooleshow.biz.dal.dto.BasicUserInfo;
import com.yonge.cooleshow.biz.dal.entity.ImGroupMember;
import com.yonge.cooleshow.biz.dal.enums.ImGroupMemberRoleType;
import com.yonge.cooleshow.biz.dal.service.ImGroupMemberService;
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.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 群成员表(ImGroupMember)表服务实现类
 *
 * @author zx
 * @since 2022-03-22 10:45:58
 */
@Service("imGroupMemberService")
public class ImGroupMemberServiceImpl extends ServiceImpl<ImGroupMemberDao, ImGroupMember> implements ImGroupMemberService {

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

    @Resource
    private TeacherDao teacherDao;
    @Resource
    private ImGroupDao imGroupDao;

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertBatch(List<ImGroupMember> imGroupMembers) {
        if(CollectionUtils.isEmpty(imGroupMembers)){
            throw new BizException("群成员列表不可为空");
        }
        this.baseMapper.insertBatch(imGroupMembers);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<GroupMember> initGroupMember(String imGroupId, Long userId, Boolean isAdmin, ImGroupMemberRoleType roleType){
        //记录群成员
        BasicUserInfo basicUserInfo = teacherDao.getBasicUserInfo(userId);
        ImGroupMember imGroupMember = new ImGroupMember(imGroupId,userId,basicUserInfo.getUsername(),basicUserInfo.getAvatar(), isAdmin, roleType);
        Date date = new Date();
        imGroupMember.setCreateTime(date);
        imGroupMember.setUpdateTime(date);
        this.baseMapper.insert(imGroupMember);
        //加入融云群
        List<GroupMember> groupMemberList = new ArrayList<>();
        groupMemberList.add(new GroupMember(userId.toString(),imGroupId,null));
        return groupMemberList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<GroupMember> initGroupMembers(String imGroupId, Set<Long> userIds, ImGroupMemberRoleType roleType){
        //记录群成员
        List<ImGroupMember> imGroupMembers = baseMapper.initImGroupMember(imGroupId,userIds,roleType.getCode());
        if(CollectionUtils.isNotEmpty(imGroupMembers)){
            baseMapper.insertBatch(imGroupMembers);
            //加入融云群
            Function<Long,GroupMember> func = (userId) -> new GroupMember(userId.toString(),imGroupId,null);
            return userIds.stream().map(func).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void join(List<GroupMember> groupMemberList,String imGroupId) throws Exception {
        GroupMember[] groupMembers = groupMemberList.toArray(new GroupMember[groupMemberList.size()]);
        GroupModel groupModel = new GroupModel(imGroupId, 0);
        groupModel.setMembers(groupMembers);
        groupModel.setName(imGroupDao.selectById(imGroupId).getName());
        Result result = RongCloudConfig.rongCloud.group.join(groupModel);
        if(!result.code.equals(200)){
            log.error("加入群组失败:{}",result.errorMessage);
            throw new BizException("加入群组失败：请联系管理员");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delByGroupId(String groupId) {
        this.baseMapper.delByGroupId(groupId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ImGroupMember getUserDetail(Long userId, String groupId) {
        ImGroupMember imGroupMember = baseMapper.findByUserIdAndGroupId(userId,groupId);
        BasicUserInfo basicUserInfo = teacherDao.getBasicUserInfo(userId);
        if(Objects.isNull(imGroupMember)){
            imGroupMember = new ImGroupMember();
            imGroupMember.setGroupId(groupId);
            imGroupMember.setUserId(userId);
        }
        //更新当前用户关联的该用户的详情信息
        imGroupMember.setNickname(basicUserInfo.getUsername());
        imGroupMember.setAvatar(basicUserInfo.getAvatar());
        if(imGroupMember.getId() != null){
            imGroupMember.setUpdateTime(new Date());
            baseMapper.updateById(imGroupMember);
        }
        return imGroupMember;
    }

    @Transactional(rollbackFor = Exception.class)
    public void startTransactional(Runnable runnable){
        runnable.run();
    }
}

