<template>
  <ElDialog
    v-model="visible"
    :title="isEdit ? $t('quotaPackage.form.editTitle') : $t('quotaPackage.form.createTitle')"
    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('quotaPackage.form.name')" prop="name">
        <ElInput
          v-model="formModel.name"
          :placeholder="$t('quotaPackage.form.namePlaceholder')"
          maxlength="50"
          show-word-limit
        />
      </ElFormItem>

      <!-- 2. 配额类型 -->
      <ElFormItem :label="$t('quotaPackage.form.quotaType')" prop="quotaType">
        <ElSelect
          v-model="formModel.quotaType"
          :placeholder="$t('quotaPackage.form.quotaTypePlaceholder')"
          :disabled="isEdit"
          style="width: 100%"
        >
          <ElOption
            v-for="option in quotaTypeOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </ElSelect>
      </ElFormItem>

      <!-- 3. 配额值 -->
      <ElFormItem :label="$t('quotaPackage.form.quotaValue')" prop="quotaValue">
        <ElInputNumber
          v-model="formModel.quotaValue"
          :min="1"
          :max="999999"
          :placeholder="$t('quotaPackage.form.quotaValuePlaceholder')"
          style="width: 100%"
        />
      </ElFormItem>

      <!-- 4. 价格 -->
      <ElFormItem :label="$t('quotaPackage.form.price')" prop="price">
        <ElInputNumber
          v-model="formModel.price"
          :min="0"
          :max="999999"
          :precision="2"
          :placeholder="$t('quotaPackage.form.pricePlaceholder')"
          style="width: 100%"
        >
          <template #prefix>¥</template>
        </ElInputNumber>
      </ElFormItem>

      <!-- 5. 描述 -->
      <ElFormItem :label="$t('quotaPackage.form.description')" prop="description">
        <ElInput
          v-model="formModel.description"
          :placeholder="$t('quotaPackage.form.descriptionPlaceholder')"
          type="textarea"
          :rows="3"
          maxlength="256"
          show-word-limit
        />
      </ElFormItem>

      <!-- 6. 排序 -->
      <ElFormItem :label="$t('quotaPackage.form.sortOrder')" prop="sortOrder">
        <ElInputNumber v-model="formModel.sortOrder" :min="0" :max="9999" style="width: 100%" />
      </ElFormItem>

      <!-- 7. 是否上架 -->
      <ElFormItem :label="$t('quotaPackage.form.isActive')" prop="isActive">
        <ElSwitch v-model="formModel.isActive" />
      </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 { fetchCreateQuotaPackage, fetchUpdateQuotaPackage } from '@/api/quotaPackage'

  defineOptions({ name: 'QuotaPackageFormDialog' })

  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 isEdit = ref(false)
  const editId = ref<string>('')

  const formModel = reactive({
    name: '',
    quotaType: undefined as number | undefined,
    quotaValue: 1,
    price: 0,
    description: '',
    sortOrder: 0,
    isActive: true
  })

  // 2. 配额类型选项
  const quotaTypeOptions = [
    { value: 0, label: t('quotaPackage.quotaType.storeCount') },
    { value: 1, label: t('quotaPackage.quotaType.accountCount') },
    { value: 2, label: t('quotaPackage.quotaType.storage') },
    { value: 3, label: t('quotaPackage.quotaType.smsCredits') },
    { value: 4, label: t('quotaPackage.quotaType.deliveryOrders') },
    { value: 5, label: t('quotaPackage.quotaType.promotionSlots') }
  ]

  // 3. 表单校验规则
  const rules = computed<FormRules>(() => ({
    name: [
      { required: true, message: t('quotaPackage.validation.nameRequired'), trigger: 'blur' },
      { max: 50, message: t('quotaPackage.validation.nameMaxLength'), trigger: 'blur' }
    ],
    quotaType: [
      { required: true, message: t('quotaPackage.validation.quotaTypeRequired'), trigger: 'change' }
    ],
    quotaValue: [
      {
        required: true,
        message: t('quotaPackage.validation.quotaValueRequired'),
        trigger: 'change'
      }
    ],
    price: [
      { required: true, message: t('quotaPackage.validation.priceRequired'), trigger: 'change' }
    ]
  }))

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

    if (row) {
      // 编辑模式
      isEdit.value = true
      editId.value = row.id
      formModel.name = row.name
      formModel.quotaType = row.quotaType
      formModel.quotaValue = row.quotaValue
      formModel.price = row.price
      formModel.description = row.description || ''
      formModel.sortOrder = row.sortOrder
      formModel.isActive = row.isActive
    } else {
      // 新建模式
      isEdit.value = false
      editId.value = ''
      formModel.name = ''
      formModel.quotaType = undefined
      formModel.quotaValue = 1
      formModel.price = 0
      formModel.description = ''
      formModel.sortOrder = 0
      formModel.isActive = true
    }

    formRef.value?.clearValidate()
  }

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

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

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

      submitting.value = true
      try {
        if (isEdit.value) {
          await fetchUpdateQuotaPackage(editId.value, {
            name: formModel.name,
            quotaType: formModel.quotaType!,
            quotaValue: formModel.quotaValue,
            price: formModel.price,
            description: formModel.description || undefined,
            sortOrder: formModel.sortOrder,
            isActive: formModel.isActive
          })
          ElMessage.success(t('quotaPackage.message.updateSuccess'))
        } else {
          await fetchCreateQuotaPackage({
            name: formModel.name,
            quotaType: formModel.quotaType!,
            quotaValue: formModel.quotaValue,
            price: formModel.price,
            description: formModel.description || undefined,
            sortOrder: formModel.sortOrder,
            isActive: formModel.isActive
          })
          ElMessage.success(t('quotaPackage.message.createSuccess'))
        }

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

  defineExpose({ open })
</script>
