import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { getToken, setToken, removeToken, getUserInfo, setUserInfo, removeUserInfo } from '../utils/storage';
import { get, post } from '../utils/request';
import type { UserInfo, MemberStatus } from '../types';

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string | null>(getToken());
  const userInfo = ref<UserInfo | null>(getUserInfo<UserInfo>());
  const memberStatus = ref<MemberStatus | null>(null);

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value);
  const isMember = computed(() => memberStatus.value?.isValid && memberStatus.value.level > 0);

  // 初始化用户状态
  function initUser() {
    // 检查是否有保存的登录状态
    const savedToken = getToken();
    const savedUserInfo = getUserInfo<UserInfo>();

    // 如果有有效的登录状态，使用它
    if (savedToken && savedUserInfo && savedToken !== 'test-token-for-dev') {
      token.value = savedToken;
      userInfo.value = savedUserInfo;
      fetchMemberStatus();
    }
    // 否则不设置默认用户，等待用户主动登录
  }

  // 登录
  async function login(phone: string, code: string) {
    const inviteCode = uni.getStorageSync('invite_code') || '';

    const result = await post<{
      token: string;
      user: UserInfo;
    }>('/auth/login', { phone, code, inviteCode });

    token.value = result.token;
    userInfo.value = result.user;
    setToken(result.token);
    setUserInfo(result.user);

    // 清除已使用的邀请码
    if (inviteCode) {
      uni.removeStorageSync('invite_code');
    }

    await fetchMemberStatus();
    return result;
  }

  // 发送验证码
  async function sendCode(phone: string) {
    return post('/auth/send-code', { phone });
  }

  // 获取用户信息
  async function fetchUserInfo() {
    const info = await get<UserInfo>('/auth/user-info');
    userInfo.value = info;
    setUserInfo(info);
    return info;
  }

  // 获取会员状态
  async function fetchMemberStatus() {
    try {
      const status = await get<MemberStatus>('/member/status');
      memberStatus.value = status;
      return status;
    } catch {
      memberStatus.value = null;
      return null;
    }
  }

  // 登出
  function logout() {
    token.value = null;
    userInfo.value = null;
    memberStatus.value = null;
    removeToken();
    removeUserInfo();
  }

  // 更新用户信息
  function updateUserInfo(info: Partial<UserInfo>) {
    if (userInfo.value) {
      userInfo.value = { ...userInfo.value, ...info };
      setUserInfo(userInfo.value);
    }
  }

  return {
    // 状态
    token,
    userInfo,
    memberStatus,
    // 计算属性
    isLoggedIn,
    isMember,
    // 方法
    initUser,
    login,
    sendCode,
    fetchUserInfo,
    fetchMemberStatus,
    logout,
    updateUserInfo,
  };
});