// stores/user.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import USER from '@/api/user.js'

export const useUserStore = defineStore('user', () => {
  const token = ref(uni.getStorageSync('token') || null)
  const userInfo = ref(uni.getStorageSync('userInfo') || null)
  const isLogging = ref(false)

  const login = async () => {
    // if (isLogging.value) {
    //   throw new Error('登录正在进行中')
    // }

    isLogging.value = true
    
    try {
      let loginData = null

      // #ifdef MP-WEIXIN
      loginData = await new Promise((resolve, reject) => {
        uni.login({
          success: async ({ code }) => {
            try {
              const { data } = await USER.fetchLogin({ code })
              resolve(data)
            } catch (error) {
              reject(error)
            }
          },
          fail: reject
        })
      })
      // #endif

      // #ifdef H5
      const { data } = await USER.userInfo()
      loginData = data
      // #endif
		uni.setStorageSync('userInfo', loginData);
		uni.setStorageSync('token', loginData.token);
      if (loginData) {
        const { token: newToken, ...userData } = loginData
        
        if (newToken) {
          token.value = newToken
          uni.setStorageSync('token', newToken)
        }
        
        userInfo.value = userData
        // uni.setStorageSync('userInfo', userData)
        
        return loginData
      } else {
        throw new Error('登录失败：未获取到数据')
      }

    } catch (error) {
      token.value = null
      userInfo.value = null
      uni.removeStorageSync('token')
      uni.removeStorageSync('userInfo')
      throw error
    } finally {
      isLogging.value = false
    }
  }

  const getTokenSafe = async () => {
    if (token.value) {
      return token.value
    }
    
    try {
      const result = await login()
      return result.token || token.value
    } catch (error) {
      console.error('自动登录失败', error)
      throw error
    }
  }

  return {
    token,
    userInfo,
    isLogging,
    login,
    getTokenSafe
  }
})