package com.liquidnet.service.sweet.utils;

import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.service.sweet.vo.SweetLostFoundAdminVo;
import com.liquidnet.service.sweet.vo.SweetLostFoundItemVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * 失物招领Redis缓存工具类
 *
 * @author liquidnet
 * @since 2025-01-18
 */
@Slf4j
@Component
public class LostFoundRedisUtils {

    @Autowired
    private RedisUtil redisUtil;

    // Redis key前缀
    private static final String LOST_FOUND_KEY_PREFIX = "sweet:lost_found:";
    private static final String ITEM_LIST_KEY = LOST_FOUND_KEY_PREFIX + "item_list:";
    private static final String ITEM_DETAIL_KEY = LOST_FOUND_KEY_PREFIX + "item_detail:";
    private static final String ADMIN_DETAIL_KEY = LOST_FOUND_KEY_PREFIX + "admin_detail:";

    // 缓存过期时间（秒）
    private static final long LIST_EXPIRE_TIME = 432000; // 5天
    private static final long DETAIL_EXPIRE_TIME = 432000; // 5天

    /**
     * 获取失物信息列表缓存
     *
     * @param performanceId 演出ID
     * @param itemType      物品类型(可选，null表示全部)
     * @return 失物信息列表
     */
    public List<SweetLostFoundItemVo> getItemList(String performanceId, Integer itemType) {
        try {
            String key = buildItemListKey(performanceId);
            Object cachedValue = redisUtil.get(key);
            if (cachedValue != null) {
                List<SweetLostFoundItemVo> allItems = (List<SweetLostFoundItemVo>) cachedValue;
                // 如果指定了itemType，进行筛选
                if (itemType != null) {
                    return allItems.stream()
                            .filter(item -> itemType.equals(item.getItemType()))
                            .collect(Collectors.toList());
                }
                return allItems;
            }
        } catch (Exception e) {
            log.error("获取失物信息列表缓存失败", e);
        }
        return null;
    }

    /**
     * 设置失物信息列表缓存
     *
     * @param performanceId 演出ID
     * @param itemList      失物信息列表
     */
    public void setItemList(String performanceId, List<SweetLostFoundItemVo> itemList) {
        try {
            String key = buildItemListKey(performanceId);
            redisUtil.set(key, itemList, LIST_EXPIRE_TIME);
        } catch (Exception e) {
            log.error("设置失物信息列表缓存失败", e);
        }
    }

    /**
     * 获取失物信息详情缓存
     *
     * @param itemId 物品ID
     * @return 失物信息详情
     */
    public SweetLostFoundItemVo getItemDetail(Long itemId) {
        try {
            String key = ITEM_DETAIL_KEY + itemId;
            Object cachedValue = redisUtil.get(key);
            if (cachedValue != null) {
                return (SweetLostFoundItemVo) cachedValue;
            }
        } catch (Exception e) {
            log.error("获取失物信息详情缓存失败", e);
        }
        return null;
    }

    /**
     * 设置失物信息详情缓存
     *
     * @param itemId     物品ID
     * @param itemDetail 失物信息详情
     */
    public void setItemDetail(Long itemId, SweetLostFoundItemVo itemDetail) {
        try {
            String key = ITEM_DETAIL_KEY + itemId;
            redisUtil.set(key, itemDetail, DETAIL_EXPIRE_TIME);
        } catch (Exception e) {
            log.error("设置失物信息详情缓存失败", e);
        }
    }

    /**
     * 删除失物信息列表缓存
     *
     * @param performanceId 演出ID
     */
    public void deleteItemListCache(String performanceId) {
        try {
            String key = buildItemListKey(performanceId);
            redisUtil.del(key);
        } catch (Exception e) {
            log.error("删除失物信息列表缓存失败", e);
        }
    }

    /**
     * 删除失物信息详情缓存
     *
     * @param itemId 物品ID
     */
    public void deleteItemDetailCache(Long itemId) {
        try {
            String key = ITEM_DETAIL_KEY + itemId;
            redisUtil.del(key);
        } catch (Exception e) {
            log.error("删除失物信息详情缓存失败", e);
        }
    }

    /**
     * 构建失物信息列表缓存key
     *
     * @param performanceId 演出ID
     * @return 缓存key
     */
    private String buildItemListKey(String performanceId) {
        return ITEM_LIST_KEY + performanceId;
    }

    /*private String buildItemListKey(String performanceId) {
        StringBuilder keyBuilder = new StringBuilder(ITEM_LIST_KEY);
        keyBuilder.append(performanceId);
        return keyBuilder.toString();
    }*/

    /**
     * 检查管理员是否存在
     *
     * @param phone         手机号
     * @param performanceId 演出ID
     * @return 是否存在
     */
    public SweetLostFoundAdminVo getAdminCache(String phone, String performanceId) {
        try {
            // 优先检查全站管理员缓存
            String globalKey = ADMIN_DETAIL_KEY + phone + ":global";
            Object globalCache = redisUtil.get(globalKey);
            if (globalCache != null) {
                return (SweetLostFoundAdminVo) globalCache;
            }

            // 检查特定演出管理员缓存
            String specificKey = ADMIN_DETAIL_KEY + phone + ":" + performanceId;
            Object specificCache = redisUtil.get(specificKey);
            if (specificCache != null) {
                return (SweetLostFoundAdminVo) specificCache;
            }
        } catch (Exception e) {
            log.error("检查管理员缓存失败", e);
        }
        return null;
    }

    /**
     * 设置管理员缓存
     *
     * @param phone         手机号
     * @param performanceId 演出ID
     * @param vo            管理员信息
     */
    public void setAdminCache(String phone, String performanceId, SweetLostFoundAdminVo vo) {
        try {
            if (vo.getAuthScope() != null && vo.getAuthScope() == 2) {
                // 全站管理员使用全局缓存键
                String globalKey = ADMIN_DETAIL_KEY + phone + ":global";
                redisUtil.set(globalKey, vo, DETAIL_EXPIRE_TIME);
            } else {
                // 特定演出管理员使用演出特定的缓存键
                String specificKey = ADMIN_DETAIL_KEY + phone + ":" + performanceId;
                redisUtil.set(specificKey, vo, DETAIL_EXPIRE_TIME);
            }
        } catch (Exception e) {
            log.error("设置管理员缓存失败", e);
        }
    }

    /**
     * 删除管理员缓存
     *
     * @param phone         手机号
     * @param performanceId 演出ID
     */
    public void deleteAdminCache(String phone, String performanceId, Integer authScope) {
        try {
            if (authScope != null && authScope == 1) {
                // 删除特定演出管理员缓存
                String specificKey = ADMIN_DETAIL_KEY + phone + ":" + performanceId;
                redisUtil.del(specificKey);
            } else if (authScope != null && authScope == 2) {
                // 删除全站管理员缓存
                String globalKey = ADMIN_DETAIL_KEY + phone + ":global";
                redisUtil.del(globalKey);
            } else {
                String specificKey = ADMIN_DETAIL_KEY + phone + ":" + performanceId;
                redisUtil.del(specificKey);
                String globalKey = ADMIN_DETAIL_KEY + phone + ":global";
                redisUtil.del(globalKey);
            }
        } catch (Exception e) {
            log.error("删除管理员缓存失败", e);
        }
    }

}