import { ref, toRefs } from 'vue'
import { defineStore } from 'pinia'
import * as userApi from '@/api/user'
import { useRoute, useRouter } from 'vue-router'

type LoginParams = {
  account: string
  password: string
}

type UserInfo = {
  tokenName: string // token名称
  tokenValue: string // token值
  isLogin: string // 是否已登录
  loginId: string // 此token对应的LoginId，未登录时为null
  loginType: string // 多账号体系下的账号类型
  tokenTimeout: string // token 剩余有效期（单位: 秒）
  sessionTimeout: string // Account-Session 剩余有效时间（单位: 秒）
  tokenSessionTimeout: string // Token-Session 剩余有效时间（单位: 秒）
  loginDeviceType: string // 登录设备类型
  tags: string // 自定义数据（暂无意义，留作扩展）
  phone: string // 手机号
  userId: number // userId
  account: string // 账户
}

export const useUserStore = defineStore(
  'user',
  () => {
    const route = useRoute()
    const router = useRouter()

    const userInfo = ref<UserInfo>({
      tokenName: '',
      tokenValue: '',
      isLogin: '',
      loginId: '',
      loginType: '',
      tokenTimeout: '',
      sessionTimeout: '',
      tokenSessionTimeout: '',
      loginDeviceType: '',
      tags: '',
      phone: '',
      userId: 0,
      account: '',
    })

    // 登录
    function login(params: LoginParams) {
      const redirectPath = route.query.redirect as string
      console.log('🚀🚀🚀userStore Login', params, redirectPath)
      return new Promise((resolve, reject) => {
        userApi
          .login(params)
          .then((res) => {
            console.log('🚀🚀🚀userStore Login res', res)
            userInfo.value = res.data
            resolve(res)
            if (redirectPath) {
              router.replace(redirectPath)
            } else {
              router.replace({ path: '/' })
            }
          })
          .catch((err) => {
            console.log('🚀🚀🚀userStore Login err', err)
            reject(err)
          })
      })
    }

    // 退出登录
    async function logout(active = false) {
      if (userInfo.value.tokenValue && active) {
        try {
          const res = await userApi.logout()
          console.log('✅ userStore logout success', res)
        } catch (error) {
          console.log('❌ userStore logout error', error)
        }
      }
      userInfo.value = {
        tokenName: '',
        tokenValue: '',
        isLogin: '',
        loginId: '',
        loginType: '',
        tokenTimeout: '',
        sessionTimeout: '',
        tokenSessionTimeout: '',
        loginDeviceType: '',
        tags: '',
        phone: '',
        userId: 0,
        account: '',
      }
      const redirectPath = router.currentRoute.value.fullPath || ''
      console.log('✅ userStore Logout', redirectPath)
      if (router.currentRoute.value.name === 'login') return
      router.push({
        name: 'login',
        // query: {
        //   redirect: redirectPath,
        // },
      })
    }

    // 获取用户信息
    function getUserInfo() {
      return toRefs(userInfo.value)
    }

    return { login, logout, getUserInfo, userInfo }
  },
  {
    persist: {
      key: `${import.meta.env.VITE_STOTRE_NAME}_USER_INFO`,
      storage: localStorage,
    },
  }
)
