package com.fs.live.service.impl;


import com.fs.common.core.redis.RedisCache;
import com.fs.live.domain.LiveGift;
import com.fs.live.mapper.LiveGiftMapper;
import com.fs.live.service.ILiveGiftService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 直播间礼物配置Service业务层处理
 *
 * @author fs
 * @date 2025-07-08
 */
@Service
public class LiveGiftServiceImpl implements ILiveGiftService {

    private static final String ACTIVE_GIFT_CACHE_KEY = "live:gift:active";
    private static final int MAX_ACTIVE_GIFT_COUNT = 8;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private LiveGiftMapper baseMapper;

//    @PostConstruct
//    public void init() {
//        loadGifts();
//    }
//
//    private void loadGifts() {
//        List<LiveGift> liveGifts = baseMapper.selectList(null);
//        redisCache.setCacheList("liveGift", liveGifts);
//    }

    /**
     * 查询直播间礼物配置
     *
     * @param giftId 直播间礼物配置主键
     * @return 直播间礼物配置
     */
    @Override
    public LiveGift selectLiveGiftByGiftId(Long giftId)
    {
        return baseMapper.selectLiveGiftByGiftId(giftId);
    }

    /**
     * 查询直播间礼物配置列表
     *
     * @param liveGift 直播间礼物配置
     * @return 直播间礼物配置
     */
    @Override
    public List<LiveGift> selectLiveGiftList(LiveGift liveGift)
    {
        return baseMapper.selectLiveGiftList(liveGift);
    }

    /**
     * 新增直播间礼物配置
     *
     * @param liveGift 直播间礼物配置
     * @return 结果
     */
    @Override
    @Transactional
    public int insertLiveGift(LiveGift liveGift)
    {
        // 如果新增的礼物状态是正常状态，需要检查正常状态礼物数量
        if ("1".equals(liveGift.getStatus())) {
            manageActiveGiftCount(liveGift);
        }
        int result = baseMapper.insertLiveGift(liveGift);
        // 清除缓存
        clearActiveGiftCache();
        return result;
    }

    /**
     * 管理正常状态礼物数量，确保不超过8个
     */
    private void manageActiveGiftCount(LiveGift newGift) {
        // 查询当前正常状态的礼物（排除当前要新增/修改的礼物）
        LiveGift query = new LiveGift();
        query.setStatus("1");
        List<LiveGift> activeGifts = baseMapper.selectLiveGiftList(query);
        
        // 如果是更新操作，需要排除当前礼物本身
        if (newGift.getGiftId() != null) {
            activeGifts = activeGifts.stream()
                    .filter(gift -> !gift.getGiftId().equals(newGift.getGiftId()))
                    .collect(Collectors.toList());
        }
        
        // 如果正常状态礼物数量已经达到或超过上限，需要停用超出部分的礼物
        // 确保新增/修改后正常状态礼物不超过8个
        if (activeGifts.size() >= MAX_ACTIVE_GIFT_COUNT) {
            // 停用超出部分的礼物（保留前面的，停用后面的）
            int needToDisable = activeGifts.size() - MAX_ACTIVE_GIFT_COUNT + 1;
            for (int i = activeGifts.size() - needToDisable; i < activeGifts.size(); i++) {
                LiveGift giftToDisable = activeGifts.get(i);
                giftToDisable.setStatus("0");
                baseMapper.updateLiveGift(giftToDisable);
            }
        }
    }

    /**
     * 修改直播间礼物配置
     *
     * @param liveGift 直播间礼物配置
     * @return 结果
     */
    @Override
    @Transactional
    public int updateLiveGift(LiveGift liveGift)
    {
        // 如果修改后的礼物状态是正常状态，需要检查正常状态礼物数量
        if ("1".equals(liveGift.getStatus())) {
            manageActiveGiftCount(liveGift);
        }
        int result = baseMapper.updateLiveGift(liveGift);
        // 清除缓存
        clearActiveGiftCache();
        return result;
    }

    /**
     * 批量删除直播间礼物配置
     *
     * @param giftIds 需要删除的直播间礼物配置主键
     * @return 结果
     */
    @Override
    public int deleteLiveGiftByGiftIds(Long[] giftIds)
    {
        int result = baseMapper.deleteLiveGiftByGiftIds(giftIds);
        // 清除缓存
        clearActiveGiftCache();
        return result;
    }

    /**
     * 删除直播间礼物配置信息
     *
     * @param giftId 直播间礼物配置主键
     * @return 结果
     */
    @Override
    public int deleteLiveGiftByGiftId(Long giftId)
    {
        int result = baseMapper.deleteLiveGiftByGiftId(giftId);
        // 清除缓存
        clearActiveGiftCache();
        return result;
    }

    /**
     * 查询正常状态的礼物列表，按价格升序排列
     *
     * @return 礼物列表
     */
    @Override
    public List<LiveGift> selectActiveLiveGiftList() {
        // 先查缓存
        List<LiveGift> cachedGifts = redisCache.getCacheList(ACTIVE_GIFT_CACHE_KEY);
        if (cachedGifts != null && !cachedGifts.isEmpty()) {
            return cachedGifts;
        }
        
        // 缓存不存在，查询数据库
        List<LiveGift> gifts = baseMapper.selectActiveLiveGiftList();
        
        // 存入缓存
        if (gifts != null && !gifts.isEmpty()) {
            redisCache.setCacheList(ACTIVE_GIFT_CACHE_KEY, gifts);
        }
        
        return gifts;
    }

    /**
     * 清除正常状态礼物缓存
     */
    private void clearActiveGiftCache() {
        redisCache.deleteObject(ACTIVE_GIFT_CACHE_KEY);
    }
}
