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
    }
  }

  // H5手动登录 - 跳转到H5登录页面
  const showH5Login = async () => {
    console.log('🔐 获取微信授权码并跳转到H5登录页面')

    try {
      // 获取微信授权码
      const loginRes = await uni.login({
        provider: 'weixin'
      })

      console.log('获取到微信授权码:', loginRes.code)

      // 跳转到H5登录页面，传递wechatCode
      uni.navigateTo({
        url: `/pages/common/webview?dest=login&title=登录&wechatCode=${loginRes.code}`
      })

    } catch (error) {
      console.error('获取微信授权码失败:', error)
      // 降级处理：不传wechatCode
      uni.navigateTo({
        url: '/pages/common/webview?dest=login&title=登录'
      })
    }
  }

  // H5自动登录 - 跳转到H5自动登录页面
  const showH5AutoLogin = () => {
    console.log('🔄 跳转到H5自动登录页面')

    // 获取yhsbToken，有token就自动登录，没有就手动登录
    const userInfo = uni.getStorageSync('userInfo') || {}
    const yhsbToken = userInfo.yhsbToken

    if (yhsbToken) {
      uni.navigateTo({
        url: `/pages/common/webview?dest=autoLogin&title=自动登录&yhsbToken=${yhsbToken}`
      })
    } else {
      console.log('⚠️ 未找到yhsbToken，跳转手动登录')
      showH5Login()
    }
  }

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