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

      <ElDescriptions :column="2" border class="mb-4">
        <ElDescriptionsItem :label="t('tenant.table.name')">{{
          tenantName || '-'
        }}</ElDescriptionsItem>
        <ElDescriptionsItem :label="t('tenant.table.code')">{{
          tenantCode || '-'
        }}</ElDescriptionsItem>
      </ElDescriptions>

      <ElForm label-width="110px">
        <ElFormItem :label="t('tenant.more.resetAdmin.resetUrl')">
          <ElInput v-model="resetUrl" readonly :placeholder="t('tenant.more.resetAdmin.empty')">
            <template #append>
              <ElButton :disabled="!resetUrl" @click="handleCopy">
                {{ t('tenant.more.resetAdmin.copy') }}
              </ElButton>
            </template>
          </ElInput>
        </ElFormItem>
      </ElForm>
    </div>

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

<script setup lang="ts">
  import { ref } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage } from 'element-plus'
  import { fetchCreateTenantAdminResetLink } from '@/api/tenant'

  defineOptions({ name: 'TenantResetAdminDialog' })

  const { t } = useI18n()

  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 resetUrl = ref<string>('')

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

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

    // 2. 重置展示
    resetUrl.value = ''
  }

  const handleClosed = () => {
    // 1. 关闭时清理状态（链接只展示一次，不做持久化）
    tenantId.value = ''
    tenantName.value = ''
    tenantCode.value = ''
    resetUrl.value = ''
  }

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

    submitting.value = true
    try {
      // 1. 生成一次性链接
      const url = await fetchCreateTenantAdminResetLink(tenantId.value)
      if (!url) {
        ElMessage.error(t('tenant.more.resetAdmin.failed'))
        return
      }

      resetUrl.value = url

      // 2. 提示
      ElMessage.success(t('tenant.more.resetAdmin.success'))
      emit('success')
    } catch (error) {
      console.error(error)
    } finally {
      submitting.value = false
    }
  }

  const handleCopy = async () => {
    if (!resetUrl.value) return

    // 1. 优先使用 Clipboard API
    try {
      await navigator.clipboard.writeText(resetUrl.value)
      ElMessage.success(t('tenant.more.resetAdmin.copied'))
      return
    } catch {
      // ignore
    }

    // 2. 兼容降级复制
    try {
      const textarea = document.createElement('textarea')
      textarea.value = resetUrl.value
      textarea.style.position = 'fixed'
      textarea.style.left = '-9999px'
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
      ElMessage.success(t('tenant.more.resetAdmin.copied'))
    } catch (error) {
      console.error(error)
    }
  }

  defineExpose({ open })
</script>
