import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { userApi } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref(uni.getStorageSync('userInfo') || null)
  const loginPopupVisible = ref(false)
  
  // 计算属性
  const isLoggedIn = computed(() => !!userInfo.value?.openid)
  const userId = computed(() => userInfo.value?.userId)
  const userName = computed(() => userInfo.value?.username)
  
  // 方法
  const showLoginPopup = () => {
    loginPopupVisible.value = true
  }
  
  const hideLoginPopup = () => {
    loginPopupVisible.value = false
  }
  
  const setUserInfo = (info) => {
    userInfo.value = info
    uni.setStorageSync('userInfo', info)
  }
  
  const clearUserInfo = () => {
    userInfo.value = null
    uni.removeStorageSync('userInfo')
  }
  
  // 登录方法
  const wechatLogin = async (code) => {
    console.log('wechatLogin', code)
    try {

      const data = await userApi.login({ code })
      setUserInfo(data)
      return data
    } catch (error) {
      console.error('微信登录失败：', error)
      throw error
    }
  }
  
  const accountLogin = async (username, password) => {
    try {
      const data = await userApi.mobileLogin({ username, password })
      setUserInfo(data)
      return data
    } catch (error) {
      console.error('账号登录失败：', error)
      throw error
    }
  }

  // 登出
  const logout = () => {
    clearUserInfo()
    uni.reLaunch({
      url: '/pages/parent/index'
    })
  }
  
  return {
    // 状态
    userInfo,
    loginPopupVisible,
    // 计算属性
    isLoggedIn,
    userId,
    userName,
    // 方法
    showLoginPopup,
    hideLoginPopup,
    setUserInfo,
    clearUserInfo,
    wechatLogin,
    accountLogin,
    logout
  }
})