package com.webchat.service.event.listener;

import com.webchat.common.enums.ChatMessageTypeEnum;
import com.webchat.common.enums.ESMessageTypeEum;
import com.webchat.common.util.JsonUtil;
import com.webchat.domain.vo.dto.AbstractESMessageDTO;
import com.webchat.domain.vo.response.publicaccount.ArticleBaseResponseVO;
import com.webchat.repository.entity.ChatMessEntity;
import com.webchat.service.elastic.WebChatElasticSearchService;
import com.webchat.service.event.ChatMessageSendEvent;
import com.webchat.service.publicaccount.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;


/**
 * 新消息发送监听
 */
@Component
public class ChatMessageSendListener implements ApplicationListener<ChatMessageSendEvent> {

    @Autowired
    private WebChatElasticSearchService webChatElasticSearchService;

    @Autowired
    private ArticleService articleService;

    /**
     * 监听聊天新消息、新消息同步ES用于消息搜索
     *
     * @param chatMessageSendEvent
     */
    @Override
    public void onApplicationEvent(ChatMessageSendEvent chatMessageSendEvent) {
        // 监听到有消息对话消息
        Object mess = chatMessageSendEvent.getSource();
        // 新消息同步ES
        webChatElasticSearchService.sync(this.buildAbstractESMessageDTO(mess));
    }

    /**
     * 构造ES消息索引数据
     *
     * @param mess
     * @return
     */
    private AbstractESMessageDTO buildAbstractESMessageDTO(Object mess) {
        ChatMessEntity chatMessEntity = (ChatMessEntity) mess;
        AbstractESMessageDTO esMessage = new AbstractESMessageDTO();
        esMessage.setType(ESMessageTypeEum.CHAT_MESSAGE.getType());
        esMessage.setBizId(String.valueOf(chatMessEntity.getId()));
        esMessage.setSenderId(chatMessEntity.getSender());
        esMessage.setReceiverId(chatMessEntity.getReceiver());
        esMessage.setProxySenderId(chatMessEntity.getProxySender());
        esMessage.setContent(chatMessEntity.getMessage());
        esMessage.setData(JsonUtil.toJsonString(mess));
        esMessage.setCreateDate(chatMessEntity.getSendDate());
        esMessage.setUpdateDate(chatMessEntity.getSendDate());
        Integer type = chatMessEntity.getType();
        if (ChatMessageTypeEnum.PUBLIC_ACCOUNT_ARTICLE.getType().equals(type)) {
            // 公众号文章
            esMessage.setType(ESMessageTypeEum.PUBLIC_ACCOUNT_ARTICLE.getType());
            ArticleBaseResponseVO article = articleService.getArticleDetailFromCache(Long.valueOf(chatMessEntity.getMessage()));
            // 方便文章搜索，支持标题+摘要搜索
            esMessage.setContent(article.getTitle() + ":" + article.getDescription());
        }
        return esMessage;
    }
}
