package com.wecloud.im.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.turo.pushy.apns.PushType;
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.ImApplicationService;
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.ws.annotation.CmdTypeAnnotation;
import com.wecloud.im.ws.enums.WsRequestCmdEnum;
import com.wecloud.im.ws.enums.WsResponseCmdEnum;
import com.wecloud.im.ws.model.ResponseModel;
import com.wecloud.im.ws.model.request.ReceiveModel;
import com.wecloud.im.ws.sender.SystemPush;
import com.wecloud.im.ws.service.WriteDataService;
import com.wecloud.im.ws.strategy.ImCmdAbstract;
import io.geekidea.springbootplus.framework.common.api.ApiCode;
import io.geekidea.springbootplus.framework.common.api.ApiResult;
import io.geekidea.springbootplus.framework.shiro.util.SnowflakeUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Description 处理app数据消息
 */
@CmdTypeAnnotation(type = WsRequestCmdEnum.DATA)
@Service
@Slf4j
public class ImChatConcrete extends ImCmdAbstract {

    private static final String TO_CONVERSATION_KEY = "toConversation";
    private static final String PUSH_KEY = "push";
    private static final String MSG_ID = "msgId";

    private static final JsonMapper JSON_MAPPER = new JsonMapper();

    @Autowired
    private ImClientBlacklistService imClientBlacklistService;

    @Autowired
    private WriteDataService writeDataService;

    @Autowired
    private ImMessageService imMessageService;

    @Autowired
    private ImInboxService imInboxService;

    @Autowired
    private ImApplicationService imApplicationService;

    @Autowired
    private ImConversationMembersService imConversationMembersService;

    @Autowired
    private ImClientService imClientService;

    @Autowired
    private SystemPush systemPush;

    @Override
    public void process(ReceiveModel receiveModel, ChannelHandlerContext ctx, String data, String appKey, String clientId) throws JsonProcessingException {


        // 查询imApplication
        ImApplication imApplication = imApplicationService.getOneByAppKey(appKey);
        if (imApplication == null) {
            log.info("imApplication为空");
            return;
        }

        // 查询发送者client
        ImClient imClientSender = getClientSender(clientId, imApplication);
        if (imClientSender == null) {
            return;
        }

        // 获取会话id
        if (receiveModel.getData().get(TO_CONVERSATION_KEY) == null) {
            return;
        }

        Long toConversationId = Long.valueOf(receiveModel.getData().get(TO_CONVERSATION_KEY).toString());

        // 查询该会话所有成员
        List<ImConversationMembers> membersList = imConversationMembersService.list(
                new QueryWrapper<ImConversationMembers>().lambda()
                        .eq(ImConversationMembers::getFkConversationId, toConversationId)
                        .notIn(ImConversationMembers::getFkClientId, imClientSender.getId())
        );
        if (membersList.isEmpty()) {
            log.info("membersList为空,toConversationId:" + toConversationId);
            return;
        }

        receiveModel.getData().remove(TO_CONVERSATION_KEY);

        // 获取自定义推送字段
        HashMap<String, String> pushMap = null;
        if (receiveModel.getData().get(PUSH_KEY) != null) {
            pushMap = (HashMap<String, String>) receiveModel.getData().get(PUSH_KEY);
            receiveModel.getData().remove(PUSH_KEY);
        }

        String content = null;

        try {
            content = JSON_MAPPER.writeValueAsString(receiveModel.getData());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        // 判断为单聊
        if (membersList.size() == 1) {
            // 拉黑逻辑
            if (black(receiveModel, appKey, clientId, imClientSender, membersList)) {
                return;
            }
        }

        // 生成消息id
        long messageId = SnowflakeUtil.getId();
        //  保存消息至消息表
        ImMessage imMessage = saveImMessage(imApplication, imClientSender, toConversationId, messageId, content);

        // 封装响应的实体
        ImMessageOnlineSend imMessageOnlineSend = new ImMessageOnlineSend();
        BeanUtils.copyProperties(imMessage, imMessageOnlineSend);
        imMessageOnlineSend.setMsgId(imMessage.getId());
        imMessageOnlineSend.setSender(clientId);
        imMessageOnlineSend.setContent(receiveModel.getData());
        imMessageOnlineSend.setConversationId(toConversationId);

        // 遍历发送
        for (ImConversationMembers conversationMembers : membersList) {
            // 保存收件箱
            long imInboxId = SnowflakeUtil.getId();
            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);

            // 查询接收方
            ImClient imClientReceiver = imClientService.getOne(new QueryWrapper<ImClient>().lambda()
                    .eq(ImClient::getFkAppid, imApplication.getId())
                    .eq(ImClient::getId, conversationMembers.getFkClientId()));
            if (imClientReceiver == null) {
                continue;
            }

            //  向接收方推送
            ResponseModel<ImMessageOnlineSend> responseModel = new ResponseModel<>();
            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);
            writeDataService.write(responseModel, appKey, imClientReceiver.getClientId());

            // 异步推送系统通知消息
            systemPush.push(pushMap, imClientReceiver, imApplication, PushType.ALERT);
        }

        // 响应发送方消息id等信息
        ResponseModel<HashMap<String, Long>> responseModel = new ResponseModel<>();
        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(receiveModel.getReqId());
        // 响应发送方
        writeDataService.write(responseModel, appKey, clientId);
    }

    private ImClient getClientSender(String clientUniId, ImApplication imApplication) {
        ImClient imClientSender = imClientService.getOne(new QueryWrapper<ImClient>().lambda()
                .eq(ImClient::getFkAppid, imApplication.getId())
                .eq(ImClient::getClientId, clientUniId));
        if (imClientSender == null) {
            log.info("imClientSender为空");
            return null;
        }
        return imClientSender;
    }

    private ImMessage saveImMessage(ImApplication imApplication, ImClient imClientSender, Long toConversationId, long messageId, String content) {
        ImMessage imMessage = new ImMessage();
        imMessage.setId(messageId);
        imMessage.setCreateTime(new Date());
        imMessage.setFkAppid(imApplication.getId());
        imMessage.setSender(imClientSender.getId());
        imMessage.setContent(content);
        imMessage.setWithdraw(false);
        imMessage.setEvent(false);
        imMessage.setSystem(false);
        imMessage.setSendStatus(2);
        imMessage.setFkConversationId(toConversationId);
        imMessageService.save(imMessage);
        return imMessage;
    }

    private boolean black(ReceiveModel receiveModel, String appKey, String clientUniId, ImClient imClientSender, List<ImConversationMembers> membersList) {
        // 判断是否被拉黑
        boolean beBlack = imClientBlacklistService.isBeBlack(membersList.get(0).getFkClientId(), imClientSender.getId());
        if (beBlack) {
            log.info("被对方拉黑了");

            // 响应发送方
            ResponseModel<HashMap<String, Long>> responseModel = new ResponseModel<>();
            ApiResult<Boolean> result = ApiResult.result(ApiCode.IS_BE_BLACK);
            responseModel.setCmd(WsResponseCmdEnum.RES.getCmdCode());
            responseModel.setCode(result.getCode());
            responseModel.setMsg(result.getMessage());
            responseModel.setReqId(receiveModel.getReqId());
            writeDataService.write(responseModel, appKey, clientUniId);
            return true;
        }

        // 是否把对方拉黑
        boolean black = imClientBlacklistService.isBeBlack(imClientSender.getId(), membersList.get(0).getFkClientId());
        if (black) {
            log.info("你把对方拉黑了");
            // 响应发送方
            ResponseModel<HashMap<String, Long>> responseModel = new ResponseModel<>();
            ApiResult<Boolean> result = ApiResult.result(ApiCode.IS_TO_BLACK);
            responseModel.setCmd(WsResponseCmdEnum.RES.getCmdCode());
            responseModel.setCode(result.getCode());
            responseModel.setMsg(result.getMessage());
            responseModel.setReqId(receiveModel.getReqId());
            writeDataService.write(responseModel, appKey, clientUniId);
            return true;
        }
        return false;
    }


}
