import { defineStore } from 'pinia'
import { sessionStorage } from '@/plugins/storage'
import useFetch from '@/hooks/useFetch'

import type { ExtractApiResponse } from '@/api/api'
interface MainStoreState {
  bootstrapTime: number
  loginSuccessTime: number
  serverTime: number
  diffTime: number
  loginInfo?: ExtractApiResponse<'userLogin'>
  myUserInfo?: ExtractApiResponse<'getMyUserInfo'>
}

interface MainStoreActions {
  getMyUserInfo: () => Promise<ExtractApiResponse<'getMyUserInfo'> | undefined>
}

const useMainStore = defineStore<'main', MainStoreState, Record<string, any>, MainStoreActions>('main', {
  state() {
    return {
      /** 进入系统的时间 */
      bootstrapTime: Date.now(),
      /** 登录成功时间 */
      loginSuccessTime: Date.now(),
      /** 服务器时间 */
      serverTime: Date.now(),
      /** 时间差 */
      diffTime: 0,
      /** 用户登录信息 */
      loginInfo: (sessionStorage.get('LOGIN_RESULT') as ExtractApiResponse<'userLogin'>) ?? void 0,
      /** 当前用户信息 */
      myUserInfo: void 0,
    }
  },
  actions: {
    async getMyUserInfo() {
      try {
        this.myUserInfo = await useFetch('getMyUserInfo').fetch()
        return this.myUserInfo
      } catch (error) {
        console.warn(error)
      }
    },
  },
})

export default useMainStore
