/** @format */

import { ref } from 'vue'
import { defineStore } from 'pinia'
import { useCommonStore } from './common'
import { loginApi, logoutApi } from '~/api/model/user'

interface LoginRequestData {
  email: string
  password: string
  type: 'google' | 'email'
}

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = shallowRef<any>()
    const token = shallowRef<any>()
    const isLogin = computed(() => !!token.value)
    const avatar = computed(() => userInfo.value?.avatar)
    const nickname = computed(() => userInfo.value?.email)
    // 是否提交过的信息
    const isCompletedInfo = computed(() => {
      return !!(+userInfo.value?.infoState)
    })

    /** 登录操作 */
    const login = async (params: LoginRequestData) => {
      try {
        const data: any = await loginApi(params)
        const { token: userToken, userInfo: userDataInfo } = data
        userInfo.value = userDataInfo
        token.value = userToken
        ElMessage({
          message: 'Login success',
          type: 'success',
          plain: true,
        })
        const commonStore = useCommonStore()
        commonStore.pushAccount({ email: userDataInfo.email, name: `${userDataInfo.firstName} ${userDataInfo.lastName}`, type: params.type })
      }
      catch (error) {
        return Promise.reject(error)
      }
    }
    const updateUserInfo = (data: any) => {
      userInfo.value = { ...userInfo.value, ...data }
    }
    /** 退出登录操作 */
    const logout = async () => {
      try {
        if (token.value) {
          await logoutApi()
          document.cookie
            = 'user=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/'
          ElMessage({
            message: 'Exit successful',
            type: 'success',
            plain: true,
          })
          window.location.reload()
        }
      }
      finally {
        token.value = null
        userInfo.value = undefined
        const router = useRouter()
        router.push('/')
      }
    }
    return { userInfo, isCompletedInfo, updateUserInfo, token, login, logout, isLogin, avatar, nickname }
  },
  {
    persist: true,
  },
)