package com.ssyf.third.bmiss.services;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageInfo;
import com.ssyf.module.robot.domain.entity.RRobotAccount;
import com.ssyf.module.robot.domain.query.RRobotAccountQuery;
import com.ssyf.module.robot.service.RRobotAccountService;
import com.ssyf.third.bmiss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 礼物服务类
 * 提供礼物列表获取、礼物信息查询、礼物赠送等功能，并支持Redis缓存
 * 
 * @author system
 * @since 1.0
 */
@Slf4j
@Service
public class GiftService {

    private static final String GIFT_LIST_CACHE_KEY = "gift:list";
    private static final String GIFT_DETAIL_CACHE_PREFIX = "gift:detail:";
    private static final long DEFAULT_CACHE_TTL = 60 * 60; // 1小时
    
    @Autowired
    private BusinessService businessService;
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取礼物列表，支持筛选
     *
     * @param filterGift 筛选条件，包括ID、价格、名称等
     * @return 符合条件的礼物详情列表
     */
    public List<GiftDetail> getGiftList(GiftDetail filterGift) {
        // 获取完整的礼物列表
        List<GiftDetail> allGiftList = getGiftList();

        if (allGiftList == null || allGiftList.isEmpty()) {
            return Collections.emptyList();
        }

        if (filterGift == null) {
            return allGiftList;
        }



        // 根据筛选条件过滤礼物列表
        return allGiftList.stream()
                .filter(gift -> {
                    // 按ID筛选
                    if (filterGift.getGift_id() != null ) {
                        if (!filterGift.getGift_id().equals(gift.getGift_id())) {
                            return false;
                        }
                    }

                    // 按价格筛选
                    if (filterGift.getGift_price() != null) {
                        if (!filterGift.getGift_price().equals(gift.getGift_price())) {
                            return false;
                        }
                    }

                    // 按名称筛选
                    if (filterGift.getGift_name() != null && !filterGift.getGift_name().isEmpty()) {
                        if (gift.getGift_name() == null || !gift.getGift_name().contains(filterGift.getGift_name())) {
                            return false;
                        }
                    }

                    return true;
                })
                .collect(Collectors.toList());
    }


    /**
     * 获取礼物列表
     * 优先从缓存获取，缓存不存在时调用BusinessService获取并缓存
     * 
     * @return 礼物详情列表
     */
    public List<GiftDetail> getGiftList() {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        
        // 从缓存获取
        List<GiftDetail> cachedGiftList = (List<GiftDetail>) ops.get(GIFT_LIST_CACHE_KEY);
        if (cachedGiftList != null) {
            log.info("从缓存获取礼物列表");
            return cachedGiftList;
        }
        
        // 缓存不存在，调用业务服务获取
        ApiResponse<List<GiftDetail>> response = businessService.getRobotGiftList();

        if(!response.isSuccess()){
            log.error("获取礼物列表失败：{}", response.getMessage());
            return Collections.emptyList();
        }
        List<GiftDetail> giftList = response.getData();
        // 缓存结果（仅成功响应）
        if (giftList != null && !giftList.isEmpty()) {
            // 按单价从小到大排序，单价为空的按0处理
            giftList.sort((g1, g2) -> {
                Double price1 = g1.getGift_price() != null ? g1.getGift_price() : 0.0;
                Double price2 = g2.getGift_price() != null ? g2.getGift_price() : 0.0;
                return price1.compareTo(price2);
            });

            ops.set(GIFT_LIST_CACHE_KEY, giftList, DEFAULT_CACHE_TTL, TimeUnit.SECONDS);
            log.info("礼物列表已按单价排序并缓存，TTL: {}秒", DEFAULT_CACHE_TTL);
        }
        // 缓存结果（仅成功响应）
        if (giftList != null && !giftList.isEmpty()) {
            ops.set(GIFT_LIST_CACHE_KEY, giftList, DEFAULT_CACHE_TTL, TimeUnit.SECONDS);
            log.info("礼物列表已缓存，TTL: {}秒", DEFAULT_CACHE_TTL);
        }
        
        return giftList;
    }

    /**
     * 获取指定礼物信息
     * 
     * @param giftId 礼物ID
     * @return 礼物详情
     */
    public GiftDetail getGiftDetail(Integer giftId) {
        if (giftId == null) {
            return null;
        }
        
        String cacheKey = GIFT_DETAIL_CACHE_PREFIX + giftId;
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        
        // 从缓存获取
        GiftDetail cachedDetail = (GiftDetail) ops.get(cacheKey);
        if (cachedDetail != null) {
            log.info("从缓存获取礼物详情，礼物ID: {}", giftId);
            return cachedDetail;
        }
        
        // 缓存不存在，从礼物列表中查找
        List<GiftDetail> giftList = getGiftList();
        if (giftList == null || giftList.isEmpty()) {
            return null;
        }
        
        GiftDetail giftDetail = findGiftInList(giftList, giftId);
        
        // 缓存找到的礼物详情
        if (giftDetail != null) {
            ops.set(cacheKey, giftDetail, DEFAULT_CACHE_TTL, TimeUnit.SECONDS);
            log.info("礼物详情已缓存，礼物ID: {}, TTL: {}秒", giftId, DEFAULT_CACHE_TTL);
        }
        
        return giftDetail;
    }
    
    /**
     * 赠送礼物
     * 需要全局锁，防止并发赠送
     * 
     * @param roomId 直播间ID
     * @param giftIdArr 礼物ID数组
     * @param isWishReach 是否心愿达成
     * @param ext 扩展信息
     * @param sendFrom 发送来源
     * @param recipientArr 接收者数组
     * @param sceneType 场景类型
     * @param token 令牌
     * @return 赠送结果
     */
    public ApiResponse<Object> sendGift(Integer roomId, List<Map<String, Object>> giftIdArr, Integer isWishReach,
                                        Map<String, Object> ext, Integer sendFrom, List<Map<String, Object>> recipientArr,
                                        Integer sceneType, String token) {
        String lockKey = "gift:send:lock:" + roomId;
        
        // 使用Redis分布式锁
        Boolean lockAcquired = redisTemplate.opsForValue().setIfAbsent(lockKey, "locked", 30, TimeUnit.SECONDS);
        
        if (lockAcquired != null && lockAcquired) {
            try {
                log.info("获取礼物赠送锁成功，直播间ID: {}", roomId);
                
                // 调用业务服务赠送礼物
                ApiResponse<Object> response = businessService.sendGift(roomId, giftIdArr, isWishReach, ext, sendFrom, recipientArr, sceneType, token);
                return response;
            } finally {
                // 释放锁
                redisTemplate.delete(lockKey);
                log.info("释放礼物赠送锁，直播间ID: {}", roomId);
            }
        } else {
            log.warn("获取礼物赠送锁失败，直播间ID: {}，可能正在处理其他赠送请求", roomId);
            return ApiResponse.error("礼物赠送请求过于频繁，请稍后重试");
        }
    }
    
    /**
     * 重置礼物缓存（全部）
     */
    public void resetCache() {
        clearGiftCache();
        log.info("礼物服务缓存已重置");
    }
    
    /**
     * 清空礼物缓存
     */
    public void clearGiftCache() {
        // 清除礼物列表缓存
        redisTemplate.delete(GIFT_LIST_CACHE_KEY);
        
        // 清除所有礼物详情缓存
        redisTemplate.delete(redisTemplate.keys(GIFT_DETAIL_CACHE_PREFIX + "*"));
        
        log.info("礼物服务缓存已清空");
    }
    
    /**
     * 在礼物列表中查找指定礼物
     * 
     * @param giftList 礼物详情列表
     * @param giftId 礼物ID
     * @return 礼物详情
     */
    private GiftDetail findGiftInList(List<GiftDetail> giftList, Integer giftId) {
        if (giftList == null || giftList.isEmpty()) {
            return null;
        }
        
        // 遍历礼物列表查找指定礼物
        for (GiftDetail gift : giftList) {
            if (gift != null && gift.getGift_id() != null && gift.getGift_id().equals(giftId.toString())) {
                return gift;
            }
        }
        
        return null;
    }
}