<template>
  <ElDialog
    v-model="visible"
    :title="t('tenant.more.impersonate.title')"
    width="560px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <div v-loading="submitting">
      <ElAlert
        :title="t('tenant.more.impersonate.tip')"
        type="warning"
        :closable="false"
        show-icon
        class="mb-4"
      />

      <ElDescriptions :column="1" border>
        <ElDescriptionsItem :label="t('tenant.table.name')">{{
          tenantName || '-'
        }}</ElDescriptionsItem>
        <ElDescriptionsItem :label="t('tenant.table.code')">{{
          tenantCode || '-'
        }}</ElDescriptionsItem>
        <ElDescriptionsItem :label="t('tenant.table.status')">
          <ElTag :type="statusTagType">{{ statusText }}</ElTag>
        </ElDescriptionsItem>
      </ElDescriptions>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="visible = false">{{ t('common.cancel') }}</ElButton>
        <ElButton type="primary" :loading="submitting" @click="handleSubmit">
          {{ t('tenant.more.impersonate.confirm') }}
        </ElButton>
      </span>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage } from 'element-plus'
  import { TenantStatus } from '@/enums/TenantStatus'
  import { fetchImpersonateTenant } from '@/api/tenant'
  import { useImpersonationStore } from '@/store/modules/impersonation'

  defineOptions({ name: 'TenantImpersonateDialog' })

  const { t } = useI18n()
  const impersonationStore = useImpersonationStore()

  const emit = defineEmits<{
    (e: 'success'): void
  }>()

  const visible = ref(false)
  const submitting = ref(false)
  const tenantId = ref<string>('')
  const tenantName = ref<string>('')
  const tenantCode = ref<string>('')
  const tenantStatus = ref<number>(TenantStatus.Active)

  const statusTagType = computed(() => {
    switch (tenantStatus.value) {
      case TenantStatus.Active:
        return 'success'
      case TenantStatus.Suspended:
        return 'danger'
      case TenantStatus.PendingReview:
        return 'warning'
      case TenantStatus.Expired:
        return 'warning'
      default:
        return 'info'
    }
  })

  const statusText = computed(() => {
    switch (tenantStatus.value) {
      case TenantStatus.Active:
        return t('tenant.status.active')
      case TenantStatus.Suspended:
        return t('tenant.status.suspended')
      case TenantStatus.PendingReview:
        return t('tenant.status.pendingReview')
      case TenantStatus.Expired:
        return t('tenant.status.expired')
      case TenantStatus.Closed:
        return t('tenant.status.closed')
      default:
        return t('tenant.status.unknown')
    }
  })

  const open = (row: Api.Tenant.TenantDto) => {
    visible.value = true

    // 1. 记录当前租户信息
    tenantId.value = row.id
    tenantName.value = row.name
    tenantCode.value = row.code
    tenantStatus.value = row.status
  }

  const handleClosed = () => {
    // 1. 关闭时清理状态
    tenantId.value = ''
    tenantName.value = ''
    tenantCode.value = ''
    tenantStatus.value = TenantStatus.Active
  }

  const handleSubmit = async () => {
    if (!tenantId.value) return

    // 1. 已处于伪装态时禁止重复伪装
    if (impersonationStore.isImpersonating) {
      ElMessage.warning(t('tenant.more.impersonate.alreadyImpersonating'))
      return
    }

    submitting.value = true
    try {
      // 2. 执行伪装登录并切换会话
      const token = await fetchImpersonateTenant(tenantId.value)
      await impersonationStore.start(token)

      // 3. 提示并关闭
      ElMessage.success(t('tenant.more.impersonate.success'))
      emit('success')
      visible.value = false
    } catch (error) {
      console.error(error)
    } finally {
      submitting.value = false
    }
  }

  defineExpose({ open })
</script>
