
package org.lym.pom.service.impl;

import com.mongodb.client.result.UpdateResult;
import org.lym.pom.notify.event.AttitudeAddEvent;
import org.lym.pom.notify.event.AttitudeRemoveEvent;
import org.lym.pom.repository.mongo.Attitude;
import org.lym.pom.repository.mongo.Attitude.RelatedType;
import org.lym.pom.repository.mongo.Attitude.Type;
import org.lym.pom.service.AttitudeService;
import org.lym.pom.service.CommentService;
import org.shoulder.core.exception.CommonErrorCodeEnum;
import org.shoulder.core.util.AssertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Map;

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

    // private RedisTemplate redisTemplate;

    @Autowired
    private AttitudeService attitudeService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 新增点赞 / 踩事件
     * 通知发帖人有新赞
     * 更新帖子评论/赞/喜欢 数（缓存） && 缓存 用户 - 点赞/踩关系
     * 推荐系统，为评论人调整该类帖子的喜好分、以及同类评论的展示优先级（AI分析评论内容）
     */
    @EventListener(AttitudeAddEvent.class)
    public void onAttitudeAddEvent(AttitudeAddEvent attitudeAddEvent) {
        if (attitudeAddEvent.getAttitude().getType().equals(Attitude.Type.LIKE)) {
            notifySourceAuthorLiked(attitudeAddEvent);
        }
        updateCache(attitudeAddEvent.getAttitude(), true);
        //score(attitudeAddEvent);
    }

    void notifySourceAuthorLiked(AttitudeAddEvent attitudeAddEvent) {
        // todo
    }

    private void updateCache(Attitude attitude, boolean addOperation) {
        //        int attitudeNumber = target.getLikeNumber() + target.getDislikeNumber() + target.getLoveNumber();
        //        Duration duration = Duration.ofMillis(System.currentTimeMillis() - target.getCreateTime());
        //        long temperature = ((long) attitudeNumber << 2) / duration.toSeconds();
        //        if(temperature > 1) {
        //            // 新高频交互流量：4s 一次交互（识别暂不彻底，暂不能识别发布很久后又火起来的）
        //        }

        Map<String, Integer> groupCount = attitudeService.countAttitudeNumber(attitude.getRelatedId(), attitude.getRelatedType());

        // 缓存用户 - 点赞/踩关系 todo 性能
        AssertUtils.notNull(attitude.getRelatedId(), CommonErrorCodeEnum.ILLEGAL_PARAM, "target id is null");
        Query query = new Query(Criteria.where("id").is(attitude.getRelatedId()));
        Update update = Update.update("updateTime", System.currentTimeMillis())
                //.set("readNumber", target.getReadNumber()) fixme 更新失败
                .set("likeNumber", groupCount.getOrDefault(Type.LIKE, 0))
                .set("loveNumber", groupCount.getOrDefault(Type.LOVE, 0))
                .set("dislikeNumber", groupCount.getOrDefault(Type.DISLIKE, 0));
        Class<?> modelClass = RelatedType.ofStorageValue(attitude.getRelatedType()).getModelClass();
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, modelClass);
        AssertUtils.equals(updateResult.getMatchedCount(), updateResult.getMatchedCount(), CommonErrorCodeEnum.DATA_STORAGE_FAIL);

    }

    /**
     * 新增评论事件
     * （【撤回】）通知发帖人有赞
     * 更新帖子评论/赞/喜欢 数（缓存） && 缓存 用户 - 点赞/踩关系
     * 推荐系统，为评论人调整该类帖子的喜好分、以及同类评论的展示优先级（AI分析评论内容）
     */
    @EventListener(AttitudeRemoveEvent.class)
    public void onAttitudeRemoveEvent(AttitudeRemoveEvent attitudeAddEvent) {
        updateCache(attitudeAddEvent.getAttitude(), false);
        //score(attitudeAddEvent);

    }

}