import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  const userId = ref(null)
  const userInfo = ref(null)
  const vipInfo = ref(null)
  
  // 获取VIP状态
  const isVIP = computed(() => {
    if (!vipInfo.value) return false
    return new Date(vipInfo.value.expireTime) > new Date()
  })
  
  // 用户登录
  const login = async (username, password) => {
    const res = await uni.request({
      url: 'https://api.aiyadianzi.ltd/auth/login',
      method: 'POST',
      data: { username, password }
    })
    
    userId.value = res.data.userId
    userInfo.value = res.data.userInfo
    vipInfo.value = res.data.vipInfo
    
    uni.setStorageSync('token', res.data.token)
  }
  
  // 购买VIP
  const purchaseVIP = async (plan) => {
    const res = await uni.request({
      url: 'https://api.aiyadianzi.ltd/vip/purchase',
      method: 'POST',
      data: {
        userId: userId.value,
        planId: plan.id
      },
      header: { Authorization: `Bearer ${uni.getStorageSync('token')}` }
    })
    
    vipInfo.value = {
      type: plan.type,
      expireTime: res.data.expireTime
    }
  }
  
  // 初始化用户
  const initUser = async () => {
    const token = uni.getStorageSync('token')
    if (!token) return
    
    try {
      const res = await uni.request({
        url: 'https://api.aiyadianzi.ltd/auth/profile',
        header: { Authorization: `Bearer ${token}` }
      })
      
      userId.value = res.data.userId
      userInfo.value = res.data.userInfo
      vipInfo.value = res.data.vipInfo
    } catch (err) {
      console.error('用户初始化失败', err)
      uni.removeStorageSync('token')
    }
  }
  
  return { 
    userId, 
    userInfo, 
    vipInfo, 
    isVIP, 
    login, 
    purchaseVIP, 
    initUser 
  }
})