<template>
  <ElDialog
    v-model="visible"
    :title="t('tenant.more.extend.title')"
    width="560px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <ElForm ref="formRef" :model="formModel" :rules="rules" label-width="110px" v-loading="loading">
      <ElAlert :title="expireTip" type="info" :closable="false" show-icon class="mb-4" />
      <ElFormItem :label="t('tenant.more.extend.months')" prop="durationMonths">
        <ElInputNumber v-model="formModel.durationMonths" :min="1" :max="120" />
        <span class="ml-2">{{ t('tenant.more.extend.monthUnit') }}</span>
      </ElFormItem>
      <ElFormItem :label="t('tenant.more.extend.notes')" prop="notes">
        <ElInput
          v-model="formModel.notes"
          :placeholder="t('tenant.more.extend.notesPlaceholder')"
          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 { fetchExtendTenantSubscription } from '@/api/tenant'

  defineOptions({ name: 'TenantExtendSubscriptionDialog' })

  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 currentExpireAt = ref<string | undefined>(undefined)

  const formModel = reactive<Api.Tenant.ExtendTenantSubscriptionCommand>({
    tenantId: '',
    durationMonths: 1,
    notes: ''
  })

  const rules = computed<FormRules>(() => ({
    durationMonths: [
      { required: true, message: t('tenant.more.extend.monthsRequired'), trigger: 'change' }
    ]
  }))

  const expireTip = computed(() => {
    if (!currentExpireAt.value) {
      return t('tenant.more.extend.expireUnknown')
    }

    return t('tenant.more.extend.currentExpireAt', {
      date: new Date(currentExpireAt.value).toLocaleString()
    })
  })

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

    // 1. 记录当前租户与到期时间
    currentTenantId.value = row.id
    currentExpireAt.value = row.effectiveTo

    // 2. 初始化表单
    formModel.tenantId = row.id
    formModel.durationMonths = 1
    formModel.notes = ''
    formRef.value?.clearValidate()
  }

  const handleClosed = () => {
    // 1. 关闭时清理状态
    currentTenantId.value = ''
    currentExpireAt.value = undefined
    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. 执行延期/赠送
        await fetchExtendTenantSubscription(currentTenantId.value, {
          durationMonths: formModel.durationMonths,
          notes: formModel.notes || undefined
        })

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

  defineExpose({ open })
</script>
