<template>
  <ElDialog
    v-model="visible"
    :title="dialogTitle"
    width="520px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <ElForm ref="formRef" :model="formModel" :rules="rules" label-width="90px" v-loading="loading">
      <ElAlert :title="alertTitle" type="warning" :closable="false" show-icon class="mb-4" />
      <ElFormItem :label="t('tenant.more.freeze.reason')" prop="reason">
        <ElInput
          v-model="formModel.reason"
          :placeholder="reasonPlaceholder"
          maxlength="256"
          show-word-limit
        />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="visible = false">{{ t('common.cancel') }}</ElButton>
        <ElButton type="primary" :loading="submitting" @click="handleSubmit">
          {{ t('common.confirm') }}
        </ElButton>
      </span>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ref, reactive, computed } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
  import { TenantStatus } from '@/enums/TenantStatus'
  import { fetchFreezeTenant, fetchUnfreezeTenant } from '@/api/tenant'

  defineOptions({ name: 'TenantFreezeDialog' })

  const { t } = useI18n()

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

  const visible = ref(false)
  const loading = ref(false)
  const submitting = ref(false)
  const formRef = ref<FormInstance>()

  const currentTenantId = ref<string>('')
  const isUnfreeze = ref(false)

  const formModel = reactive<{ reason: string }>({
    reason: ''
  })

  const dialogTitle = computed(() =>
    isUnfreeze.value ? t('tenant.more.freeze.unfreezeTitle') : t('tenant.more.freeze.freezeTitle')
  )

  const alertTitle = computed(() =>
    isUnfreeze.value ? t('tenant.more.freeze.unfreezeTip') : t('tenant.more.freeze.freezeTip')
  )

  const reasonPlaceholder = computed(() =>
    isUnfreeze.value
      ? t('tenant.more.freeze.unfreezePlaceholder')
      : t('tenant.more.freeze.freezePlaceholder')
  )

  const rules = computed<FormRules>(() => {
    if (isUnfreeze.value) {
      return {}
    }

    return {
      reason: [{ required: true, message: t('tenant.more.freeze.reasonRequired'), trigger: 'blur' }]
    }
  })

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

    // 1. 记录当前租户与动作
    currentTenantId.value = row.id
    isUnfreeze.value = row.status === TenantStatus.Suspended

    // 2. 重置表单
    formModel.reason = ''
    formRef.value?.clearValidate()
  }

  const handleClosed = () => {
    // 1. 关闭时清理状态
    currentTenantId.value = ''
    isUnfreeze.value = false
    formModel.reason = ''
    formRef.value?.resetFields()
  }

  const handleSubmit = async () => {
    if (!formRef.value || !currentTenantId.value) return

    // 1. 校验表单
    await formRef.value.validate(async (valid) => {
      if (!valid) return

      submitting.value = true
      try {
        // 2. 执行冻结/解冻
        if (isUnfreeze.value) {
          await fetchUnfreezeTenant(currentTenantId.value, {
            reason: formModel.reason || undefined
          })
        } else {
          await fetchFreezeTenant(currentTenantId.value, { reason: formModel.reason })
        }

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

  defineExpose({ open })
</script>
