
package org.lym.pom.service.impl;

import org.apache.commons.collections4.CollectionUtils;
import org.lym.pom.notify.event.PostAddEvent;
import org.lym.pom.repository.mongo.Feed;
import org.lym.pom.repository.mongo.Follow;
import org.lym.pom.repository.mongo.Post;
import org.lym.pom.service.FeedService;
import org.lym.pom.service.FollowService;
import org.shoulder.core.dto.request.BasePageQuery;
import org.shoulder.core.dto.request.BasePageQuery.Order;
import org.shoulder.core.dto.request.BasePageQuery.OrderRule;
import org.shoulder.core.dto.response.PageResult;
import org.shoulder.core.log.AppLoggers;
import org.shoulder.core.log.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lym
 */
@Service
public class PostEventConsumer {

    private static final Logger logger = AppLoggers.APP_SERVICE;

    @Autowired
    private FeedService feedService;

    @Autowired
    private FollowService followService;

    /**
     * add
     */
    @EventListener(PostAddEvent.class)
    public void onPostAddEvent(PostAddEvent postAddEvent) {
        long currentTime = System.currentTimeMillis();
        Post post = postAddEvent.getPost();
        String creator = post.getCreator();

        // 创建者自己的时间轴
        Feed postFeed = createFeed(creator, post.getId(), post.getType(), creator, currentTime);
        feedService.addFeedList(List.of(postFeed));
        logger.debug("save creator feed. contentId={}, contentType={}", post.getId(), post.getType());

        int page = 0;
        int pageSize = 100;
        PageResult<Follow> fansPageResult;
        Follow queryCondition = new Follow();
        queryCondition.setFolloweeUserId(creator);
        Map<String, Object> extQueryCondition = new HashMap<>();
        long lastRecordCreateTime = System.currentTimeMillis();
        // 朋友的时间轴：找到这个用户的所有粉丝（好友）
        do {
            page++;
            BasePageQuery<Follow> pageQuery = new BasePageQuery<>(page, pageSize);
            // 时间 < xxx，确保粉丝列表不重复不遗漏 todo 改为 id，id要有顺序
            extQueryCondition.put("createTime" + "_ed", lastRecordCreateTime);
            pageQuery.setOrderRules(List.of(new OrderRule("createTime", Order.DESC)));
            pageQuery.setCondition(queryCondition);
            pageQuery.setExt(extQueryCondition);
            fansPageResult = followService.pageQueryFollowed(pageQuery);
            if(fansPageResult.getTotal() > 1000) {
                // 加大并发力度
            }

            List<Follow> fansList = fansPageResult.getList();
            if (CollectionUtils.isEmpty(fansList)) {
                break;
            }
            List<Feed> fansFeed = fansList.stream()
                    .map(Follow::getUserId)
                    .map(uid -> createFeed(uid, post.getId(), post.getType(), creator, currentTime))
                    .toList();
            Feed last = fansFeed.get(fansFeed.size() -1);
            lastRecordCreateTime = last.getCreateTime();
            feedService.addFeedList(fansFeed);
            logger.debug("save fans feedList. contentId={}, contentType={}, size={}.", post.getId(), post.getType(), fansFeed.size());
        } while (fansPageResult.getHasNextPage());

        // 没必要在最后再添加一轮最新关注的人，不重要

    }

    private static Feed createFeed(String feedUserId, String contentId, String contentType, String creator, long currentTime) {
        Feed postFeed = new Feed();
        postFeed.setUserId(feedUserId);
        postFeed.setRelatedId(contentId);
        postFeed.setRelatedCreator(creator);
        postFeed.setScene(contentType);
        postFeed.setCreateTime(currentTime);
        return postFeed;
    }

}