<template>
  <section class="space-y-6">
    <header class="flex flex-wrap items-center justify-between gap-4">
      <div>
        <h1 class="mos-title text-2xl font-semibold">{{ isEdit ? '编辑规则' : '新建规则' }}</h1>
        <p class="mos-muted mt-2 text-sm">配置风控规则，包括规则类型、触发条件、处理动作等。</p>
      </div>
    </header>

    <div class="mos-card p-6">
      <form @submit.prevent="handleSubmit" class="space-y-4">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label class="block text-sm font-medium text-mosquito-ink mb-1">规则名称 *</label>
            <input
              v-model="formData.name"
              type="text"
              class="mos-input w-full"
              placeholder="请输入规则名称"
              required
            />
          </div>

          <div>
            <label class="block text-sm font-medium text-mosquito-ink mb-1">规则类型 *</label>
            <select v-model="formData.riskType" class="mos-input w-full" required>
              <option value="">请选择规则类型</option>
              <option value="CHEAT">欺诈</option>
              <option value="ABNORMAL">异常</option>
              <option value="VIOLATION">违规</option>
              <option value="SYSTEM">系统</option>
            </select>
          </div>

          <div>
            <label class="block text-sm font-medium text-mosquito-ink mb-1">处理动作 *</label>
            <select v-model="formData.action" class="mos-input w-full" required>
              <option value="">请选择处理动作</option>
              <option value="BLOCK">拦截</option>
              <option value="WARN">警告</option>
              <option value="LOG">记录</option>
              <option value="CAPTCHA">验证码</option>
            </select>
          </div>

          <div>
            <label class="block text-sm font-medium text-mosquito-ink mb-1">优先级</label>
            <input
              v-model.number="formData.priority"
              type="number"
              class="mos-input w-full"
              placeholder="数值越大优先级越高"
              min="0"
            />
          </div>
        </div>

        <div>
          <label class="block text-sm font-medium text-mosquito-ink mb-1">触发条件 *</label>
          <textarea
            v-model="formData.condition"
            class="mos-input w-full"
            rows="3"
            placeholder="请输入触发条件表达式，如: user.invite_count > 10"
            required
          ></textarea>
          <p class="text-xs text-mosquito-ink/60 mt-1">支持条件表达式，用于判断是否触发此规则</p>
        </div>

        <div>
          <label class="block text-sm font-medium text-mosquito-ink mb-1">描述</label>
          <textarea
            v-model="formData.description"
            class="mos-input w-full"
            rows="2"
            placeholder="请输入规则描述"
          ></textarea>
        </div>

        <div class="flex gap-2 pt-4">
          <button type="submit" class="mos-btn mos-btn-primary" :disabled="submitting">
            {{ submitting ? '提交中...' : '提交审批' }}
          </button>
          <button type="button" class="mos-btn mos-btn-secondary" @click="handleCancel">
            取消
          </button>
        </div>
      </form>
    </div>
  </section>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import riskService, { type RiskRule, type RiskType, type RiskAction } from '@/services/risk'

const router = useRouter()
const route = useRoute()

const isEdit = computed(() => !!route.params.id)
const ruleId = computed(() => route.params.id as string | undefined)
const submitting = ref(false)

const formData = ref({
  name: '',
  riskType: '',
  condition: '',
  action: '',
  priority: 0,
  description: ''
})

const loadRule = async () => {
  if (!ruleId.value) return
  try {
    const rules = await riskService.getRules()
    const rule = rules.data.find(r => r.id === Number(ruleId.value))
    if (rule) {
      formData.value = {
        name: rule.name,
        riskType: rule.riskType || '',
        condition: rule.condition || '',
        action: rule.action || '',
        priority: rule.priority || 0,
        description: rule.description || ''
      }
    }
  } catch (error: any) {
    alert('加载规则失败: ' + (error.message || '未知错误'))
  }
}

const handleSubmit = async () => {
  if (submitting.value) return
  submitting.value = true

  try {
    const ruleData: Partial<RiskRule> = {
      name: formData.value.name,
      riskType: formData.value.riskType as RiskType,
      condition: formData.value.condition,
      action: formData.value.action as RiskAction,
      priority: formData.value.priority,
      description: formData.value.description
    }
    if (isEdit.value && ruleId.value) {
      await riskService.updateRule(Number(ruleId.value), ruleData)
    } else {
      await riskService.createRule(ruleData)
    }
    router.push('/risks/rules')
  } catch (error: any) {
    alert('提交失败: ' + (error.message || '未知错误'))
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  router.push('/risks/rules')
}

onMounted(() => {
  if (isEdit.value) {
    loadRule()
  }
})
</script>
