package com.webchat.service.elastic;


import com.webchat.common.enums.ChatMessageTypeEnum;
import com.webchat.common.util.JsonUtil;
import com.webchat.domain.vo.dto.ChatMessageSearchResultDTO;
import com.webchat.domain.vo.response.UserBaseResponseInfoVO;
import com.webchat.domain.vo.response.publicaccount.ArticleBaseResponseVO;
import com.webchat.service.UserService;
import com.webchat.service.publicaccount.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 业务数据数据同步ES
 *
 * 一对一聊天消息、群聊消息、机器人对话消息、公众号文章推文消息、群组、人、公众号
 */
@Slf4j
@Service
public class WebChatElasticSearchService extends AbstractWebChatElasticSearchClient<ChatMessageSearchResultDTO> {

    @Value("${spring.elasticsearch.message-index}")
    private String chatMessageIndex;

    @Autowired
    private UserService userService;
    @Autowired
    private ArticleService articleService;

    @Override
    protected String getIndexName() {
        // 聊天消息索引
        return chatMessageIndex;
    }

    @Override
    protected Integer getShards() {
        return 1;
    }

    @Override
    protected Integer getReplicas() {
        return 1;
    }

    /**
     * 消息搜索索引结构设计
     *
     *
     * @return
     */
    @Override
    protected XContentBuilder getXContentBuilder() throws IOException {

        return JsonXContent.contentBuilder()
                .startObject()
                .startObject("properties")
                .startObject("type")
                .field("type", "integer")
                .endObject()
                .startObject("biz_id")
                .field("type", "keyword")
                .endObject()
                .startObject("sender_id")
                .field("type", "keyword")
                .endObject()
                .startObject("proxy_sender_id")
                .field("type", "keyword")
                .endObject()
                .startObject("receiver_id")
                .field("type", "keyword")
                .endObject()
                .startObject("content")
                .field("type", "text")
                .endObject()
                .startObject("create_date")
                .field("type", "date")
                .field("format", "yyyy-MM-dd")
                .endObject()
                .startObject("update_date")
                .field("type", "date")
                .field("format", "yyyy-MM-dd")
                .endObject()
                .endObject()
                .endObject();
    }

    @Override
    protected ChatMessageSearchResultDTO convert(String dataJson) {
        if (StringUtils.isBlank(dataJson)) {
            return null;
        }
        return JsonUtil.fromJson(dataJson, ChatMessageSearchResultDTO.class);
    }

    @Override
    protected void setSearchResultExtInfo(List<ChatMessageSearchResultDTO> dataList) {
        if (CollectionUtils.isEmpty(dataList)) {
            return;
        }
        Set<String> userIds = new HashSet<>();
        for (ChatMessageSearchResultDTO dto : dataList) {
            userIds.add(dto.getSender());
            userIds.add(dto.getReceiver());
            if (StringUtils.isNotBlank(dto.getProxySender())) {
                userIds.add(dto.getProxySender());
            }
        }
        // 走redis批量查询用户信息
        Map<String, UserBaseResponseInfoVO> users = userService.batchGetUserInfoFromCache(new ArrayList<>(userIds));
        for (ChatMessageSearchResultDTO dto : dataList) {
            dto.setSenderUser(users.get(dto.getSender()));
            dto.setReceiverUser(users.get(dto.getReceiver()));
            if (StringUtils.isNotBlank(dto.getProxySender())) {
                dto.setProxySenderUser(users.get(dto.getProxySender()));
            }
        }
        // 设置文章信息
        List<ChatMessageSearchResultDTO> articleMessages = dataList.stream().filter(dto ->
                        ChatMessageTypeEnum.PUBLIC_ACCOUNT_ARTICLE.getType().equals(dto.getType()))
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(articleMessages)) {
            Set<Long> articleIdSet = articleMessages.stream().map(dto -> Long.valueOf(dto.getMessage())).collect(Collectors.toSet());
            Map<Long, ArticleBaseResponseVO> articleBaseResponseVOMap = articleService.batchGetArticleDetailFromCache(new ArrayList<>(articleIdSet));
            for (ChatMessageSearchResultDTO dto : dataList) {
                if (ChatMessageTypeEnum.PUBLIC_ACCOUNT_ARTICLE.getType().equals(dto.getType())) {
                    dto.setArticle(articleBaseResponseVOMap.get(Long.valueOf(dto.getMessage())));
                }
            }
        }
    }
}
