import { defineStore } from 'pinia'
import { userInfoType } from './storeType'
import { getUserInfoApi } from '@/api/user'

interface userState {
  token: null | string
  userId: null | number
  tabbarHeight: null | string
  userInfo: null | userInfoType
  navigaterHeight: null | string
}

export const useCounterStore = defineStore('counter', {
  state: (): userState => ({
    token: null,
    userId: null,
    userInfo: null,
    tabbarHeight: '3.16rem',
    navigaterHeight: '3.13rem'
  }),
  actions: {
    async getUserInfo() {
      // 调用获取个人信息接口 来判断是否需要跳转登录页
      const res = await getUserInfoApi({ user_id: this.$state.userInfo?.user_id })
      if (res.code === 1) {
        uni.setStorageSync('userInfo', res.data)
        this.$state.userInfo = res.data
      }
    },
    // 清除个人信息
    clearState() {
      this.$state = {
        token: null,
        userId: null,
        userInfo: null,
        tabbarHeight: '5.503rem'
      } as userState
      uni.removeStorageSync('token')
      uni.removeStorageSync('userId')
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('tabbarHeight')
      this.getUserInfo()
    }
  }
})
