<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑奖品' : '新增奖品'"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <!-- 优惠券类型字段 -->
      <el-form-item label="选择优惠券" prop="couponId">
        <el-select
          v-model="formData.couponId"
          placeholder="请选择优惠券"
          style="width: 100%"
          filterable
          :loading="couponLoading"
        >
          <el-option
            v-for="coupon in couponList"
            :key="coupon.id"
            :label="`${coupon.title} (满${coupon.minPrice}减${coupon.discountPrice})`"
            :value="coupon.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="数量" prop="quantity">
        <el-input-number
          v-model="formData.quantity"
          :min="1"
          :precision="0"
          placeholder="请输入优惠券数量"
          style="width: 100%"
        />
      </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 {
  createQyLevelPrize,
  updateQyLevelPrize,
  QyLevelPrizeType,
  type QyLevelPrizeResponse,
  type QyLevelPrizeCreateRequest,
  type QyLevelPrizeUpdateRequest
} from '@/api/business/qylevel'
import { getCoupons, type CouponResponse } from '@/api/business/coupon'

const props = defineProps<{
  modelValue: boolean
  levelId: number | undefined
  prize: QyLevelPrizeResponse | 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)

// 优惠券列表
const couponList = ref<CouponResponse[]>([])
const couponLoading = ref(false)

// 表单数据
interface FormDataType {
  couponId: number | undefined
  quantity: number
}

const formData = reactive<FormDataType>({
  couponId: undefined,
  quantity: 1
})

// 表单验证规则
const formRules = computed<FormRules>(() => ({
  couponId: [{ required: true, message: '请选择优惠券', trigger: 'change' }],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ]
}))

// 加载优惠券列表
const loadCoupons = async () => {
  couponLoading.value = true
  try {
    const res = await getCoupons({ page: 1, pageSize: 1000 })
    couponList.value = res.data.list
  } catch {
    couponList.value = []
  } finally {
    couponLoading.value = false
  }
}

// 监听弹窗打开，初始化数据
watch(() => props.modelValue, (visible) => {
  if (visible) {
    // 加载优惠券列表
    loadCoupons()
    
    if (props.isEdit && props.prize) {
      // 编辑模式：回显数据
      Object.assign(formData, {
        couponId: props.prize.couponId,
        quantity: props.prize.quantity || 1
      })
    } else {
      // 新增模式：重置数据
      resetForm()
    }
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    couponId: undefined,
    quantity: 1
  })
  formRef.value?.resetFields()
}

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

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

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

  // 优惠券验证
  if (!formData.couponId) {
    ElMessage.error('请选择优惠券')
    return
  }
  if (formData.quantity <= 0) {
    ElMessage.error('数量必须大于0')
    return
  }

  submitLoading.value = true
  try {
    const submitData: QyLevelPrizeCreateRequest | QyLevelPrizeUpdateRequest = {
      type: QyLevelPrizeType.Coupon,
      couponId: formData.couponId,
      quantity: formData.quantity
    }

    if (props.isEdit && props.prize) {
      await updateQyLevelPrize(props.prize.id, submitData as QyLevelPrizeUpdateRequest)
      ElMessage.success('更新成功')
    } else {
      if (!props.levelId) {
        ElMessage.error('未选择权益等级')
        return
      }
      await createQyLevelPrize(props.levelId, submitData as QyLevelPrizeCreateRequest)
      ElMessage.success('创建成功')
    }

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

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.image-preview {
  margin-top: 8px;
}
</style>
