package com.wzj.soopin.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzj.soopin.order.domain.entity.OrderItem;
import com.wzj.soopin.order.mapper.OrderItemMapper;
import com.wzj.soopin.order.service.OrderItemService;
import org.dromara.common.redis.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wzj.soopin.content.utils.RedisOperator;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;

/**
 * 订单中所包含的商品Service业务层处理
 *
 *
 * @author zcc
 */
@Slf4j
@Service
public class OrderItemServiceImpl extends ServiceImpl<OrderItemMapper, OrderItem> implements OrderItemService {

    @Autowired
    private RedisCache redisCache;

    @Override
    public List<OrderItem> findByOrderId(Long orderId) {
        return baseMapper.selectList(new QueryWrapper<OrderItem>().lambda()
                .eq(OrderItem::getOrderId, orderId));
    }

    @Override
    public void cacheTopTradingProducts(int limit) {
        try {
            log.info("开始查询交易量最多的{}个商品", limit);

            // 查询交易量最多的商品列表
            List<Map<String, Object>> topTradingProducts = baseMapper.selectTopTradingProducts(limit);

            if (topTradingProducts != null && !topTradingProducts.isEmpty()) {
                // 将结果存储到Redis中，使用JSON格式
                ObjectMapper objectMapper = new ObjectMapper();
                // 注册JavaTimeModule以支持LocalDateTime序列化
                objectMapper.registerModule(new com.fasterxml.jackson.datatype.jsr310.JavaTimeModule());
                objectMapper.disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
                String jsonData = objectMapper.writeValueAsString(topTradingProducts);

                // 存储到Redis，设置24小时过期时间
                String redisKey = "top_trading_products:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                redisCache.setCacheObject(redisKey, jsonData, 24 * 60 * 60, TimeUnit.SECONDS); // 24小时过期

                log.info("成功缓存{}个交易量最多的商品到Redis，key: {}", topTradingProducts.size(), redisKey);
            } else {
                log.warn("未查询到交易量最多的商品数据");
            }
        } catch (Exception e) {
            log.error("缓存交易量最多商品到Redis失败", e);
        }
    }
}
