<template>
  <section class="space-y-6">
    <header>
      <h1 class="mos-title text-2xl font-semibold">申请奖励</h1>
      <p class="mos-muted mt-2 text-sm">提交奖励申请，进入审批流程。</p>
    </header>

    <div class="mos-card p-6 max-w-2xl">
      <form @submit.prevent="submitApplication" class="space-y-4">
        <div>
          <label class="block text-sm font-medium text-mosquito-ink mb-1">奖励类型</label>
          <select v-model="form.rewardType" class="mos-input w-full" required>
            <option value="">请选择奖励类型</option>
            <option value="coupon">优惠券</option>
            <option value="points">积分</option>
            <option value="cash">现金</option>
            <option value="gift">实物礼品</option>
          </select>
        </div>

        <div>
          <label class="block text-sm font-medium text-mosquito-ink mb-1">关联活动</label>
          <select v-model="form.activityId" class="mos-input w-full" required>
            <option value="">请选择活动</option>
            <option v-for="activity in activities" :key="activity.id" :value="activity.id">
              {{ activity.name }}
            </option>
          </select>
        </div>

        <div>
          <label class="block text-sm font-medium text-mosquito-ink mb-1">奖励数量/金额</label>
          <input v-model="form.amount" type="number" class="mos-input w-full" placeholder="请输入数量或金额" required />
        </div>

        <div>
          <label class="block text-sm font-medium text-mosquito-ink mb-1">目标用户</label>
          <input v-model="form.targetUser" type="text" class="mos-input w-full" placeholder="请输入用户ID或手机号" required />
        </div>

        <div>
          <label class="block text-sm font-medium text-mosquito-ink mb-1">申请原因</label>
          <textarea v-model="form.reason" class="mos-input w-full h-24" placeholder="请说明申请原因" required></textarea>
        </div>

        <div class="flex gap-3 pt-2">
          <button type="submit" class="mos-btn mos-btn-primary" :disabled="submitting">
            {{ submitting ? '提交中...' : '提交申请' }}
          </button>
          <RouterLink to="/rewards" class="mos-btn mos-btn-secondary">取消</RouterLink>
        </div>
      </form>
    </div>

    <div v-if="submitSuccess" class="mos-card border-green-200 bg-green-50 p-4">
      <div class="flex items-center gap-3">
        <span class="text-green-600">✓</span>
        <div>
          <div class="font-semibold text-green-700">申请提交成功</div>
          <div class="text-sm text-green-600">您的申请已提交，等待审批。</div>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { rewardService } from '../services/reward'

const router = useRouter()
const submitting = ref(false)
const submitSuccess = ref(false)

const form = ref({
  rewardType: '',
  activityId: '',
  amount: '',
  targetUser: '',
  reason: ''
})

const activities = ref<{ id: number; name: string }[]>([])

onMounted(async () => {
  try {
    // 加载活动列表
    const rewards = await rewardService.getRewards({ page: 1, size: 100 })
    // 由于getRewards返回的是奖励列表，我们用活动ID过滤
    // 实际应调用专门的活动列表接口，这里暂时用空
    activities.value = []
  } catch (error) {
    console.error('Failed to load activities:', error)
  }
})

const submitApplication = async () => {
  submitting.value = true
  try {
    // 调用后端API申请奖励
    // 解析targetUser为userId（这里假设targetUser格式为用户ID）
    const userId = Number(form.value.targetUser) || 0
    if (!userId) {
      throw new Error('请输入有效的用户ID')
    }
    await rewardService.applyReward({
      userId: userId,
      activityId: Number(form.value.activityId),
      rewardType: form.value.rewardType.toUpperCase() as any,
      rewardAmount: Number(form.value.amount),
      applyReason: form.value.reason
    })
    submitSuccess.value = true
    setTimeout(() => {
      router.push('/rewards')
    }, 2000)
  } catch (error) {
    alert('申请提交失败：' + (error instanceof Error ? error.message : '未知错误'))
  } finally {
    submitting.value = false
  }
}
</script>
