<template>
  <div class="prize-reward-config">
    <div v-for="(item, index) in rewardList" :key="index" class="reward-item">
      <el-select
        v-model="item.type"
        placeholder="奖励类型"
        style="width: 120px"
        @change="handleChange"
      >
        <el-option
          v-for="opt in rewardTypeOptions"
          :key="opt.value"
          :label="opt.label"
          :value="opt.value"
        />
      </el-select>
      <el-input-number
        v-model="item.amount"
        :min="0"
        :max="999999999"
        placeholder="数量"
        style="width: 150px; margin-left: 8px"
        @change="handleChange"
      />
      <el-button
        type="danger"
        :icon="Delete"
        circle
        size="small"
        style="margin-left: 8px"
        @click="removeItem(index)"
      />
    </div>
    <el-button type="primary" link @click="addItem" style="margin-top: 8px">
      <el-icon><Plus /></el-icon>添加奖励
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'

interface RewardItem {
  type: number
  amount: number
}

interface Props {
  modelValue: RewardItem[]
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => []
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: RewardItem[]): void
}>()

// 奖励类型选项
const rewardTypeOptions = [
  { label: '钻石', value: 1 },
  { label: 'HH币', value: 2 },
  { label: '哈尼券', value: 3 }
]

// 内部数据
const rewardList = ref<RewardItem[]>([])

// 监听外部值变化
watch(() => props.modelValue, (newVal) => {
  if (Array.isArray(newVal) && newVal.length > 0) {
    rewardList.value = newVal.map(item => ({ ...item }))
  } else {
    rewardList.value = []
  }
}, { immediate: true, deep: true })

// 处理变化 - 同步到父组件，不过滤 amount=0 的项（保留编辑中的项）
const handleChange = () => {
  // 直接同步所有项，不过滤（过滤逻辑在提交时由后端处理）
  emit('update:modelValue', rewardList.value.map(item => ({ ...item })))
}

// 添加奖励配置
const addItem = () => {
  rewardList.value.push({ type: 1, amount: 0 })
}

// 移除奖励配置
const removeItem = (index: number) => {
  rewardList.value.splice(index, 1)
  emit('update:modelValue', rewardList.value.map(item => ({ ...item })))
}

onMounted(() => {
  if (Array.isArray(props.modelValue) && props.modelValue.length > 0) {
    rewardList.value = props.modelValue.map(item => ({ ...item }))
  }
})
</script>

<style scoped>
.prize-reward-config {
  width: 100%;
}

.reward-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.reward-item:last-child {
  margin-bottom: 0;
}
</style>
