<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="rewardType">
        <el-select
          v-model="formData.rewardType"
          placeholder="请选择奖励类型"
          style="width: 100%"
          :disabled="isEdit"
        >
          <el-option
            v-for="(label, value) in RewardTypeLabels"
            :key="value"
            :label="label"
            :value="Number(value)"
          />
        </el-select>
      </el-form-item>

      <!-- 优惠券类型：显示优惠券选择 -->
      <el-form-item
        v-if="formData.rewardType === RewardType.Coupon"
        label="选择优惠券"
        prop="rewardExtend"
      >
        <el-select
          v-model="formData.rewardExtend"
          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
        v-if="formData.rewardType && formData.rewardType !== RewardType.Coupon"
        label="奖励数值"
        prop="rewardValue"
      >
        <el-input-number
          v-model="formData.rewardValue"
          :min="1"
          :precision="0"
          placeholder="请输入奖励数值"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入描述（可选）"
          maxlength="200"
          show-word-limit
        />
      </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 {
  createReward,
  updateReward,
  RewardType,
  RewardTypeLabels,
  type RewardResponse,
  type RewardCreateRequest
} from '@/api/business/reward'
import { getCoupons, type CouponResponse } from '@/api/business/coupon'

const props = defineProps<{
  modelValue: boolean
  reward: RewardResponse | 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 {
  rewardType: number | undefined
  rewardExtend: number | undefined
  rewardValue: number
  description: string
}

const formData = reactive<FormDataType>({
  rewardType: undefined,
  rewardExtend: undefined,
  rewardValue: 1,
  description: ''
})

// 表单验证规则
const formRules = computed<FormRules>(() => ({
  rewardType: [
    { required: true, message: '请选择奖励类型', trigger: 'change' }
  ],
  rewardExtend: formData.rewardType === RewardType.Coupon
    ? [{ required: true, message: '请选择优惠券', trigger: 'change' }]
    : [],
  rewardValue: formData.rewardType && formData.rewardType !== RewardType.Coupon
    ? [
        { 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.reward) {
      // 编辑模式：回显数据
      Object.assign(formData, {
        rewardType: props.reward.rewardType,
        rewardExtend: props.reward.rewardExtend,
        rewardValue: props.reward.rewardValue || 1,
        description: props.reward.description || ''
      })
    } else {
      // 新增模式：重置数据
      resetForm()
    }
  }
})

// 监听奖励类型变化，清空相关字段
watch(() => formData.rewardType, (newType, oldType) => {
  if (oldType !== undefined && newType !== oldType) {
    if (newType === RewardType.Coupon) {
      formData.rewardValue = 1
    } else {
      formData.rewardExtend = undefined
    }
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    rewardType: undefined,
    rewardExtend: undefined,
    rewardValue: 1,
    description: ''
  })
  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.rewardType === RewardType.Coupon && !formData.rewardExtend) {
    ElMessage.error('请选择优惠券')
    return
  }

  // 额外验证：非优惠券类型必须输入正数值
  if (formData.rewardType !== RewardType.Coupon && formData.rewardValue <= 0) {
    ElMessage.error('奖励数值必须大于0')
    return
  }

  submitLoading.value = true
  try {
    const submitData: RewardCreateRequest = {
      rewardType: formData.rewardType!,
      rewardExtend: formData.rewardType === RewardType.Coupon ? formData.rewardExtend : undefined,
      rewardValue: formData.rewardType === RewardType.Coupon ? 1 : formData.rewardValue,
      description: formData.description || undefined
    }

    if (props.isEdit && props.reward) {
      await updateReward(props.reward.id, submitData)
      ElMessage.success('更新成功')
    } else {
      await createReward(submitData)
      ElMessage.success('创建成功')
    }

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

<style scoped>
</style>
