import Taro from '@tarojs/taro'
import { listShopDealerApply } from '@/api/shop/shopDealerApply'

const VIP_STORAGE_KEY = 'is_vip_member'

/**
 * 从本地缓存读取 VIP 状态
 */
export function getVipStatusFromCache(): boolean {
  return Taro.getStorageSync(VIP_STORAGE_KEY) === true
}

/**
 * 写入 VIP 状态到本地缓存
 */
export function setVipStatus(isVip: boolean) {
  Taro.setStorageSync(VIP_STORAGE_KEY, isVip)
}

/**
 * 同步检查 VIP 状态（从缓存读取，无网络请求）
 * 用于价格展示等需要即时判断的场景
 */
export function isVipMember(): boolean {
  return getVipStatusFromCache()
}

/**
 * 异步检查 VIP 状态并更新缓存
 * 通过查询 ShopDealerApply 记录判断（applyStatus === 20 表示已通过）
 * @param userId 用户ID
 */
export async function checkAndCacheVipStatus(userId?: number): Promise<boolean> {
  if (!userId) {
    // 尝试从 storage 获取 userId
    const uid = Taro.getStorageSync('UserId')
    if (!uid) {
      setVipStatus(false)
      return false
    }
    userId = uid
  }

  try {
    const list = await listShopDealerApply({ userId })
    const approved = (list || []).some(item => item.applyStatus === 20)
    setVipStatus(approved)
    return approved
  } catch {
    // 请求失败时保持原缓存值
    return getVipStatusFromCache()
  }
}

/**
 * 获取商品对当前用户的实际购买价格
 * VIP 会员返回 dealerPrice，普通用户返回 price
 */
export function getDisplayPrice(product: {
  dealerPrice?: string
  price?: string
  salePrice?: string
}): string {
  if (isVipMember() && product.dealerPrice) {
    return product.dealerPrice
  }
  return product.price || product.salePrice || '0'
}
