import useTabbarStore from './tabbar'
import useRouteStore from './route'
import useMenuStore from './menu'
import { getPermit, signIn, signOut, updatePassword } from '@/api'
import storage from '@/utils/storage'

const useUserStore = defineStore(
  // 唯一ID
  'user',
  () => {
    const tabbarStore = useTabbarStore()
    const routeStore = useRouteStore()
    const menuStore = useMenuStore()

    const account = ref(storage.local.get('account') ?? '')
    const userData = ref(storage.local.get('userData'))
    const token = ref(storage.local.get('token') ?? '')
    const failure_time = ref(storage.local.get('failure_time') ?? '')
    const permissions = ref<string[]>([])
    const isLogin = computed(() => {
      let retn = false
      if (token.value) {
        if (new Date().getTime() < parseInt(failure_time.value)) {
          retn = true
        }
      }
      return retn
    })

    // 登录
    function login(username: string, password: string) {
      return new Promise<void>((resolve, reject) => {
        const f = new FormData()
        f.append('username', username)
        f.append('password', password)
        signIn(f).then((res) => {
          storage.local.set('account', res.data.user.userName)
          storage.local.set('userData', res.data.user)
          storage.local.set('token', res.data.accessToken)
          storage.local.set('failure_time', res.data.leaseTime)
          userData.value = res.data.user
          token.value = res.data.accessToken
          failure_time.value = res.data.leaseTime
          resolve()
        }).catch((error) => {
          reject(error)
        })
      })
    }
    interface USER {
      ocId: string
      grantGroupId: number
      grantGroupName: string
      groupId: number
      groupName: string
      mapId: number
      ocAdminId: number
      ocGroupId: number
      ocName: string
      ocTypeId: number
      positionId: number
      positionName: string
      roleCode: number
      roleId: number
      roleName: string
      roleTypeId: number
      userAvatar: string
      userId: number
      userIntro: string
      userName: string
      userPhone: number
      userPhoto: string
      userRealName: string
    }
    function getUserData() {
      return userData as unknown as USER
    }

    // 登出
    async function logout() {
      await signOut()
      storage.local.remove('account')
      storage.local.remove('userData')
      storage.local.remove('token')
      storage.local.remove('failure_time')
      account.value = ''
      userData.value = null
      token.value = ''
      failure_time.value = ''
      permissions.value = []
      tabbarStore.clean()
      routeStore.removeRoutes()
      menuStore.setActived(0)
    }

    // 获取我的权限
    async function getPermissions() {
      const res = await getPermit()
      permissions.value = res.data
      return permissions.value
    }

    // 修改密码
    async function editPassword(data: {
      accountId: number
      password: string
    }) {
      await updatePassword({
        accountId: data.accountId,
        password: data.password,
      })
    }

    return {
      account,
      getUserData,
      token,
      permissions,
      isLogin,
      login,
      logout,
      getPermissions,
      editPassword,
    }
  },
)

export default useUserStore
