//package com.wecloud.im.ws.strategy.concrete;
//
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.wecloud.im.entity.ImApplication;
//import com.wecloud.im.entity.ImClient;
//import com.wecloud.im.entity.ImConversationMembers;
//import com.wecloud.im.entity.ImInbox;
//import com.wecloud.im.entity.ImMessage;
//import com.wecloud.im.entity.ImMessageOnlineSend;
//import com.wecloud.im.service.ImClientBlacklistService;
//import com.wecloud.im.service.ImClientService;
//import com.wecloud.im.service.ImConversationMembersService;
//import com.wecloud.im.service.ImInboxService;
//import com.wecloud.im.service.ImMessageService;
//import com.wecloud.im.thousandchat.cache.ThousandChatCacheManager;
//import com.wecloud.im.ws.annotation.ImCmdType;
//import com.wecloud.im.ws.enums.WsRequestCmdEnum;
//import com.wecloud.im.ws.enums.WsResponseCmdEnum;
//import com.wecloud.im.ws.model.WsResponse;
//import com.wecloud.im.ws.model.request.ReceiveDataVO;
//import com.wecloud.im.ws.model.request.ReceiveVO;
//import com.wecloud.im.ws.sender.AsyncPush;
//import com.wecloud.im.ws.sender.ChannelSender;
//import com.wecloud.im.ws.strategy.AbstractImCmdStrategy;
//import com.wecloud.utils.JsonUtils;
//import io.geekidea.springbootplus.framework.common.api.ApiCode;
//import io.geekidea.springbootplus.framework.common.api.ApiResult;
//import com.wecloud.utils.SnowflakeUtil;
//import io.netty.channel.ChannelHandlerContext;
//import io.netty.channel.socket.nio.NioSocketChannel;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import java.util.Date;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
///**
// * @Description 处理app数据消息
// */
//@ImCmdType(type = WsRequestCmdEnum.THROUSAND_CHAT)
//@Service
//@Slf4j
//public class ThousandChatStrategy extends AbstractImCmdStrategy {
//
//    public static final String MSG_ID = "msgId";
//
//    @Autowired
//    private ImClientBlacklistService imClientBlacklistService;
//
//    @Autowired
//    private ChannelSender channelSender;
//
//    @Autowired
//    private ImMessageService imMessageService;
//
//    @Autowired
//    private ImInboxService imInboxService;
//
//    @Autowired
//    private ImConversationMembersService imConversationMembersService;
//
//    @Autowired
//    private ImClientService imClientService;
//
//    @Autowired
//    private AsyncPush systemPush;
//    @Autowired
//    private ThousandChatCacheManager thousandChatCacheManager;
//
//    @Override
//    public void process(ImApplication imApplication, ImClient imSender, ChannelHandlerContext ctx, ReceiveVO receiveVO, ReceiveDataVO sysParam) {
//        NioSocketChannel channel = (NioSocketChannel) ctx.channel();
//
//        // 查询该会话所有成员
//        List<ImConversationMembers> membersList = imConversationMembersService.list(
//                new QueryWrapper<ImConversationMembers>().lambda()
//                        .eq(ImConversationMembers::getFkConversationId, sysParam.getToConversation())
//        );
//
//        // 生成消息id
//        long messageId = SnowflakeUtil.getId();
//        // 入库  保存消息至消息表
//        ImMessage imMessage = imMessageService.saveImMessage(imApplication, imSender, messageId, receiveVO, sysParam);
//
//        // 封装响应的实体
//        ImMessageOnlineSend imMessageOnlineSend = new ImMessageOnlineSend();
//        imMessageOnlineSend.setMsgId(imMessage.getId());
//        imMessageOnlineSend.setSender(imSender.getClientId());
//        HashMap<String, Object> content = JsonUtils.decodeJson2Map(JsonUtils.encodeJson(receiveVO.getData()));
//        imMessageOnlineSend.setContent(content);
//        imMessageOnlineSend.setConversationId(sysParam.getToConversation());
//        imMessageOnlineSend.setCreateTime(imMessage.getCreateTime());
//        imMessageOnlineSend.setWithdrawTime(imMessage.getWithdrawTime());
//        imMessageOnlineSend.setWithdraw(imMessage.getWithdraw());
//        imMessageOnlineSend.setEvent(imMessage.getEvent());
//        imMessageOnlineSend.setSystemFlag(imMessage.getSystemFlag());
//        imMessageOnlineSend.setType(sysParam.getType());
//        imMessageOnlineSend.setAt(imMessage.getAt());
//
//        // 在线用户直接发消息
//        Map<String /** ip **/, List<String /** client的主键ID:platform **/>> onlineIpClientMap =
//                thousandChatCacheManager.findOnlineHostsByThousandGroupId(sysParam.getToConversation());
//        //  封装要推给接收方的消息
//        WsResponse<ImMessageOnlineSend> responseModel = new WsResponse<>();
//        responseModel.setCmd(WsResponseCmdEnum.ONLINE_MSG.getCmdCode());
//        ApiResult<Boolean> result = ApiResult.result(ApiCode.SUCCESS);
//        responseModel.setCode(result.getCode());
//        responseModel.setMsg(result.getMessage());
//        responseModel.setData(imMessageOnlineSend);
//        responseModel.setReqId(null);
//
//        onlineIpClientMap.forEach((ip, clientIdAndPlatforms) -> {
//            channelSender.batchSendMsg(responseModel, ip, clientIdAndPlatforms);
//        });
//
//        // 给所有人（在线+离线）遍历发送
//        //todo 需要改成批量
//        for (ImConversationMembers conversationMembers : membersList) {
//            // 入库 保存收件箱
////            long imInboxId = SnowflakeUtil.getId();
////            saveImInbox(imApplication, toConversationId, messageId, conversationMembers, imInboxId);
//
//            // 查询接收方
//            ImClient imClientReceiver = imClientService.getOne(new QueryWrapper<ImClient>().lambda()
//                    .eq(ImClient::getFkAppid, imApplication.getId())
//                    .eq(ImClient::getId, conversationMembers.getFkClientId()));
//            if (imClientReceiver == null) {
//                continue;
//            }
//            // 异步推送系统通知消息
//            systemPush.push(sysParam.getPushVO(), imClientReceiver, imApplication);
//        }
//
//        // 响应发送方消息id等信息
//        response(receiveVO, messageId, channel);
//
//    }
//
//    /**
//     * 入库 保存收件箱
//     *
//     * @param imApplication
//     * @param toConversationId
//     * @param messageId
//     * @param conversationMembers
//     * @param imInboxId
//     */
//    private void saveImInbox(ImApplication imApplication, Long toConversationId, long messageId, ImConversationMembers conversationMembers, long imInboxId) {
//        ImInbox imInbox = new ImInbox();
//        imInbox.setId(imInboxId);
//        imInbox.setCreateTime(new Date());
//        imInbox.setFkAppid(imApplication.getId());
//        imInbox.setReceiver(conversationMembers.getFkClientId());
//        imInbox.setFkMsgId(messageId);
//        imInbox.setReadMsgStatus(0);
//        imInbox.setReceiverMsgStatus(0);
//        imInbox.setFkConversationId(toConversationId);
//        imInboxService.save(imInbox);
//    }
//
//    /**
//     * 响应发送方消息id等信息
//     *
//     * @param receiveVO
//     * @param messageId
//     */
//    private void response(ReceiveVO receiveVO, long messageId, NioSocketChannel channel) {
//        WsResponse<HashMap<String, Long>> responseModel = new WsResponse<>();
//        ApiResult<Boolean> result = ApiResult.result(ApiCode.SUCCESS);
//        responseModel.setCmd(WsResponseCmdEnum.RES.getCmdCode());
//        responseModel.setCode(result.getCode());
//        responseModel.setMsg(result.getMessage());
//        HashMap<String, Long> stringHashMap = new HashMap<>(3);
//        stringHashMap.put(MSG_ID, messageId);
//        responseModel.setData(stringHashMap);
//        responseModel.setReqId(receiveVO.getReqId());
//        // 响应发送方
////        writeDataService.write(responseModel, appKey, clientId);
//        channelSender.sendMsgLocal(channel, responseModel);
//    }
//
//    /**
//     * 判断是否被拉黑
//     *
//     * @param receiveVO
//     * @param imClientSender
//     * @param membersList
//     * @return
//     */
//    private boolean black(ReceiveVO receiveVO, ImClient imClientSender, List<ImConversationMembers> membersList, NioSocketChannel channel) {
//        // 判断是否被拉黑
//        boolean beBlack = imClientBlacklistService.isBeBlack(membersList.get(0).getFkClientId(), imClientSender.getId());
//        if (beBlack) {
//            log.info("被对方拉黑了");
//
//            // 响应发送方
//            WsResponse<HashMap<String, Long>> responseModel = new WsResponse<>();
//            ApiResult<Boolean> result = ApiResult.result(ApiCode.IS_BE_BLACK);
//            responseModel.setCmd(WsResponseCmdEnum.RES.getCmdCode());
//            responseModel.setCode(result.getCode());
//            responseModel.setMsg(result.getMessage());
//            responseModel.setReqId(receiveVO.getReqId());
////            writeDataService.write(responseModel, appKey, clientUniId);
//
//            channelSender.sendMsgLocal(channel, responseModel);
//
//            return true;
//        }
//
//        // 是否把对方拉黑
//        boolean black = imClientBlacklistService.isBeBlack(imClientSender.getId(), membersList.get(0).getFkClientId());
//        if (black) {
//            log.info("你把对方拉黑了");
//            // 响应发送方
//            WsResponse<HashMap<String, Long>> responseModel = new WsResponse<>();
//            ApiResult<Boolean> result = ApiResult.result(ApiCode.IS_TO_BLACK);
//            responseModel.setCmd(WsResponseCmdEnum.RES.getCmdCode());
//            responseModel.setCode(result.getCode());
//            responseModel.setMsg(result.getMessage());
//            responseModel.setReqId(receiveVO.getReqId());
////            writeDataService.write(responseModel, appKey, clientUniId);
//
//            channelSender.sendMsgLocal(channel, responseModel);
//
//            return true;
//        }
//        return false;
//    }
//
//
//}
