package com.copy.trade.consumer;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class MarketListener implements MessageListener {
	@Autowired
	private RedisTemplate redisTemplate;

	private static final String PRICE_CACHE_KEY = "copy:market:price";

	private Map<String, BigDecimal> currentPriceMap = new HashMap<String, BigDecimal>();

	/** 启动时从 Redis 预热价格，避免重启后短暂显示 -- */
	@PostConstruct
	public void init() {
		try {
			Map<Object, Object> cached = redisTemplate.opsForHash().entries(PRICE_CACHE_KEY);
			if (cached != null && !cached.isEmpty()) {
				cached.forEach((k, v) -> {
					try {
						currentPriceMap.put(k.toString(), new BigDecimal(v.toString()));
					} catch (Exception ignored) {}
				});
				log.info("MarketListener preloaded {} prices from Redis", currentPriceMap.size());
			}
		} catch (Exception e) {
			log.warn("MarketListener init preload failed: {}", e.getMessage());
		}
	}

	@Override
	public void onMessage(Message message, byte[] pattern) {
		byte[] messageBody = message.getBody();
        Object msg = redisTemplate.getValueSerializer().deserialize(messageBody);
        JSONObject thumb = JSON.parseObject(msg.toString());
        String symbol = thumb.getString("symbol");
        BigDecimal close = thumb.getBigDecimal("close");
        this.updatePrice(symbol, close);
	}

	public void updatePrice(String symbol, BigDecimal price) {
		currentPriceMap.put(symbol, price);
		// 同时持久化到 Redis，供重启时预热
		try {
			redisTemplate.opsForHash().put(PRICE_CACHE_KEY, symbol, price.toPlainString());
		} catch (Exception ignored) {}
	}

	public Map<String, BigDecimal> getCurrentPriceMap() {
		return currentPriceMap;
	}

}
