<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">风控规则</h1>
        <p class="mos-muted mt-2 text-sm">配置和管理风控规则，包括导入导出、拦截与解除拦截。</p>
      </div>
      <div class="flex gap-2">
        <PermissionButton permission="risk.rule.create.ALL" variant="secondary" @click="handleImport">
          导入
        </PermissionButton>
        <PermissionButton permission="risk.rule.manage.ALL" variant="secondary" @click="handleExport">
          导出
        </PermissionButton>
        <PermissionButton permission="risk.rule.create.ALL" variant="primary" @click="router.push('/risks/new')">
          新建规则
        </PermissionButton>
      </div>
    </header>

    <div class="mos-card p-4">
      <div class="flex flex-wrap gap-4 mb-4">
        <input v-model="searchQuery" class="mos-input w-64" placeholder="搜索规则名称..." />
        <select v-model="filterStatus" class="mos-input w-40">
          <option value="">全部状态</option>
          <option value="enabled">已启用</option>
          <option value="disabled">已禁用</option>
        </select>
      </div>

      <div class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="border-b border-mosquito-line text-left text-sm text-mosquito-ink/70">
              <th class="pb-3 font-medium">规则名称</th>
              <th class="pb-3 font-medium">规则类型</th>
              <th class="pb-3 font-medium">阈值</th>
              <th class="pb-3 font-medium">状态</th>
              <th class="pb-3 font-medium">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="rule in filteredRules" :key="rule.id" class="border-b border-mosquito-line/50">
              <td class="py-3 text-sm text-mosquito-ink">{{ rule.name }}</td>
              <td class="py-3 text-sm text-mosquito-ink">{{ rule.type }}</td>
              <td class="py-3 text-sm text-mosquito-ink">{{ rule.threshold }}</td>
              <td class="py-3">
                <span
                  :class="rule.enabled ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'"
                  class="rounded-full px-2 py-1 text-xs font-semibold"
                >
                  {{ rule.enabled ? '已启用' : '已禁用' }}
                </span>
              </td>
              <td class="py-3">
                <div class="flex gap-2">
                  <PermissionButton permission="risk.rule.edit.ALL" variant="secondary" @click="editRule(rule)">
                    <span class="text-sm text-mosquito-accent hover:underline">编辑</span>
                  </PermissionButton>
                  <PermissionButton
                    permission="risk.rule.enable.ALL"
                    variant="secondary"
                    @click="toggleRule(rule)"
                  >
                    <span :class="rule.enabled ? 'text-amber-600 hover:underline' : 'text-green-600 hover:underline'">
                      {{ rule.enabled ? '禁用' : '启用' }}
                    </span>
                  </PermissionButton>
                  <PermissionButton permission="risk.rule.delete.ALL" variant="danger" @click="deleteRule(rule)">
                    <span class="text-sm text-rose-600 hover:underline">删除</span>
                  </PermissionButton>
                  <PermissionButton
                    v-if="rule.blocked"
                    permission="risk.block.execute.ALL"
                    variant="secondary"
                    @click="unblockRule(rule)"
                  >
                    <span class="text-sm text-blue-600 hover:underline">解除拦截</span>
                  </PermissionButton>
                  <PermissionButton
                    v-else
                    permission="risk.block.execute.ALL"
                    variant="secondary"
                    @click="blockRule(rule)"
                  >
                    <span class="text-sm text-orange-600 hover:underline">拦截</span>
                  </PermissionButton>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div v-if="!filteredRules.length" class="py-8 text-center text-mosquito-ink/60">
        暂无风控规则
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import riskService from '@/services/risk'
import PermissionButton from '../components/PermissionButton.vue'

const router = useRouter()

const showMessage = (msg: string, type: 'success' | 'error' = 'success') => {
  if (type === 'error') {
    alert(msg)
  } else {
    console.log(msg)
  }
}

interface RiskRule {
  id: number
  name: string
  type: string
  code: string
  condition: string
  action: string
  threshold: string
  enabled: boolean
  blocked: boolean
}

const searchQuery = ref('')
const filterStatus = ref('')
const loading = ref(false)

const rules = ref<RiskRule[]>([])

// 加载规则列表
const loadRules = async () => {
  try {
    loading.value = true
    const result = await riskService.getRules({
      status: filterStatus.value || undefined
    })
    rules.value = result.data.map((r: any) => ({
      id: r.id,
      name: r.name,
      type: r.type || r.riskType || '',
      code: r.code || '',
      condition: r.condition || '',
      action: r.action || '',
      threshold: r.condition || '',
      enabled: r.status === 'ENABLED',
      blocked: false
    }))
  } catch (error: any) {
    console.error('加载规则列表失败:', error)
    showMessage(error.message || '加载规则列表失败', 'error')
  } finally {
    loading.value = false
  }
}

const filteredRules = computed(() => {
  return rules.value.filter((rule) => {
    const matchesSearch = !searchQuery.value || rule.name.includes(searchQuery.value)
    const matchesStatus = !filterStatus.value ||
      (filterStatus.value === 'enabled' && rule.enabled) ||
      (filterStatus.value === 'disabled' && !rule.enabled)
    return matchesSearch && matchesStatus
  })
})

const handleImport = () => {
  // 创建文件输入元素
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.json,.csv'
  input.onchange = async (e: Event) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (!file) return

    try {
      const text = await file.text()
      // 尝试解析JSON格式
      const imported = JSON.parse(text)
      if (Array.isArray(imported)) {
        // 批量导入规则
        for (const rule of imported) {
          if (rule.name && rule.code && rule.riskType) {
            await riskService.createRule(rule)
          }
        }
        showMessage(`成功导入 ${imported.length} 条规则`)
        loadRules()
      } else {
        showMessage('导入格式不正确，应为规则数组', 'error')
      }
    } catch (error: any) {
      showMessage('导入失败: ' + (error.message || '文件格式错误'), 'error')
    }
  }
  input.click()
}

const handleExport = async () => {
  // 调用后端CSV导出接口
  try {
    loading.value = true
    const blob = await riskService.exportRules()
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `risk-rules-${new Date().toISOString().split('T')[0]}.csv`
    link.click()
    URL.revokeObjectURL(url)
    showMessage('规则导出成功')
  } catch (error: any) {
    showMessage('导出失败: ' + (error.message || '未知错误'), 'error')
  } finally {
    loading.value = false
  }
}

const editRule = (rule: RiskRule) => {
  router.push(`/risks/edit/${rule.id}`)
}

const toggleRule = async (rule: RiskRule) => {
  try {
    loading.value = true
    await riskService.toggleRule(rule.id, !rule.enabled)
    rule.enabled = !rule.enabled
    showMessage(rule.enabled ? '规则已启用' : '规则已禁用')
  } catch (error: any) {
    showMessage(error.message || '操作失败', 'error')
  } finally {
    loading.value = false
  }
}

const deleteRule = async (rule: RiskRule) => {
  if (confirm(`确定删除规则"${rule.name}"吗？`)) {
    try {
      loading.value = true
      await riskService.deleteRule(rule.id)
      rules.value = rules.value.filter((r) => r.id !== rule.id)
      showMessage('规则删除成功')
    } catch (error: any) {
      showMessage(error.message || '删除规则失败', 'error')
    } finally {
      loading.value = false
    }
  }
}

const blockRule = async (rule: RiskRule) => {
  // 拦截操作应前往风险告警页面进行
  // 这里提示用户去告警页面执行拦截操作
  if (confirm(`规则"${rule.name}"的拦截操作需要在风险告警页面执行。\n\n是否前往风险监控页面？`)) {
    router.push('/risks')
  }
}

const unblockRule = async (rule: RiskRule) => {
  // 解除拦截操作应前往风险告警页面进行
  if (confirm(`规则"${rule.name}"的解除拦截操作需要在风险告警页面执行。\n\n是否前往风险监控页面？`)) {
    router.push('/risks')
  }
}

// 监听筛选状态变化
const handleFilterChange = () => {
  loadRules()
}

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