<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="rank">
        <el-input-number
          v-model="formData.rank"
          :min="1"
          :max="999"
          placeholder="请输入排名"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="奖品名称" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入奖品名称"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="奖品类型" prop="prizeTypeId">
        <el-select
          v-model="formData.prizeTypeId"
          placeholder="请选择奖品类型"
          style="width: 100%"
        >
          <el-option
            v-for="item in prizeTypes"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="售价" prop="price">
        <el-input-number
          v-model="formData.price"
          :min="0"
          :max="999999"
          :precision="2"
          placeholder="请输入售价"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="采购价" prop="costPrice">
        <el-input-number
          v-model="formData.costPrice"
          :min="0"
          :max="999999"
          :precision="2"
          placeholder="请输入采购价"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="奖品图片" prop="imgUrl">
        <el-input
          v-model="formData.imgUrl"
          placeholder="请输入图片URL"
        />
        <div v-if="formData.imgUrl" class="image-preview">
          <el-image
            :src="formData.imgUrl"
            fit="cover"
            class="preview-img"
          />
        </div>
      </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, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  createWeekPrize,
  updateWeekPrize,
  createMonthPrize,
  updateMonthPrize,
  getPrizeTypes,
  type RankPrizeResponse,
  type RankPrizeCreateRequest,
  type PrizeTypeResponse
} from '@/api/business/rank'

const props = defineProps<{
  modelValue: boolean
  prize: RankPrizeResponse | null
  isEdit: boolean
  type: 'week' | 'month'
}>()

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 prizeTypes = ref<PrizeTypeResponse[]>([])

// 表单数据
interface FormDataType {
  rank: number
  title: string
  imgUrl: string
  price: number
  costPrice: number
  prizeTypeId: number | undefined
}

const formData = reactive<FormDataType>({
  rank: 1,
  title: '',
  imgUrl: '',
  price: 0,
  costPrice: 0,
  prizeTypeId: undefined
})

// 表单验证规则
const formRules: FormRules = {
  rank: [
    { required: true, message: '请输入排名', trigger: 'blur' },
    { type: 'number', min: 1, message: '排名必须大于0', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入奖品名称', trigger: 'blur' },
    { min: 1, max: 100, message: '名称长度在1-100个字符', trigger: 'blur' }
  ],
  prizeTypeId: [
    { required: true, message: '请选择奖品类型', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入售价', trigger: 'blur' },
    { type: 'number', min: 0, message: '售价不能为负数', trigger: 'blur' }
  ],
  costPrice: [
    { required: true, message: '请输入采购价', trigger: 'blur' },
    { type: 'number', min: 0, message: '采购价不能为负数', trigger: 'blur' }
  ],
  imgUrl: [
    { required: true, message: '请输入图片URL', trigger: 'blur' }
  ]
}

// 获取奖品类型列表
const fetchPrizeTypes = async () => {
  try {
    const res = await getPrizeTypes()
    prizeTypes.value = res.data
  } catch {
    // 忽略错误
  }
}

// 监听弹窗打开，初始化数据
watch(() => props.modelValue, (visible) => {
  if (visible) {
    if (props.isEdit && props.prize) {
      // 编辑模式：回显数据
      Object.assign(formData, {
        rank: props.prize.rank,
        title: props.prize.title,
        imgUrl: props.prize.imgUrl,
        price: props.prize.price,
        costPrice: props.prize.costPrice,
        prizeTypeId: props.prize.prizeTypeId || undefined
      })
    } else {
      // 新增模式：重置数据
      resetForm()
    }
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    rank: 1,
    title: '',
    imgUrl: '',
    price: 0,
    costPrice: 0,
    prizeTypeId: undefined
  })
  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: RankPrizeCreateRequest = {
      rank: formData.rank,
      title: formData.title,
      imgUrl: formData.imgUrl,
      price: formData.price,
      costPrice: formData.costPrice,
      prizeTypeId: formData.prizeTypeId || 0
    }

    if (props.isEdit && props.prize) {
      if (props.type === 'week') {
        await updateWeekPrize(props.prize.id, submitData)
      } else {
        await updateMonthPrize(props.prize.id, submitData)
      }
      ElMessage.success('更新成功')
    } else {
      if (props.type === 'week') {
        await createWeekPrize(submitData)
      } else {
        await createMonthPrize(submitData)
      }
      ElMessage.success('创建成功')
    }

    emit('success')
    handleClose()
  } finally {
    submitLoading.value = false
  }
}

onMounted(() => {
  fetchPrizeTypes()
})
</script>

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

.preview-img {
  width: 100px;
  height: 100px;
  border-radius: 4px;
}
</style>
