package com.gxwebsoft.shop.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.gxwebsoft.cms.service.CmsWebsiteService;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.shop.service.ShopWebsiteService;
import com.gxwebsoft.shop.vo.ShopVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 商城网站服务实现类
 *
 * @author 科技小王子
 * @since 2025-08-13
 */
@Slf4j
@Service
public class ShopWebsiteServiceImpl implements ShopWebsiteService {

    @Autowired
    private CmsWebsiteService cmsWebsiteService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 商城信息缓存键前缀
     */
    private static final String SHOP_INFO_KEY_PREFIX = "ShopInfo:";

    @Override
    public ShopVo getShopInfo(Integer tenantId) {
        // 参数验证
        if (ObjectUtil.isEmpty(tenantId)) {
            throw new IllegalArgumentException("租户ID不能为空");
        }

        // 商城专用缓存键
        String cacheKey = SHOP_INFO_KEY_PREFIX + tenantId;
        String shopInfo = redisUtil.get(cacheKey);
        if (StrUtil.isNotBlank(shopInfo)) {
            try {
                ShopVo cacheVo = JSONUtil.parseObject(shopInfo, ShopVo.class);
                if (cacheVo != null) {
                    log.info("从缓存获取商城信息，租户ID: {}", tenantId);
                    return cacheVo;
                }
                // 兼容历史缓存：JSON "null" 会被解析为 null；此时清理缓存并回源。
                log.warn("商城信息缓存命中但内容为空(null)，清理缓存后回源数据库，租户ID: {}", tenantId);
                redisUtil.delete(cacheKey);
            } catch (Exception e) {
                log.warn("商城缓存解析失败，清理缓存后重新获取: {}", e.getMessage());
                redisUtil.delete(cacheKey);
            }
        }

        // 直接调用 CMS 服务获取站点信息，然后使用商城专用缓存
        ShopVo shopVO = cmsWebsiteService.getSiteInfo(tenantId);
        if (shopVO == null) {
            throw new RuntimeException("请先创建商城");
        }

        // 缓存结果（商城信息缓存时间设置为1小时）
        try {
            redisUtil.set(cacheKey, shopVO, 1L, TimeUnit.HOURS);
        } catch (Exception e) {
            log.warn("缓存商城信息失败: {}", e.getMessage());
        }

        log.info("获取商城信息成功，租户ID: {}", tenantId);
        return shopVO;
    }

    @Override
    public void clearShopInfoCache(Integer tenantId) {
        if (tenantId != null) {
            String cacheKey = SHOP_INFO_KEY_PREFIX + tenantId;
            redisUtil.delete(cacheKey);
            log.info("清除商城信息缓存成功，租户ID: {}", tenantId);
        }
    }


}
