<script lang="ts" setup>
import { ElMessageBox, ElLoading } from 'element-plus'
import { switchLogin, switchTenant } from '@/api/login/index'
import { getTenantAll } from '@/api/system/tenant'
import avatarImg from '@/assets/imgs/avatar.jpg'
import { useDesign } from '@/hooks/web/useDesign'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { useUserStore } from '@/store/modules/user'
import { resetRouter } from '@/router'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import * as authUtil from '@/utils/auth'

defineOptions({ name: 'UserInfo' })

const { t } = useI18n()

const { push, replace } = useRouter()

const userStore = useUserStore()

const { wsCache } = useCache()

const tagsViewStore = useTagsViewStore()

const { getPrefixCls } = useDesign()

const prefixCls = getPrefixCls('user-info')

const switchInfoObj = ref({
  dialog: false,
  deptId: userStore.user.loginDeptId,
  roleId: userStore.user.loginRoleId,
  tenantId: Number(authUtil.getTenantId()),
  tenantList: []
})
const loading = ref()

const avatar = computed(() => userStore.user.avatar || avatarImg)
const userName = computed(() => userStore.user.nickname ?? 'Admin')
const isSupAdminToken = computed(() => userStore.user.supAdminToken)
const currRoleList = computed(() => {
  if (switchInfoObj.value.deptId) {
    let list = [{ id: -1, name: t('common.noRole') }]
    userStore.deptInfo.forEach((dept) => {
      if (switchInfoObj.value.deptId == dept.deptId) {
        if (dept.roleInfoList.length >= 2) list.push(...dept.roleInfoList)
        else if (dept.roleInfoList.length !== 0) list = dept.roleInfoList
      }
    })
    return list
  } else return []
})
const isDisabled = computed(() => {
  const { deptId, roleId, tenantId } = switchInfoObj.value
  let bool = false
  if (isSupAdminToken.value) {
    if (tenantId == Number(authUtil.getTenantId())) bool = true
  } else if (deptId == userStore.user.loginDeptId && roleId == userStore.user.loginRoleId) {
    bool = true
  }
  return bool
})

watch(
  () => currRoleList.value,
  (list) => {
    if (list.length) {
      let isContain = false
      list.forEach((item) => {
        if (Number(item.name) === switchInfoObj.value.roleId) isContain = true
      })
      if (!isContain) switchInfoObj.value.roleId = list[0].id
    } else switchInfoObj.value.roleId = -1
  },
  { deep: true }
)

const loginOut = async () => {
  try {
    await ElMessageBox.confirm(t('common.loginOutMessage'), t('common.reminder'), {
      confirmButtonText: t('common.ok'),
      cancelButtonText: t('common.cancel'),
      type: 'warning'
    })
    await userStore.loginOut()
    tagsViewStore.delAllViews()
    resetRouter()
    window.location.href = window.location.origin + '/login?redirect=/index'
    // replace('/login?redirect=/index')
  } catch {}
}
const toProfile = async () => {
  push('/user/profile')
}
const toDocument = () => {
  window.open('http://doc.lideeyunji.com/')
}

const getTenantList = () => {
  getTenantAll().then((res) => {
    switchInfoObj.value.tenantList = res
  })
}
const openSwitchInfo = () => {
  if (isSupAdminToken.value) {
    switchInfoObj.value.tenantId = Number(authUtil.getTenantId())
  } else {
    switchInfoObj.value.deptId = userStore.user.loginDeptId
    if (currRoleList.value.length == 1) {
      switchInfoObj.value.roleId = currRoleList.value[0].id
    } else {
      switchInfoObj.value.roleId = userStore.user.loginRoleId
    }
  }

  switchInfoObj.value.dialog = true
}
const switchInfo = async () => {
  const { deptId, roleId, tenantId } = switchInfoObj.value
  loading.value = ElLoading.service({
    lock: true,
    text: '切换中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  let res: any = null
  if (isSupAdminToken.value) {
    res = await switchTenant({ tenantId }).catch(() => false)
  } else {
    res = await switchLogin({ loginDeptId: deptId, loginRoleId: roleId }).catch(() => false)
  }
  loading.value?.close()
  if (!res) return
  authUtil.setTenantId(tenantId + '')
  authUtil.setToken(res)
  wsCache.delete(CACHE_KEY.USER)
  wsCache.delete(CACHE_KEY.ROLE_ROUTERS)
  location.reload()
}

if (isSupAdminToken.value) getTenantList()
</script>

<template>
  <ElDropdown class="custom-hover" :class="prefixCls" trigger="click">
    <div class="flex items-center">
      <ElAvatar
        :src="avatar"
        alt=""
        class="w-[calc(var(--logo-height)-25px)] rounded-[50%] b-solid b-1px b-#f1f1f1"
      />
      <span class="pl-[5px] text-14px text-[var(--top-header-text-color)] <lg:hidden">
        {{ userName }}
      </span>
    </div>
    <template #dropdown>
      <ElDropdownMenu>
        <ElDropdownItem @click="toProfile">
          <Icon icon="ep:tools" />
          <div>{{ t('common.profile') }}</div>
        </ElDropdownItem>
        <ElDropdownItem
          v-if="!userStore.user.supAdmin && !userStore.user.tenantAdmin"
          @click="openSwitchInfo"
        >
          <Icon icon="material-symbols:directory-sync-rounded" />
          <div>{{ t('common.switchInfo') }}</div>
        </ElDropdownItem>

        <ElDropdownItem divided @click="loginOut">
          <Icon icon="ep:switch-button" />
          <div>{{ t('common.loginOut') }}</div>
        </ElDropdownItem>
      </ElDropdownMenu>
    </template>
  </ElDropdown>
  <ElDialog
    class="avue-dialog switch-info-dialog"
    v-model="switchInfoObj.dialog"
    :title="isSupAdminToken ? t('common.switchTenant') : t('common.switchInfo')"
    append-to-body
    width="400"
  >
    <div v-if="isSupAdminToken">
      <div class="flex items-center gap-x-10px">
        <span class="flex-basis-80px text-right">{{ t('common.tenant') }}：</span>
        <avue-select
          v-model="switchInfoObj.tenantId"
          :placeholder="t('common.selectText') + t('common.tenant')"
          :dic="switchInfoObj.tenantList"
          :props="{ label: 'name', value: 'id' }"
          :clearable="false"
        ></avue-select>
      </div>
    </div>
    <div v-else>
      <div class="flex items-center gap-x-10px">
        <span class="flex-basis-80px text-right">{{ t('common.dept') }}：</span>
        <avue-select
          v-model="switchInfoObj.deptId"
          :placeholder="t('common.selectText') + t('common.dept')"
          :dic="userStore.deptInfo"
          :props="{ label: 'deptName', value: 'deptId' }"
          :clearable="false"
        ></avue-select>
      </div>
      <div class="flex items-center gap-x-10px mt-12px">
        <span class="flex-basis-80px text-right">{{ t('common.role') }}：</span>
        <avue-select
          v-model="switchInfoObj.roleId"
          :placeholder="t('common.selectText') + t('common.role')"
          :dic="currRoleList"
          :props="{ label: 'name', value: 'id' }"
          :clearable="false"
        ></avue-select>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="switchInfoObj.dialog = false">{{ t('common.close') }}</el-button>
        <el-button type="primary" :disabled="isDisabled" @click="switchInfo">
          {{ t('common.ok') }}
        </el-button>
      </div>
    </template>
  </ElDialog>
</template>

<style lang="scss">
.switch-info-dialog {
  .el-dialog__body {
    padding-bottom: 20px;
  }

  .el-dialog__footer {
    width: 100%;
    padding: 10px 16px;
    background-color: #fff;
    border-top: 1px solid #f0f0f0;
    box-sizing: border-box;
  }
}
</style>
