<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑优惠券' : '新增优惠券'"
    width="550px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="优惠券类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择类型" style="width: 100%">
          <el-option
            v-for="(label, value) in CouponTypeLabels"
            :key="value"
            :label="label"
            :value="Number(value)"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="使用限制" prop="useLimit">
        <el-select v-model="formData.useLimit" placeholder="请选择使用限制" style="width: 100%">
          <el-option
            v-for="(label, value) in CouponUseLimitLabels"
            :key="value"
            :label="label"
            :value="Number(value)"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="优惠券名称" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入优惠券名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="满减门槛" prop="minPrice">
        <el-input-number
          v-model="formData.minPrice"
          :min="0"
          :max="999999"
          :precision="2"
          placeholder="请输入满减门槛"
          style="width: 100%"
        >
          <template #suffix>元</template>
        </el-input-number>
      </el-form-item>

      <el-form-item label="优惠金额" prop="discountPrice">
        <el-input-number
          v-model="formData.discountPrice"
          :min="0.01"
          :max="999999"
          :precision="2"
          placeholder="请输入优惠金额"
          style="width: 100%"
        >
          <template #suffix>元</template>
        </el-input-number>
      </el-form-item>

      <el-form-item label="有效期" prop="validDays">
        <el-input-number
          v-model="formData.validDays"
          :min="1"
          :max="365"
          placeholder="请输入有效期天数"
          style="width: 100%"
        >
          <template #suffix>天</template>
        </el-input-number>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  createCoupon,
  updateCoupon,
  CouponType,
  CouponUseLimit,
  CouponTypeLabels,
  CouponUseLimitLabels,
  type CouponResponse,
  type CouponCreateRequest
} from '@/api/business/coupon'

const props = defineProps<{
  modelValue: boolean
  coupon: CouponResponse | null
  isEdit: boolean
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 表单引用
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 表单数据
interface FormDataType {
  title: string
  minPrice: number
  discountPrice: number
  validDays: number
  type: number
  useLimit: number
}

const formData = reactive<FormDataType>({
  title: '',
  minPrice: 0,
  discountPrice: 0,
  validDays: 7,
  type: CouponType.FullReduction,
  useLimit: CouponUseLimit.NoLimit
})

// 表单验证规则
const formRules: FormRules = {
  title: [
    { required: true, message: '请输入优惠券名称', trigger: 'blur' },
    { min: 1, max: 50, message: '名称长度在1-50个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择优惠券类型', trigger: 'change' }
  ],
  useLimit: [
    { required: true, message: '请选择使用限制', trigger: 'change' }
  ],
  minPrice: [
    { required: true, message: '请输入满减门槛', trigger: 'blur' },
    { type: 'number', min: 0, message: '满减门槛不能为负数', trigger: 'blur' }
  ],
  discountPrice: [
    { required: true, message: '请输入优惠金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '优惠金额必须大于0', trigger: 'blur' }
  ],
  validDays: [
    { required: true, message: '请输入有效期', trigger: 'blur' },
    { type: 'number', min: 1, max: 365, message: '有效期在1-365天之间', trigger: 'blur' }
  ]
}

// 监听弹窗打开，初始化数据
watch(() => props.modelValue, (visible) => {
  if (visible) {
    if (props.isEdit && props.coupon) {
      // 编辑模式：回显数据
      Object.assign(formData, {
        title: props.coupon.title,
        minPrice: props.coupon.minPrice,
        discountPrice: props.coupon.discountPrice,
        validDays: props.coupon.validDays,
        type: props.coupon.type,
        useLimit: props.coupon.useLimit
      })
    } else {
      // 新增模式：重置数据
      resetForm()
    }
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    title: '',
    minPrice: 0,
    discountPrice: 0,
    validDays: 7,
    type: CouponType.FullReduction,
    useLimit: CouponUseLimit.NoLimit
  })
  formRef.value?.resetFields()
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
  } catch {
    return
  }

  submitLoading.value = true
  try {
    const submitData: CouponCreateRequest = {
      title: formData.title,
      minPrice: formData.minPrice,
      discountPrice: formData.discountPrice,
      validDays: formData.validDays,
      type: formData.type,
      useLimit: formData.useLimit
    }

    if (props.isEdit && props.coupon) {
      await updateCoupon(props.coupon.id, submitData)
      ElMessage.success('更新成功')
    } else {
      await createCoupon(submitData)
      ElMessage.success('创建成功')
    }

    emit('success')
    handleClose()
  } finally {
    submitLoading.value = false
  }
}
</script>

<style scoped>
</style>
