package com.wecloud.im.tillo.app_ws.strategy.concrete;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
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.service.ImApplicationService;
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.tillo.app_ws.annotation.ReceiveTypeAnnotation;
import com.wecloud.im.tillo.app_ws.enums.WsRequestCmdEnum;
import com.wecloud.im.tillo.app_ws.model.request.ReceiveModel;
import com.wecloud.im.tillo.app_ws.service.MangerChannelService;
import com.wecloud.im.tillo.app_ws.strategy.AbstractReceiveStrategy;
import io.geekidea.springbootplus.framework.shiro.util.SnowflakeUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Description 处理app单聊消息
 */
@ReceiveTypeAnnotation(type = WsRequestCmdEnum.DATA)
@Service
@Slf4j
public class SingleConcreteReceiveStrategy extends AbstractReceiveStrategy {

    @Autowired
    private ImMessageService imMessageService;

    @Autowired
    private ImInboxService imInboxService;

    @Autowired
    private ImApplicationService imApplicationService;

    @Resource
    private MangerChannelService mangerChannelService;

    @Autowired
    private ImConversationMembersService imConversationMembersService;

    @Autowired
    private ImClientService imClientService;

    @Override
    public void process(ReceiveModel requestModel, String language, ChannelHandlerContext ctx, String data) {

        String appKey = ctx.channel().attr(MangerChannelService.APP_KEY).get();
        String clientUniId = ctx.channel().attr(MangerChannelService.CLIENT_ID).get();

        // 查询imApplication
        ImApplication imApplication = imApplicationService.getOne(new QueryWrapper<ImApplication>().lambda()
                .eq(ImApplication::getAppKey, appKey));

        // 查询发送者client
        ImClient imClientSender = imClientService.getOne(new QueryWrapper<ImClient>().lambda()
                .eq(ImClient::getFkAppid, imApplication.getId())
                .eq(ImClient::getClientId, clientUniId));

        JsonMapper jsonMapper = new JsonMapper();
        Long toConversationId = Long.valueOf(requestModel.getData().get("toConversation").toString());

        long messageId = SnowflakeUtil.getId();
        String content = null;

        try {
            content = jsonMapper.writeValueAsString(requestModel.getData());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        //  保存离线消息
        ImMessage imMessage = new ImMessage();
        imMessage.setId(messageId);
        imMessage.setCreateTime(new Date());
//        imMessage.setWithdrawTime(new Date());
//        imMessage.setUpdateDate(new Date());
        imMessage.setFkAppid(imApplication.getId());
        imMessage.setSender(imClientSender.getId());
        imMessage.setContent(content);
        imMessage.setWithdraw(false);
        imMessage.setEvent(false);
        imMessage.setSystem(false);
//        imMessage.setAt("");
        imMessage.setSendStatus(0);
        imMessage.setFkConversationId(toConversationId);
        imMessageService.save(imMessage);

        // 查询该会话所有成员
        List<ImConversationMembers> membersList = imConversationMembersService.list(
                new QueryWrapper<ImConversationMembers>().lambda()
                        .eq(ImConversationMembers::getFkConversationId, toConversationId)
        );

        if (membersList.isEmpty()) {
            log.error("membersList为空");
            return;
        }

        for (ImConversationMembers conversationMembers : membersList) {

            // 排除发送者
            if (conversationMembers.getFkClientId().equals(imClientSender.getId())) {
                continue;
            }

            // 保存收件箱
            long imInboxId = SnowflakeUtil.getId();
            ImInbox imInbox = new ImInbox();
            imInbox.setId(imInboxId);
            imInbox.setCreateTime(new Date());
            imInbox.setFkAppid(imApplication.getId());
            imInbox.setReceiver(conversationMembers.getId());
            imInbox.setFkMsgId(messageId);
            imInbox.setReadMsg(0);
            imInbox.setFkConversationId(toConversationId);
            imInboxService.save(imInbox);

            // 接收方
            ImClient imClientReceiver = imClientService.getOne(new QueryWrapper<ImClient>().lambda()
                    .eq(ImClient::getFkAppid, imApplication.getId())
                    .eq(ImClient::getId, conversationMembers.getFkClientId()));

            //  向接收方推送
            String imClientRecerverUniId = imClientReceiver.getClientId();
            mangerChannelService.writeData(content, appKey, imClientRecerverUniId);
        }
    }
}
