<template>
  <ElDialog
    v-model="visible"
    :title="$t('subscription.extend.title')"
    width="560px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <ElForm ref="formRef" :model="formModel" :rules="rules" label-width="110px" v-loading="loading">
      <!-- 1. 延期时长 -->
      <ElFormItem :label="$t('subscription.extend.duration')" prop="duration">
        <div class="duration-input">
          <ElInputNumber v-model="formModel.duration" :min="1" :max="999" />
          <ElRadioGroup v-model="formModel.unit" class="ml-2">
            <ElRadio value="day">{{ $t('subscription.extend.unitDay') }}</ElRadio>
            <ElRadio value="month">{{ $t('subscription.extend.unitMonth') }}</ElRadio>
          </ElRadioGroup>
        </div>
      </ElFormItem>

      <!-- 2. 备注 -->
      <ElFormItem :label="$t('subscription.extend.notes')" prop="notes">
        <ElInput
          v-model="formModel.notes"
          :placeholder="$t('subscription.extend.notesPlaceholder')"
          type="textarea"
          :rows="3"
          maxlength="256"
          show-word-limit
        />
      </ElFormItem>

      <!-- 3. 预览延期后的时间 -->
      <ElFormItem :label="$t('subscription.extend.preview')">
        <div class="preview-date">{{ previewExpireDate }}</div>
      </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 { extendSubscription } from '@/api/subscription'

  defineOptions({ name: 'ExtendSubscriptionDialog' })

  const { t } = useI18n()

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

  // 1. 响应式变量
  const visible = ref(false)
  const loading = ref(false)
  const submitting = ref(false)
  const formRef = ref<FormInstance>()

  const currentSubscriptionId = ref<string>('')
  const currentExpireDate = ref<string | undefined>(undefined)

  const formModel = reactive({
    duration: 1,
    unit: 'month' as 'day' | 'month',
    notes: ''
  })

  // 2. 表单校验规则
  const rules = computed<FormRules>(() => ({
    duration: [
      {
        required: true,
        message: t('subscription.extend.validation.durationRequired'),
        trigger: 'change'
      },
      {
        type: 'number',
        min: 1,
        message: t('subscription.extend.validation.durationMin'),
        trigger: 'change'
      }
    ]
  }))

  // 3. 预览延期后的时间
  const previewExpireDate = computed(() => {
    if (!currentExpireDate.value || !formModel.duration) {
      return '-'
    }

    const expireDate = new Date(currentExpireDate.value)
    if (formModel.unit === 'day') {
      expireDate.setDate(expireDate.getDate() + formModel.duration)
    } else {
      expireDate.setMonth(expireDate.getMonth() + formModel.duration)
    }

    return expireDate.toLocaleString()
  })

  // 4. 打开弹窗
  const open = (row: Api.Subscription.SubscriptionDto) => {
    visible.value = true

    // 记录当前订阅信息
    currentSubscriptionId.value = row.id
    currentExpireDate.value = row.effectiveTo

    // 初始化表单
    formModel.duration = 1
    formModel.unit = 'month'
    formModel.notes = ''
    formRef.value?.clearValidate()
  }

  // 5. 关闭处理
  const handleClosed = () => {
    currentSubscriptionId.value = ''
    currentExpireDate.value = undefined
    formRef.value?.resetFields()
  }

  // 6. 提交处理
  const handleSubmit = async () => {
    if (!formRef.value || !currentSubscriptionId.value) return

    await formRef.value.validate(async (valid) => {
      if (!valid) return

      submitting.value = true
      try {
        // 计算延期月数
        let extendMonths = formModel.duration
        if (formModel.unit === 'day') {
          // 将天数转换为月数（向上取整，至少1个月）
          extendMonths = Math.max(1, Math.ceil(formModel.duration / 30))
        }

        await extendSubscription(currentSubscriptionId.value, {
          durationMonths: extendMonths,
          notes: formModel.notes || undefined
        })

        ElMessage.success(t('subscription.extend.success'))
        emit('success')
        visible.value = false
      } catch (error) {
        console.error(error)
      } finally {
        submitting.value = false
      }
    })
  }

  defineExpose({ open })
</script>

<style scoped>
  .duration-input {
    display: flex;
    align-items: center;
    width: 100%;
  }

  .preview-date {
    font-weight: 600;
    color: var(--el-color-primary);
  }
</style>
