import { defineStore } from 'pinia'
import { store } from '../index'
import { UserLoginType, UserType, UserState, IDeptType } from '../../api/types/login'
import { ElMessageBox } from 'element-plus'
import { useI18n } from '../../hooks/web/useI18n'
import { codeLogout, loginOutApi } from '../../api/login'
// import { useTagsViewStore } from './tagsView'
// @ts-ignore
import router from '@/router'
import { usePermissionStoreWithOut } from './permission'

export const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      userInfo: undefined,
      // tokenKey: 'Authorization',
      tokenKey: 'accessToken',
      token: '',
      roleRouters: undefined,
      // 记住我
      rememberMe: true,
      loginInfo: undefined,
      appInfo: undefined,
      btnAuth: []
    }
  },
  getters: {
    getTokenKey(): string {
      return this.tokenKey
    },
    getToken(): string {
      return this.token
    },
    getUserInfo(): UserType | undefined {
      return this.userInfo
    },
    // 获取用户的部门组
    getUserDeptList(): IDeptType[] | undefined {
      return this.userInfo?.deptList
    },
    // 获取用户的部门id
    getUserDeptId(): number {
      return (this.userInfo?.deptList as [{ deptId: number }])[0]?.deptId || 0
    },
    // 获取用户的部门所属区划
    getUserDistrictNo(): string {
      return (this.userInfo?.deptList as [{ districtNo: string }])[0]?.districtNo || ''
    },
    // 获取系统code
    getAppCode(): string | undefined {
      return this.userInfo?.appInfo?.appCode
    },
    // 获取系统id
    getAppId(): number | undefined {
      return this.userInfo?.appInfo?.appId
    },
    getRoleRouters(): string[] | AppCustomRouteRecordRaw[] | undefined {
      return this.roleRouters
    },
    getRememberMe(): boolean {
      return this.rememberMe
    },
    getLoginInfo(): UserLoginType | undefined {
      return this.loginInfo
    },
    getBtnAuth(): any[] | undefined {
      return this.btnAuth
    }
  },
  actions: {
    setBtnAuth(btn: any[]) {
      this.btnAuth = btn
    },
    setTokenKey(tokenKey: string) {
      this.tokenKey = tokenKey
    },
    setToken(token: string) {
      this.token = token
    },
    setUserInfo(userInfo?: UserType) {
      this.userInfo = userInfo
    },
    setRoleRouters(roleRouters: string[] | AppCustomRouteRecordRaw[]) {
      this.roleRouters = roleRouters
    },
    logoutConfirm() {
      const { t } = useI18n()

      ElMessageBox.confirm(t('common.loginOutMessage'), t('common.reminder'), {
        confirmButtonText: t('common.ok'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      })
        .then(async () => {
          await this.logout()
        })
        .catch(() => {})
    },
    // 重置数据
    reset() {
      // const tagsViewStore = useTagsViewStore()
      // tagsViewStore.delAllViews()
      this.setToken('')
      this.setUserInfo(undefined)
      this.setRoleRouters([])

      const usePermissionStore = usePermissionStoreWithOut()
      usePermissionStore.resetAddRouters()
    },
    async logout() {
      // 有flag的 要跳转至logout返回的登录页
      if (sessionStorage.getItem('flag')) {
        const res = await codeLogout({})
        if (res) {
          window.location.href = res?.attachments?.serverPortalUrl
        }
      } else {
        // 内登录模式退出
        const res = await loginOutApi()
        if (res) {
          router.replace('/login')
        }
      }
      this.reset()
    },
    setRememberMe(rememberMe: boolean) {
      this.rememberMe = rememberMe
    },
    setLoginInfo(loginInfo: UserLoginType | undefined) {
      this.loginInfo = loginInfo
    }
  },
  persist: true
})

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
