import { defineStore } from 'pinia'
import { loginByCode, loginByEmail, refreshTokenApi, getChunkApiAuthToken } from '@/api'
import type { LoginResponseDto } from '@/api/login/types'
import { useStorage } from '@vueuse/core'
/**
 * 关于用户的store
 */
export const useUserStore = defineStore('user', () => {
  const userInfo = useStorage<LoginResponseDto>('userInfo', {} as LoginResponseDto)
  const token = useStorage<string>('token', '')
  const refreshToken = useStorage<string>('refreshToken', '')
  const chunkApiAuthToken = useStorage<string>('chunkApiAuthToken', '')
  // 获取用户信息
  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 })
    setUserInfoAndToken(data)

    // 同时获取关于分片的token
    const token = await getChunkApiAuthToken(data.account)
    setChunkApiAuthToken(token)
  }
  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 setChunkApiAuthToken = (str: string) => {
    chunkApiAuthToken.value = str
    localStorage.setItem('chunkApiAuthToken', str)
  }
  const setRefreshToken = (str: string) => {
    refreshToken.value = str
    localStorage.setItem('refreshToken', str)
  }
  // window.setToken = (str: string) => {
  //   setToken(str)
  // }

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