package com.tzy.listener.mq;

import com.rabbitmq.client.Channel;
import com.tzy.browse.domain.AppUserBrowseRecord;
import com.tzy.browse.mapper.AppUserBrowseRecordMapper;
import com.tzy.common.constant.MqConstans;
import com.tzy.common.utils.bean.JSONTools;
import com.tzy.framework.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Component
public class AppUserBrowseRecordConsumer {
    @Resource
    private AppUserBrowseRecordMapper appUserBrowseRecordMapper;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @RabbitHandler
    //@RabbitListener(queuesToDeclare = @Queue(MqConstans.QUEUE_USER_BROWSE_RECORD))
    public void addUserBrowseRecord(String param, Channel channel, Message message) throws IOException {
        log.debug("入库用户浏览记录：{}", param);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        /*try{
            List<AppUserBrowseRecord> records = JSONTools.parseObjectList(param, AppUserBrowseRecord.class);
            records.forEach(record ->{
                String key = "app_user_browse_" + record.getUserId();
                Double timestamp = redisTemplate.opsForZSet().score(key, param);
                record.setBrowseTime(new Date(timestamp.longValue()));
                record.setBrowseDate(new Date(timestamp.longValue()));
            });
            appUserBrowseRecordMapper.batchSave(records);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            // 处理完要删除这些浏览记录
            Set<Long> userIds = redisUtils.sGet("app_user_set").stream()
                    .map(obj -> Long.parseLong(obj.toString()))
                    .collect(Collectors.toSet());
            userIds.forEach(userId ->{
                // 用户浏览记录存储 Key
                String historyKey = "app_user_browse_history_" + userId;
                redisUtils.del(historyKey);
            });
            redisUtils.del("app_user_set");
            redisUtils.set("browse_queue_count", 0); // 全局计数器归零
        }catch (Exception e){
            log.error("入库用户浏览记录异常：{}", param, e);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }*/

    }
}
