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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.microsvc.toolkit.middleware.im.ImPluginContext;
import com.microsvc.toolkit.middleware.im.impl.TencentCloudImPlugin;
import com.microsvc.toolkit.middleware.im.message.ETencentMessage;
import com.microsvc.toolkit.middleware.im.message.MessageWrapper;
import com.microsvc.toolkit.middleware.im.message.TencentRequest;
import com.microsvc.toolkit.middleware.im.message.TencentWrapper;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.auth.config.CustomerServiceConfig;
import com.yonge.cooleshow.biz.dal.dao.ImUserFriendDao;
import com.yonge.cooleshow.biz.dal.dao.StudentDao;
import com.yonge.cooleshow.biz.dal.dao.TeacherDao;
import com.yonge.cooleshow.biz.dal.dto.BasicUserInfo;
import com.yonge.cooleshow.biz.dal.entity.ImUserFriend;
import com.yonge.cooleshow.biz.dal.entity.Student;
import com.yonge.cooleshow.biz.dal.entity.Subject;
import com.yonge.cooleshow.biz.dal.entity.Teacher;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.MK;
import com.yonge.cooleshow.biz.dal.enums.im.EImUserFriendSourceForm;
import com.yonge.cooleshow.biz.dal.mapper.SysUserMapper;
import com.yonge.cooleshow.biz.dal.service.ImGroupService;
import com.yonge.cooleshow.biz.dal.service.ImUserFriendService;
import com.yonge.cooleshow.biz.dal.service.SubjectService;
import com.yonge.cooleshow.biz.dal.service.SysConfigService;
import com.yonge.cooleshow.biz.dal.service.VipCardRecordService;
import com.yonge.cooleshow.biz.dal.vo.StudentVo;
import com.yonge.cooleshow.biz.dal.vo.TeacherVo;
import com.yonge.cooleshow.biz.dal.vo.im.ImUserFriendVO;
import com.yonge.cooleshow.biz.dal.wrapper.VipCardRecordWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.im.CustomerService;
import com.yonge.cooleshow.biz.dal.wrapper.im.ImUserWrapper;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.base.util.ImUtil;
import io.rong.messages.BaseMessage;
import io.rong.messages.ImgMessage;
import io.rong.messages.TxtMessage;
import io.rong.models.message.PushExt;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 用户通讯录表(ImUserFriend)表服务实现类
 *
 * @author zx
 * @since 2022-03-22 10:46:00
 */
@Slf4j
@Service("imUserFriendService")
public class ImUserFriendServiceImpl extends ServiceImpl<ImUserFriendDao, ImUserFriend> implements ImUserFriendService {

    @Resource
    private TeacherDao teacherDao;
    @Resource
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private CustomerServiceConfig customerServiceConfig;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ImGroupService imGroupService;

    @Autowired
    private ImPluginContext imPluginContext;
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private VipCardRecordService vipCardRecordService;
    @Autowired
    private SysConfigService sysConfigService;
    @Override
    public ImUserFriendDao getDao() {
        return this.baseMapper;
    }

    /**
     *
     * @param teacherId 老师ID
     * @param studentIds  学生列表
     * @param sourceForm 建立关系方式，TEACHER：已老师身份添加或更新关系，CUSTOMER：以客服身份添加或者更新关系
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserFriend(Long teacherId, Set<Long> studentIds, EImUserFriendSourceForm sourceForm) {
        if (CollectionUtils.isEmpty(studentIds)) {
            return;
        }
        Date now = new Date();
        //老师添加学员联系人
        List<ImUserFriend> imUserFriends = new ArrayList<>();
        BasicUserInfo teacherInfo = teacherDao.getBasicUserInfo(teacherId);
        List<BasicUserInfo> studentInfos = teacherDao.findBasicUserInfo(studentIds);
        if (teacherInfo == null || studentInfos.isEmpty()) {
            // 过滤注销状态的账号
            return;
        }
        studentInfos.add(teacherInfo);
        Map<Long, List<BasicUserInfo>> basicUserInfoMap =
                studentInfos.stream().collect(Collectors.groupingBy(BasicUserInfo::getUserId));
        for (Long studentId : studentIds) {
            //老师关联学员
            ImUserFriend teacherFriend = new ImUserFriend();
            //学员关联老师
            ImUserFriend studentFriend = new ImUserFriend();
            List<BasicUserInfo> basicUserInfos = basicUserInfoMap.get(studentId);
            if (CollectionUtils.isNotEmpty(basicUserInfos)) {
                BasicUserInfo info = basicUserInfos.get(0);
                teacherFriend.setFriendAvatar(info.getAvatar());
                teacherFriend.setFriendNickname(info.getUsername());

                studentFriend.setFriendAvatar(teacherInfo.getAvatar());
                studentFriend.setFriendNickname(teacherInfo.getUsername());
            }
            teacherFriend.setClientType(ClientEnum.TEACHER);
            teacherFriend.setFriendId(studentId);
            teacherFriend.setFriendType(ClientEnum.STUDENT);
            teacherFriend.setUserId(teacherId);
            teacherFriend.setSourceForm(sourceForm);
            teacherFriend.setCreateTime(now);
            teacherFriend.setUpdateTime(now);

            studentFriend.setClientType(ClientEnum.STUDENT);
            studentFriend.setFriendId(teacherId);
            studentFriend.setFriendType(ClientEnum.TEACHER);
            studentFriend.setUserId(studentId);
            studentFriend.setSourceForm(sourceForm);
            studentFriend.setCreateTime(now);
            studentFriend.setUpdateTime(now);
            imUserFriends.add(teacherFriend);
            imUserFriends.add(studentFriend);
        }
        baseMapper.insertBatch(imUserFriends);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserTeacherFriend(Long teacherId, Set<Long> teacherIds, EImUserFriendSourceForm sourceForm) {
        if (CollectionUtils.isEmpty(teacherIds)) {
            return;
        }
        Date now = new Date();
        //老师添加学员联系人
        List<ImUserFriend> imUserFriends = new ArrayList<>();
        BasicUserInfo teacherInfo = teacherDao.getBasicUserInfo(teacherId);
        List<BasicUserInfo> studentInfos = teacherDao.findBasicUserInfo(teacherIds);
        studentInfos.add(teacherInfo);
        Map<Long, List<BasicUserInfo>> basicUserInfoMap =
                studentInfos.stream().collect(Collectors.groupingBy(BasicUserInfo::getUserId));
        for (Long studentId : teacherIds) {
            //老师关联学员
            ImUserFriend teacherFriend = new ImUserFriend();
            //学员关联老师
            ImUserFriend studentFriend = new ImUserFriend();
            List<BasicUserInfo> basicUserInfos = basicUserInfoMap.get(studentId);
            if (CollectionUtils.isNotEmpty(basicUserInfos)) {
                BasicUserInfo info = basicUserInfos.get(0);
                teacherFriend.setFriendAvatar(info.getAvatar());
                teacherFriend.setFriendNickname(info.getUsername());

                studentFriend.setFriendAvatar(teacherInfo.getAvatar());
                studentFriend.setFriendNickname(teacherInfo.getUsername());
            }
            teacherFriend.setClientType(ClientEnum.TEACHER);
            teacherFriend.setFriendId(studentId);
            teacherFriend.setFriendType(ClientEnum.TEACHER);
            teacherFriend.setUserId(teacherId);
            teacherFriend.setSourceForm(sourceForm);
            teacherFriend.setCreateTime(now);
            teacherFriend.setUpdateTime(now);

            studentFriend.setClientType(ClientEnum.TEACHER);
            studentFriend.setFriendId(teacherId);
            studentFriend.setFriendType(ClientEnum.TEACHER);
            studentFriend.setUserId(studentId);
            studentFriend.setSourceForm(sourceForm);
            studentFriend.setCreateTime(now);
            studentFriend.setUpdateTime(now);
            imUserFriends.add(teacherFriend);
            imUserFriends.add(studentFriend);
        }
        baseMapper.insertBatch(imUserFriends);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ImUserFriendVO.ImUserFriend getDetail(String imUserId, ClientEnum clientType) {

        // 用户ID
        long userId = Long.parseLong(imGroupService.analysisImUserId(imUserId));

        SysUser sysUser = sysUserFeignService.queryUserInfo();
        BasicUserInfo basicUserInfo = teacherDao.getBasicUserInfo(userId);
        if (basicUserInfo == null) {
            throw new BizException("无效的用户");
        }

        String friendClientType = imGroupService.analysisImUserClient(imUserId);
        ImUserFriend imUserFriend = lambdaQuery()
                .eq(ImUserFriend::getUserId, sysUser.getId())
                .eq(ImUserFriend::getClientType, clientType)
                .eq(ImUserFriend::getFriendId, userId)
                .eq(ImUserFriend::getFriendType, ClientEnum.valueOf(friendClientType))
                .one();
        if (Objects.nonNull(imUserFriend)) {
            //更新当前用户关联的该用户的详情信息
            imUserFriend.setFriendAvatar(basicUserInfo.getAvatar());
            imUserFriend.setFriendNickname(basicUserInfo.getUsername());
            imUserFriend.setUpdateTime(new Date());
            baseMapper.updateById(imUserFriend);

            // 设置融云IM好友ID
            imUserFriend.setImFriendId(imUserId);
        } else {
            // 好友身份类型
            ClientEnum friendType = ClientEnum.TEACHER;
            if (ClientEnum.STUDENT.match(imGroupService.analysisImUserClient(imUserId))) {
                friendType = ClientEnum.STUDENT;
            }
            // 返回当前登录用户信息
            imUserFriend = new ImUserFriend();
            imUserFriend.setFriendAvatar(basicUserInfo.getAvatar());
            imUserFriend.setFriendNickname(basicUserInfo.getUsername());
            imUserFriend.setFriendId(userId);
            imUserFriend.setFriendType(friendType);
            // 设置融云IM好友ID
            imUserFriend.setImFriendId(imUserId);
        }

        ImUserFriendVO.ImUserFriend result = JSON.parseObject(JSON.toJSONString(imUserFriend), ImUserFriendVO.ImUserFriend.class);
        result.setFriendGender(basicUserInfo.getGender());

        if (ClientEnum.STUDENT.getCode().equals(friendClientType)) {
            StudentVo detail = studentDao.detail(userId);
            if (detail != null && StringUtils.isNotEmpty(detail.getSubjectId())) {
                List<Subject> subject = subjectService.findBySubjectByIdList(detail.getSubjectId());
                String subjectName = subject.stream().map(Subject::getName).collect(Collectors.joining("、"));
                result.setFriendSubjectName(subjectName);
            }
        } else if (ClientEnum.TEACHER.getCode().equals(friendClientType)) {
            TeacherVo detail = teacherDao.detail(userId);
            if (detail != null && StringUtils.isNotEmpty(detail.getSubjectId())) {
                List<Subject> subject = subjectService.findBySubjectByIdList(detail.getSubjectId());
                String subjectName = subject.stream().map(Subject::getName).collect(Collectors.joining("、"));
                result.setFriendSubjectName(subjectName);
            }
        }
        VipCardRecordWrapper.UserVip userVip = vipCardRecordService.UserVipInfo(userId, ClientEnum.valueOf(friendClientType));
        result.setUserVip(userVip);
        result.setFriendBirthdate(basicUserInfo.getBirthdate());
        return result;
    }

    /**
     * 获取用户详情
     *
     * @param userId 用户ID
     * @return ImUserFriend
     */
    @Override
    public ImUserFriend getImUserProfile(String userId) {

        try {
            TencentWrapper.UserProfile userProfile = imPluginContext.getPluginService().getUserProfile(userId);
            // 返回当前登录用户信息
            ImUserFriend imUserFriend = new ImUserFriend();
            imUserFriend.setFriendAvatar(userProfile.getAvatar());
            imUserFriend.setFriendNickname(userProfile.getUsername());
            imUserFriend.setFriendId(Long.valueOf(userId));
            imUserFriend.setFriendType(ClientEnum.STUDENT);
            // 设置融云IM好友ID
            imUserFriend.setImFriendId(userId);
            return imUserFriend;
        } catch (Exception e) {
            log.error("getImUserProfile userId={}", userId, e);
        }
        return null;
    }

    /**
     * 新用户自动添加客服
     *
     * @param userId     新用户ID
     * @param friendIds  好友ID,客服ID
     * @param clientType 客户端类型
     * @return Integer
     */
    @Override
    public Integer registerUserBindCustomerService(Long userId, List<Long> friendIds, ClientEnum clientType) {

        // 不在加客服好友
        if (true) {
            // TODO: 忽略后续流程不执行
            return 0;
        }

        if(userId == null || CollectionUtils.isEmpty(friendIds)){
            return 0;
        }

        SysUser sysUser = sysUserMapper.getByUserId(userId);
        try {
            imGroupService.register(sysUser.getId().toString(), clientType, sysUser.getUsername(), sysUser.getAvatar());
            log.info("注册用户成功：" + userId);
        } catch (Exception e) {
            log.error("注册用户失败：" + userId + ",type:" + clientType);
        }
        // 判断是否是同一机构
        EImUserFriendSourceForm sourceForm = EImUserFriendSourceForm.CUSTOMER;
        Teacher customer = teacherDao.selectById(friendIds.get(0));
        if (customer.getTenantId() != null && customer.getTenantId() > 0) {
            if (ClientEnum.STUDENT.equals(clientType)) {
                Student student = studentDao.selectById(userId);
                if (customer.getTenantId().equals(student.getTenantId())) {
                    sourceForm = EImUserFriendSourceForm.TEACHER;

                }
            } else if (ClientEnum.TEACHER.equals(clientType)) {
                Teacher teacher = teacherDao.selectById(userId);
                if (customer.getTenantId().equals(teacher.getTenantId())) {
                    sourceForm = EImUserFriendSourceForm.TEACHER;
                }
            }
        }

        // 添加新用户好友，客服默认为老师身份
        for (Long teacherId : friendIds) {
            if (ClientEnum.STUDENT == clientType) {
                saveUserFriend(teacherId, Sets.newHashSet(userId), sourceForm);
                studentDao.update(null, new UpdateWrapper<Student>().lambda().eq(Student::getUserId, userId).set(Student::getCustomerId, teacherId));
            } else if (ClientEnum.TEACHER == clientType) {
                //saveUserTeacherFriend(teacherId, Sets.newHashSet(userId), sourceForm);
                teacherDao.update(null, new UpdateWrapper<Teacher>().lambda().eq(Teacher::getUserId, userId).set(Teacher::getCustomerId, teacherId));
            }

            // 新注册用户为老师身份时，更新好友关系为老师身份
//            if (ClientEnum.TEACHER == clientType) {
//
//                // 更新我的身份信息
//                imUserFriendService.lambdaUpdate()
//                        .eq(ImUserFriend::getUserId, userId)
//                        .eq(ImUserFriend::getClientType, ClientEnum.STUDENT)
//                        .eq(ImUserFriend::getFriendId, teacherId)
//                        .eq(ImUserFriend::getFriendType, ClientEnum.TEACHER)
//                        .set(ImUserFriend::getClientType, ClientEnum.TEACHER)
//                        .update();
//
//                // 更新客服好友身份信息
//                imUserFriendService.lambdaUpdate()
//                        .eq(ImUserFriend::getUserId, teacherId)
//                        .eq(ImUserFriend::getClientType, ClientEnum.TEACHER)
//                        .eq(ImUserFriend::getFriendId, userId)
//                        .eq(ImUserFriend::getFriendType, ClientEnum.STUDENT)
//                        .set(ImUserFriend::getFriendType, ClientEnum.TEACHER)
//                        .update();
//            }
        }

        try {

            // 设置默认值
            String customerMessage = sysConfigService.findConfigValue(SysConfigConstant.CUSTOMER_SERVICE_ADD_MSG);
            if (StringUtils.isEmpty(customerMessage)) {
                customerMessage = MK.IM_SYS_FRIEND;
            }

            String customerTitle = sysConfigService.findConfigValue(SysConfigConstant.CUSTOMER_SERVICE_ADD_MSG_TITLE);
            if (StringUtils.isEmpty(customerTitle)) {
                customerTitle = MK.IM_SYS_TITLE;
            }

            // 拓展消息
            PushExt pushExt = PushExt.build(customerTitle, 1,
                    new PushExt.HW("channelId", "NORMAL"), new PushExt.VIVO("1"),
                    new PushExt.APNs("", ""),
                    new PushExt.OPPO(""));

            MessageWrapper.PrivateMessage build = MessageWrapper.PrivateMessage.builder()
                    .senderId(imGroupService.getImUserId(friendIds.get(0).toString(),ClientEnum.TEACHER.getCode()))
                    .targetIds(Lists.newArrayList(imGroupService.getImUserId(userId.toString(),clientType.getCode())))
                    //.objectName(txtMessage.getType())
                    //.rongCloueMessage(txtMessage)
                    .pushExt(JSON.toJSONString(pushExt))
                    .includeSender(0)
                    .build();


            if (TencentCloudImPlugin.PLUGIN_NAME.equals(imPluginContext.defaultService())) {
                // 腾讯IM消息
                TencentRequest.MessageBody message = TencentRequest.MessageBody.builder()
                        .msgType(ETencentMessage.TIMTextElem.name())
                        .msgContent(TencentRequest.TextMessageBody.builder().text(customerMessage).build())
                        .build();

                String ret = imPluginContext.getPluginService().sendPrivateMessage(build.objectName(message.getMsgType()).tencentMessage(message));
                log.info("registerUserBindCustomerService GROUP tencentCloud senderId={}, ret={}", build.getSenderId(), ret);
            } else {
                // 融云IM消息
                TxtMessage message = new TxtMessage(customerMessage, "");
                String ret = imPluginContext.getPluginService().sendPrivateMessage(build.objectName(message.getType()).rongCloueMessage(message));
                log.info("registerUserBindCustomerService GROUP rongCloud senderId={}, ret={}", build.getSenderId(), ret);
            }

            /*Boolean ret = imPluginContext.getPluginService().sendPrivateMessage(build);
            log.info("registerUserBindCustomerService GROUP senderId={},data= {} ret={}", userId,build, ret);*/
        } catch (Exception e) {
            log.error("registerUserBindCustomerService userId={}", userId, e);
        }

        return CollectionUtils.size(friendIds);
    }

    /**
     * 与客服建立好友关系时，客服给好友发送消息
     */
    @Override
    public void sendCustomerServiceAddFriendMessage(Long customerServiceId, String sendTitle, String sendMessage, List<Long> friendIds, ClientEnum friendType) {

        if (customerServiceId == null || CollectionUtils.isEmpty(friendIds)) {
            return;
        }

        // 客服不加好友
        if (true) {
            return;
        }

        try {
            if (StringUtils.isEmpty(sendMessage)) {
                sendMessage = MK.IM_SYS_FRIEND;
            }

            if (StringUtils.isEmpty(sendTitle)) {
                sendTitle = MK.IM_SYS_TITLE;
            }

            // 拓展消息
            PushExt pushExt = PushExt.build(sendTitle, 1,
                    new PushExt.HW("channelId", "NORMAL"), new PushExt.VIVO("1"),
                    new PushExt.APNs("", ""),
                    new PushExt.OPPO(""));


            List<String> targetIds = friendIds.stream().map(n -> imGroupService.getImUserId(n, friendType)).collect(Collectors.toList());
            MessageWrapper.PrivateMessage build = MessageWrapper.PrivateMessage.builder()
                    .senderId(imGroupService.getImUserId(customerServiceId.toString(), ClientEnum.TEACHER.getCode()))
                    .targetIds(targetIds)
                    //.objectName(txtMessage.getType())
                    //.rongCloueMessage(txtMessage)
                    .pushExt(JSON.toJSONString(pushExt))
                    .includeSender(0)
                    .build();


            if (TencentCloudImPlugin.PLUGIN_NAME.equals(imPluginContext.defaultService())) {
                // 腾讯IM消息
                TencentRequest.MessageBody message = TencentRequest.MessageBody.builder()
                        .msgType(ETencentMessage.TIMTextElem.name())
                        .msgContent(TencentRequest.TextMessageBody.builder().text(sendMessage).build())
                        .build();

                String ret = imPluginContext.getPluginService().sendPrivateMessage(build.objectName(message.getMsgType()).tencentMessage(message));
                log.info("registerUserBindCustomerService GROUP tencentCloud senderId={}, ret={}", build.getSenderId(), ret);
            } else {
                // 融云IM消息
                TxtMessage message = new TxtMessage(sendMessage, "");
                String ret = imPluginContext.getPluginService().sendPrivateMessage(build.objectName(message.getType()).rongCloueMessage(message));
                log.info("registerUserBindCustomerService GROUP rongCloud senderId={}, ret={}", build.getSenderId(), ret);
            }
        } catch (Exception e) {
            log.error("registerUserBindCustomerService userId={}", customerServiceId, e);
        }
    }

    /**
     * 发送系统客服消息
     *
     * @param sender 发送者
     * @param info   CustomerService.NotifyMessage
     */
    @Override
    public void sendCustomerServiceNotifyMessage(String sender, CustomerService.NotifyMessage info) {

        // 发送者信息
        com.yonge.cooleshow.biz.dal.entity.SysUser senderUser =
                sysUserMapper.selectOne(Wrappers.<com.yonge.cooleshow.biz.dal.entity.SysUser>lambdaQuery()
                .eq(com.yonge.cooleshow.biz.dal.entity.SysUser::getPhone, sender));

        if (Objects.isNull(senderUser)) {
            throw new BizException("无效的客服联系方式");
        }

        List<String> receiveUserIds;
        if (Objects.nonNull(info.getClientType())) {

            receiveUserIds = sysUserMapper.selectMessageReceives(info).stream()
                    .map(x -> String.valueOf(x.getUserId()))
                    .collect(Collectors.toList());
            receiveUserIds = receiveUserIds.stream()
                    .map(x -> imGroupService.getImUserId(x, ClientEnum.STUDENT.getCode()))
                    .collect(Collectors.toList());
        } else {

            LambdaQueryWrapper<com.yonge.cooleshow.biz.dal.entity.SysUser> wrapper =
                    Wrappers.<com.yonge.cooleshow.biz.dal.entity.SysUser>lambdaQuery()
                    .select(com.yonge.cooleshow.biz.dal.entity.SysUser::getId,
                            com.yonge.cooleshow.biz.dal.entity.SysUser::getUsername)
                    .in(com.yonge.cooleshow.biz.dal.entity.SysUser::getPhone, info.getReceives());

            wrapper.last("LIMIT 1500");
            // 接收者信息
            List<com.yonge.cooleshow.biz.dal.entity.SysUser> sysUsers = sysUserMapper.selectList(wrapper);

            // 分批次发送用户消息
            receiveUserIds = sysUsers.stream()
                    .map(com.yonge.cooleshow.biz.dal.entity.SysUser::getId)
                    .map(String::valueOf)
                    .collect(Collectors.toList());
        }

        // 发送图片消息
        ImgMessage imgMessage = new ImgMessage(ImUtil.imageToBase64(info.getImgMessage(), "png"), "", info.getImgUrl());

        // 发送文本消息
        TxtMessage txtMessage = new TxtMessage(info.getTxtMessage(), "");

        List<BaseMessage> baseMessages = Lists.newArrayList(imgMessage, txtMessage);

        List<TencentRequest.MessageBody> tencentMessages = Lists.newArrayList();
        tencentMessages.add(CustomerServiceBatchSendingServiceImpl.getTimTextElem(info.getTxtMessage()));
        tencentMessages.add(CustomerServiceBatchSendingServiceImpl.getTimImageElem(info.getImgMessage()));

        // 拓展消息
        PushExt pushExt = PushExt.build(info.getTitle(), 1,
                new PushExt.HW("channelId", "NORMAL"), new PushExt.VIVO("1"),
                new PushExt.APNs("", ""),
                new PushExt.OPPO(""));

        String senderId = imGroupService.getImUserId(senderUser.getId().toString(), ClientEnum.TEACHER.getCode());
        for (List<String> item : Lists.partition(receiveUserIds, 100)) {

            try {

                // 发送用户IM通知消息
                MessageWrapper.PrivateMessage build = MessageWrapper.PrivateMessage.builder()
                        .senderId(senderId)
                        .targetIds(item)
//                        .objectName(message.getType())
//                        .rongCloueMessage(message)
                        .pushExt(JSON.toJSONString(pushExt))
                        .includeSender(0)
//                        .tencentMessage()
                        .build();

                if (TencentCloudImPlugin.PLUGIN_NAME.equals(imPluginContext.defaultService())) {
                    // 腾讯云消息
                    for (TencentRequest.MessageBody message : tencentMessages) {
                        if (message == null) {
                            continue;
                        }
                        String ret = imPluginContext.getPluginService().sendPrivateMessage(build.objectName(message.getMsgType()).tencentMessage(message));
                        log.info("batchSendPrivateMessage GROUP tencentCloud senderId={}, ret={}", senderId, ret);
                    }
                } else {
                    // 融云消息
                    for (BaseMessage message : baseMessages) {
                        if (message == null){
                            continue;
                        }
                        String ret = imPluginContext.getPluginService().sendPrivateMessage(build.objectName(message.getType()).rongCloueMessage(message));
                        log.info("batchSendPrivateMessage GROUP rongCloud senderId={}, ret={}", senderId, ret);
                    }
                }

            } catch (Exception e) {
                log.error("sendCustomerServiceNotifyMessage senderId={}", senderId, e);
            }

        }

    }


    /**
     * 用户IM好友列表
     *
     * @param clientType 客户端类型
     * @param userId     用户ID
     * @param paramMap   Map<String, Object>
     * @return List<ImUserWrapper.ImUserFriend>
     */
    @Override
    public List<ImUserWrapper.ImUserFriend> findUserAllImFriendInfo(ClientEnum clientType, Long userId, Map<String,
            Object> paramMap) {

        // 用户好友匹配条件
        Object search = paramMap.get("search");

        // 查询用户好友列表
        List<ImUserFriend> records = lambdaQuery()
                .eq(ImUserFriend::getUserId, userId)
                .eq(ImUserFriend::getClientType, clientType)
                .and(Objects.nonNull(search) && StringUtils.isNotEmpty(search.toString()),
                        e -> e.eq(ImUserFriend::getFriendId, search).or().like(ImUserFriend::getFriendNickname, search))
                .orderByDesc(ImUserFriend::getId).list();

        List<ImUserWrapper.ImUserFriend> userFriends = JSON.parseArray(JSON.toJSONString(records),
                ImUserWrapper.ImUserFriend.class);

        // 获取好友ID，查询注销的人，过滤
        if (CollectionUtils.isNotEmpty(userFriends)) {
            List<Long> userIds = userFriends.stream().map(ImUserWrapper.ImUserFriend::getFriendId).collect(Collectors.toList());
            List<com.yonge.cooleshow.biz.dal.entity.SysUser> sysUsers = sysUserMapper.selectBatchIds(userIds);
            List<Long> delUserIds = sysUsers.stream().filter(o -> o.getDelFlag() == 1).map(o -> o.getId()).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(delUserIds)) {
                userFriends = userFriends.stream().filter(o -> !delUserIds.contains(o.getFriendId())).collect(Collectors.toList());
            }
        }

        for (ImUserWrapper.ImUserFriend item : userFriends) {
            if (item.getFriendType() == null) {
                continue;
            }

            item.setImFriendId(imGroupService.getImUserId(String.valueOf(item.getFriendId()),item.getFriendType().getCode()));
        }

        return userFriends;
    }

    /**
     * 删除机构下的好友
     *
     * @param tenantId   机构ID
     * @param userId     用户ID
     * @param clientType 用户类型，处理同账号多角色问题
     */
    @Override
    public void delTeacherFriendByTenantId(Long tenantId, Long userId, String clientType) {
        this.baseMapper.delTeacherFriendByTenantId(tenantId, userId, clientType);
    }

    @Override
    public void delStudentFriendByTenantId(Long tenantId, Long userId, String clientType) {
        this.baseMapper.delStudentFriendByTenantId(tenantId, userId, clientType);
    }

    @Override
    public void refreshCustomer(Long userId, ClientEnum userClientType, List<Long> friendIds, ClientEnum friendClientType) {

        /*this.lambdaUpdate()
                .set(ImUserFriend::getSourceForm, EImUserFriendSourceForm.TEACHER)
                .eq(ImUserFriend::getUserId, userId)
                .eq(ImUserFriend::getClientType, userClientType)
                .in(ImUserFriend::getFriendId, friendIds)
                .eq(ImUserFriend::getFriendType, friendClientType)
                .update();

        this.lambdaUpdate()
                .set(ImUserFriend::getSourceForm, EImUserFriendSourceForm.TEACHER)
                .in(ImUserFriend::getUserId, friendIds)
                .eq(ImUserFriend::getClientType, friendClientType)
                .eq(ImUserFriend::getFriendId, userId)
                .eq(ImUserFriend::getFriendType, userClientType)
                .update();*/
    }

    @Override
    public ImUserFriendVO.ImMessageUser getImMessageUser(String imUserId) {
        long id = Long.parseLong(imGroupService.analysisImUserId(imUserId));

        SysUser byUserId = sysUserMapper.getByUserId(id);

        ImUserFriendVO.ImMessageUser imMessageUser = new ImUserFriendVO.ImMessageUser();
        imMessageUser.setImUserId(imUserId);
        imMessageUser.setDelFlag(true);
        if (byUserId !=null) {
            imMessageUser.setUserId(byUserId.getId());
            imMessageUser.setDelFlag(byUserId.getDelFlag());
            imMessageUser.setUsername(byUserId.getUsername());
            imMessageUser.setAvatar(byUserId.getAvatar());
        }
        return imMessageUser;
    }
}

