<template>
  <section class="space-y-6">
    <header class="space-y-2">
      <h1 class="mos-title text-2xl font-semibold">风控与黑名单</h1>
      <p class="mos-muted text-sm">识别异常行为并管理黑名单。</p>
    </header>

    <ListSection>
      <template #title>风险告警处置</template>
      <template #subtitle>跟踪告警处理进度与闭环结果。</template>
      <template #default>
        <div v-if="alerts.length" class="space-y-3">
          <div v-for="alert in alerts" :key="alert.id" class="flex items-start justify-between rounded-xl border border-mosquito-line px-4 py-3">
            <div>
              <div class="text-sm font-semibold text-mosquito-ink">{{ alert.title }}</div>
              <div class="mos-muted text-xs">{{ alert.detail }}</div>
              <div class="mos-muted text-xs">更新时间：{{ formatDate(alert.updatedAt) }}</div>
            </div>
            <div class="flex flex-col items-end gap-2 text-xs text-mosquito-ink/70">
              <span class="rounded-full bg-mosquito-accent/10 px-2 py-1 text-[10px] font-semibold text-mosquito-brand">{{ alert.status }}</span>
              <div class="flex items-center gap-2">
                <button
                  class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs"
                  :disabled="alert.status !== '未处理'"
                  @click="updateAlert(alert, 'process')"
                >
                  处理
                </button>
                <button
                  class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs"
                  :disabled="alert.status === '已关闭'"
                  @click="updateAlert(alert, 'close')"
                >
                  关闭
                </button>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #empty>
        <div v-if="!alerts.length" class="mt-4 text-sm text-mosquito-ink/60">暂无告警</div>
      </template>
    </ListSection>

    <ListSection :page="page" :total-pages="totalPages" @prev="page--" @next="page++">
      <template #title>风控规则与黑名单</template>
      <template #filters>
        <input class="mos-input !py-1 !px-2 !text-xs w-48" v-model="query" placeholder="搜索类型/目标" />
        <input class="mos-input !py-1 !px-2 !text-xs" type="date" v-model="startDate" />
        <input class="mos-input !py-1 !px-2 !text-xs" type="date" v-model="endDate" />
      </template>
      <template #actions>
        <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="selectAll">
          {{ allSelected ? '取消全选' : '全选' }}
        </button>
        <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="batchEnable">批量启用</button>
        <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="batchPause">批量暂停</button>
        <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="addRule">新增规则</button>
      </template>
      <template #default>
        <div class="space-y-3">
          <div v-for="item in pagedRisks" :key="item.id" class="flex items-center justify-between rounded-xl border border-mosquito-line px-4 py-3">
            <div class="flex items-center gap-3">
              <input
                type="checkbox"
                class="h-4 w-4"
                :checked="selectedIds.includes(item.id)"
                @click.stop
                @change.stop="toggleSelect(item.id)"
              />
              <div>
                <div class="text-sm font-semibold text-mosquito-ink">{{ item.type }}</div>
                <div class="mos-muted text-xs">{{ item.target }}</div>
              </div>
            </div>
            <div class="flex items-center gap-3 text-xs text-mosquito-ink/70">
              <span>{{ item.status }}</span>
              <span class="mos-muted">{{ formatDate(item.updatedAt) }}</span>
              <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="toggleRisk(item)">
                {{ item.status === '生效' ? '暂停' : '启用' }}
              </button>
            </div>
          </div>
        </div>
      </template>
    </ListSection>
  </section>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useDataService } from '../services'
import { useAuditStore } from '../stores/audit'
import ListSection from '../components/ListSection.vue'
import { transitionAlertStatus, type AlertAction } from '../utils/risk'

type RiskItem = {
  id: string
  type: string
  target: string
  status: string
  updatedAt: string
}

type RiskAlert = {
  id: string
  title: string
  detail: string
  status: '未处理' | '处理中' | '已关闭'
  updatedAt: string
}

const risks = ref<RiskItem[]>([])
const alerts = ref<RiskAlert[]>([])
const service = useDataService()
const auditStore = useAuditStore()
const query = ref('')
const startDate = ref('')
const endDate = ref('')
const selectedIds = ref<string[]>([])
const page = ref(0)
const pageSize = 6

const formatDate = (value: string) => new Date(value).toLocaleDateString('zh-CN')

onMounted(async () => {
  risks.value = await service.getRiskItems()
  alerts.value = await service.getRiskAlerts()
})

const addRule = () => {
  risks.value.unshift({
    id: `risk-${Date.now()}`,
    type: '新增规则',
    target: '待配置',
    status: '待核查',
    updatedAt: new Date().toISOString()
  })
  auditStore.addLog('新增风控规则', '风控规则')
}

const toggleRisk = (item: RiskItem) => {
  item.status = item.status === '生效' ? '暂停' : '生效'
  item.updatedAt = new Date().toISOString()
  auditStore.addLog(item.status === '生效' ? '启用风控规则' : '暂停风控规则', item.type)
}

const updateAlert = (alert: RiskAlert, action: AlertAction) => {
  const nextStatus = transitionAlertStatus(alert.status, action)
  if (nextStatus === alert.status) return
  alert.status = nextStatus
  alert.updatedAt = new Date().toISOString()
  auditStore.addLog(nextStatus === '已关闭' ? '关闭风险告警' : '处理风险告警', alert.title)
}

const filteredRisks = computed(() => {
  return risks.value.filter((item) => {
    const keyword = query.value.trim()
    const matchesKeyword = keyword ? item.type.includes(keyword) || item.target.includes(keyword) : true
    const startOk = startDate.value ? new Date(item.updatedAt).getTime() >= new Date(startDate.value).getTime() : true
    const endOk = endDate.value ? new Date(item.updatedAt).getTime() <= new Date(endDate.value).getTime() : true
    return matchesKeyword && startOk && endOk
  })
})

const allSelected = computed(() => {
  return filteredRisks.value.length > 0 && filteredRisks.value.every((item) => selectedIds.value.includes(item.id))
})

const toggleSelect = (id: string) => {
  if (selectedIds.value.includes(id)) {
    selectedIds.value = selectedIds.value.filter((item) => item !== id)
  } else {
    selectedIds.value = [...selectedIds.value, id]
  }
}

const selectAll = () => {
  if (allSelected.value) {
    selectedIds.value = []
  } else {
    selectedIds.value = filteredRisks.value.map((item) => item.id)
  }
}

const batchEnable = () => {
  filteredRisks.value
    .filter((item) => selectedIds.value.includes(item.id))
    .forEach((item) => {
      if (item.status !== '生效') toggleRisk(item)
    })
}

const batchPause = () => {
  filteredRisks.value
    .filter((item) => selectedIds.value.includes(item.id))
    .forEach((item) => {
      if (item.status === '生效') toggleRisk(item)
    })
}

const totalPages = computed(() => Math.max(1, Math.ceil(filteredRisks.value.length / pageSize)))

const pagedRisks = computed(() => {
  const start = page.value * pageSize
  return filteredRisks.value.slice(start, start + pageSize)
})

watch([query, startDate, endDate], () => {
  page.value = 0
})
</script>
