import { useUserStore } from '@/stores/user'

/**
 * 公共方法：根据用户信息判断用户是否为 VIP 会员
 * @param {Object} [userObj] - 用户信息对象（可选，未传时自动同步 Pinia/localStorage 数据）
 * @returns {Boolean} - 是否为有效 VIP 会员
 */
export function checkUserVip(userObj) {
  let targetUser = userObj;

  // 0. 若未传入有效对象，优先从 userStore 的响应式数据读取，保证接口更新后 Vue 视图可响应式刷新
  if (!targetUser || typeof targetUser !== 'object' || Object.keys(targetUser).length === 0) {
    try {
      const userStore = useUserStore();
      if (userStore && userStore.userInfoRaw) {
        targetUser = userStore.userInfoRaw;
      }
    } catch (e) { }

    // 若 store 暂无数据，降级从 localStorage 读取缓存
    if (!targetUser || typeof targetUser !== 'object' || Object.keys(targetUser).length === 0) {
      try {
        const localData = localStorage.getItem('user_info');
        if (localData) {
          targetUser = JSON.parse(localData);
        }
      } catch (e) {
        console.error('解析本地用户信息失败:', e);
      }
    }
  }

  if (!targetUser || typeof targetUser !== 'object') return false;

  // 1. 过滤游客/临时账号
  if (targetUser.temp === true || targetUser.role === '8' || targetUser.name === '游客' || targetUser.nickname === '游客') {
    return false;
  }

  // 2. VIP 标记判定 (兼容 vip > 1、vip 为 true、is_vip 为 true 等字段结构)
  const isVipFlag = (typeof targetUser.vip === 'number' ? targetUser.vip > 1 : !!targetUser.vip) ||
                    !!targetUser.is_vip ||
                    targetUser.role === 'vip' ||
                    targetUser.role === '1';

  if (!isVipFlag) return false;

  // 3. 校验过期时间 (如果包含 vip_expire)
  if (targetUser.vip_expire) {
    const expireTime = new Date(targetUser.vip_expire).getTime();
    if (!isNaN(expireTime) && expireTime < Date.now()) {
      return false; // 已过期
    }
  }

  return true;
}

export default {
  deepClone(obj) {
    if (!obj) return obj;
    return JSON.parse(JSON.stringify(obj));
  },
  generateUUID() {
    var d = new Date().getTime();
    var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
      /[xy]/g,
      function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
      }
    );
    return uuid;
  },
  checkUserVip
};
