<script setup lang="ts">
import { Globe, Plus, ShieldCheck, ShieldOff, Smartphone } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

import type { RiskRule } from '@/pages/admin/risk-control/data/schema'

import ConfirmDialog from '@/components/confirm-dialog.vue'
import SingleFilter from '@/components/data-table/single-filter.vue'
import { BasicPage } from '@/components/global-layout'
import DataTable from '@/pages/admin/risk-control/components/data-table.vue'
import api from '@/services/api'

const router = useRouter()

const loading = ref(true)
const rules = ref<RiskRule[]>([])
const tableRef = ref()

const typeFilter = ref<string>('')
const statusFilter = ref<string>('')

const deleteDialogOpen = ref(false)
const deleteTarget = ref<RiskRule | null>(null)
const batchDeleteDialogOpen = ref(false)
const batchDeleteIds = ref<(string | number)[]>([])

const typeOptions = computed(() => [
  { label: 'IP封禁', value: 'ip' },
  { label: '设备封禁', value: 'device' },
  { label: '用户封禁', value: 'user' },
  { label: '地区封禁', value: 'region' },
])

const statusOptions = computed(() => [
  { label: '生效中', value: 'active' },
  { label: '已失效', value: 'inactive' },
])

const filteredRules = computed(() => {
  let result = rules.value

  if (typeFilter.value) {
    result = result.filter(rule => rule.type === typeFilter.value)
  }

  if (statusFilter.value) {
    result = result.filter(rule => rule.status === statusFilter.value)
  }

  return result
})

const activeCount = computed(() => filteredRules.value.filter(rule => rule.status === 'active').length)
const inactiveCount = computed(() => filteredRules.value.filter(rule => rule.status === 'inactive').length)
const ipCount = computed(() => filteredRules.value.filter(rule => rule.type === 'ip').length)
const deviceCount = computed(() => filteredRules.value.filter(rule => rule.type === 'device').length)

async function fetchRules() {
  loading.value = true
  try {
    const data = await api.get<RiskRule[]>('/dev/risk-control/rules')
    rules.value = Array.isArray(data) ? data : []
  }
  catch (error) {
    console.error('获取风控规则失败:', error)
    rules.value = []
  }
  finally {
    loading.value = false
  }
}

function goToCreate() {
  router.push('/admin/risk-control/create')
}

function openEditPage(rule: RiskRule) {
  router.push(`/admin/risk-control/${rule.id}`)
}

async function toggleStatus(rule: RiskRule) {
  try {
    const newStatus = rule.status === 'active' ? 'inactive' : 'active'
    await api.put(`/dev/risk-control/rules/${rule.id}/status`, { status: newStatus })
    toast.success('状态更新成功')
    fetchRules()
  }
  catch (error: any) {
    console.error('切换状态失败:', error)
    toast.error(error.message || '状态更新失败')
  }
}

function confirmDelete(rule: RiskRule) {
  deleteTarget.value = rule
  deleteDialogOpen.value = true
}

async function handleDelete() {
  if (!deleteTarget.value)
    return

  try {
    await api.delete(`/dev/risk-control/rules/${deleteTarget.value.id}`)
    toast.success('删除成功')
    fetchRules()
  }
  catch (error: any) {
    console.error('删除风控规则失败:', error)
    toast.error(error.message || '删除失败')
  }
  finally {
    deleteTarget.value = null
  }
}

function confirmBatchDelete(ids: (string | number)[]) {
  batchDeleteIds.value = ids
  batchDeleteDialogOpen.value = true
}

async function handleBatchDelete() {
  try {
    await api.delete('/dev/risk-control/rules/batch', { ids: batchDeleteIds.value } as any)
    toast.success('批量删除成功')
    fetchRules()
  }
  catch (error: any) {
    console.error('批量删除失败:', error)
    toast.error(error.message || '批量删除失败')
  }
  finally {
    batchDeleteIds.value = []
  }
}

async function batchToggleStatus(ids: (string | number)[], status: string) {
  try {
    await api.put('/dev/risk-control/rules/batch/status', { ids, status })
    toast.success('批量更新状态成功')
    fetchRules()
  }
  catch (error: any) {
    console.error('批量更新状态失败:', error)
    toast.error(error.message || '批量更新状态失败')
  }
}

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

<template>
  <BasicPage
    title="风控管理"
    description="管理封禁的IP、设备、用户等，保护应用安全"
    sticky
  >
    <template #actions>
      <UiButton @click="goToCreate">
        <Plus class="mr-2 h-4 w-4" />
        添加规则
      </UiButton>
    </template>

    <div class="space-y-6">
      <div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              生效中
            </UiCardTitle>
            <ShieldCheck class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ activeCount }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              已失效
            </UiCardTitle>
            <ShieldOff class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ inactiveCount }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              IP封禁
            </UiCardTitle>
            <Globe class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ ipCount }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              设备封禁
            </UiCardTitle>
            <Smartphone class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ deviceCount }}
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            ref="tableRef"
            :loading
            :data="filteredRules"
            :on-toggle-status="toggleStatus"
            :on-edit="openEditPage"
            :on-delete="confirmDelete"
            @refresh="fetchRules"
            @batch-disable="batchToggleStatus(tableRef?.table?.getSelectedRowModel().rows.filter((r: any) => r.original.status === 'active').map((r: any) => r.original.id) || [], 'inactive')"
            @batch-enable="batchToggleStatus(tableRef?.table?.getSelectedRowModel().rows.filter((r: any) => r.original.status === 'inactive').map((r: any) => r.original.id) || [], 'active')"
            @batch-delete="confirmBatchDelete(tableRef?.table?.getSelectedRowModel().rows.map((r: any) => r.original.id) || [])"
          >
            <template #filters>
              <SingleFilter
                v-model="typeFilter"
                title="规则类型"
                :options="typeOptions"
              />
              <SingleFilter
                v-model="statusFilter"
                title="状态"
                :options="statusOptions"
              />
            </template>
          </DataTable>
        </UiCardContent>
      </UiCard>
    </div>

    <ConfirmDialog
      v-model:open="deleteDialogOpen"
      destructive
      confirm-button-text="删除"
      cancel-button-text="取消"
      @confirm="handleDelete"
    >
      <template #title>
        删除风控规则
      </template>
      <template #description>
        确定要删除该风控规则吗？此操作不可撤销。
      </template>
    </ConfirmDialog>

    <ConfirmDialog
      v-model:open="batchDeleteDialogOpen"
      destructive
      confirm-button-text="删除"
      cancel-button-text="取消"
      @confirm="handleBatchDelete"
    >
      <template #title>
        批量删除风控规则
      </template>
      <template #description>
        确定要删除选中的 {{ batchDeleteIds.length }} 条规则吗？此操作不可撤销。
      </template>
    </ConfirmDialog>
  </BasicPage>
</template>
