import { defineStore } from 'pinia'
import { ref } from 'vue'
import { bindUser } from '@/api/common'
import { getUserInfo as _getUserInfo, login as _login } from '@/api/login'
import { t } from '@/locale'
import { toPage } from '@/utils/page'
import { toast } from '@/utils/toast'

// 初始化状态
const userInfoState: any = {
  headPic: '/static/images/default-avatar.png',
}

export const useUserStore = defineStore(
  'user',
  () => {
    // 定义用户信息
    const userInfo = ref<any>({ ...userInfoState })
    const token = ref<string>('')
    // 设置用户信息
    const setUserInfo = (val: any) => {
      console.log('设置用户信息', val)
      userInfo.value = val
    }
    // 删除用户信息
    const removeUserInfo = () => {
      userInfo.value = { ...userInfoState }
      token.value = ''
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('token')
    }
    /**
     * 获取用户信息
     */
    const getUserInfo = async () => {
      const res = await _getUserInfo()
      const userInfo = res.data
      setUserInfo(userInfo)
      uni.setStorageSync('userInfo', userInfo)
      return res
    }

    /**
     * 用户登录
     * @param loginData 登录数据
     * @param redirect 登录成功后的跳转地址，默认跳转到首页
     */
    const login = async (loginData: any, redirect?: string) => {
      try {
        // 显示加载状态
        uni.showLoading({
          title: t('auth.login.loading'),
          mask: true,
        })

        // 调用登录接口
        const res = await _login(loginData)

        uni.hideLoading()

        // 登录成功，保存 token
        if (res.code === '200' && res.data && res.data.token) {
          token.value = res.data.token
          uni.setStorageSync('token', res.data.token)
          // 绑定到用户需要调用的
          bindUser({ jpushDeviceId: uni.getStorageSync('registerID') })
          // 获取用户信息
          await getUserInfo()
        }

        // 登录成功提示
        toast.success(t('auth.login.success'))

        // 跳转到指定页面或默认首页
        setTimeout(() => {
          if (redirect) {
            // 使用 toPage 方法，自动判断是否为 tabBar 页面
            toPage({ url: decodeURIComponent(redirect), isRedirect: true })
          }
          else {
            // 默认跳转到首页
            toPage({ url: '/pages/index/index', isReLaunch: true })
          }
        }, 1500)

        return res
      }
      catch (error) {
        uni.hideLoading()
        toast.error(error.message || t('auth.login.error.failed'))
        throw error
      }
    }

    return {
      userInfo,
      token,
      getUserInfo,
      setUserInfo,
      removeUserInfo,
      login,
    }
  },
  {
    persist: true,
  },
)
