import { defineStore } from 'pinia'
import { loginByCode, loginByEmail } from '@/api/login'
import type { LoginResponseDto } from '@/api/login/types'
/**
 * 关于用户的store
 */
export const useUserStore = defineStore('user', () => {
  const userInfo = ref(JSON.parse(sessionStorage.getItem('userInfo') || '{}') as LoginResponseDto)
  // const token = ref(localStorage.getItem('token') || '')
  const token = ref(sessionStorage.getItem('token') || '')
  // 获取用户信息
  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)
    setUserInfo(data)
    setToken(data.token)
  }

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

  return { userInfo, token, fetchUserInfo, setUserInfo, setToken, getUserInfoByCode }
})
