import { defineStore } from 'pinia'
import { loginByCode, loginByEmail, refreshTokenApi } from '@/api/login'
import type { LoginResponseDto } from '@/api/login/types'
/**
 * 关于用户的store
 */
export const useUserStore = defineStore('user', () => {
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}') as LoginResponseDto)
  const token = ref(localStorage.getItem('token') || '')
  const refreshToken = ref(localStorage.getItem('refreshToken') || '')
  // 获取用户信息
  const fetchUserInfo = async () => {
    // {
    //   email: 'lijiabin@yswg.com.cn',
    //   password: 'Lijiabin123.',
    // }
    // {
    //   email: 'wangshouyong@yswg.com.cn',
    //   password: 'Wsy123456!',
    // }
    const { data } = await loginByEmail({
      email: 'lijiabin@yswg.com.cn',
      password: 'Lijiabin123.',
    })
    // const { data } = await loginByEmail({
    //   email: 'wangshouyong@yswg.com.cn',
    //   password: 'Wsy123456!',
    // })
    setUserInfo(data)
  }

  // 根据code 获取用户信息
  const getUserInfoByCode = async ({
    code,
    isCodeLogin,
    cutEmail,
  }: {
    code: string
    isCodeLogin: number
    cutEmail?: string
  }) => {
    const { data } = await loginByCode({ code, isCodeLogin, cutEmail })
    console.log(data)
    setUserInfoAndToken(data)
  }
  const getNewToken = async () => {
    const { data } = await refreshTokenApi(refreshToken.value)
    setUserInfoAndToken(data)
  }
  const setUserInfoAndToken = (data: LoginResponseDto) => {
    setUserInfo(data)
    setToken(data.token)
    setRefreshToken(data.refreshToken)
  }

  const clearAllUserInfo = () => {
    userInfo.value = {} as LoginResponseDto
    token.value = ''
    refreshToken.value = ''
    localStorage.removeItem('userInfo')
    localStorage.removeItem('token')
    localStorage.removeItem('refreshToken')
  }

  const setUserInfo = (info: LoginResponseDto) => {
    userInfo.value = info
    // session存一份
    localStorage.setItem('userInfo', JSON.stringify(info))
  }
  const setToken = (str: string) => {
    token.value = str
    // session存一份
    localStorage.setItem('token', str)
  }
  const setRefreshToken = (str: string) => {
    refreshToken.value = str
    localStorage.setItem('refreshToken', str)
  }
  // window.setToken = (str: string) => {
  //   setToken(str)
  // }

  return {
    userInfo,
    token,
    fetchUserInfo,
    setUserInfo,
    setToken,
    getUserInfoByCode,
    refreshToken,
    getNewToken,
    clearAllUserInfo,
  }
})
