<script setup lang="ts">
import { Search, Trash2 } from 'lucide-vue-next'
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

import { BasicPage } from '@/components/global-layout'
import api from '@/services/api'

interface Variable {
  id: number
  key: string
  var_type: string
  scope: string
  max_records: number
}

interface VariableRecord {
  id: number
  data: Record<string, any>
  user_id?: number
  user?: {
    id: number
    username: string
  }
  created_at: string
}

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

const loading = ref(true)
const variable = ref<Variable | null>(null)
const records = ref<VariableRecord[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)
const startDate = ref('')
const endDate = ref('')
const selectedIds = ref<number[]>([])

async function fetchVariable() {
  try {
    const data = await api.get<{ variables: Variable[] }>(`/dev/cloud-variables?app_id=${route.query.app_id}`)
    const vars = data?.variables || []
    variable.value = vars.find((v: Variable) => String(v.id) === route.params.id) || null
    if (variable.value && variable.value.var_type !== 'stream') {
      toast.error('该变量不是记录类型')
      router.back()
    }
  }
  catch (error) {
    console.error('获取变量信息失败:', error)
  }
}

async function fetchRecords() {
  if (!variable.value)
    return

  loading.value = true
  try {
    const params = new URLSearchParams()
    params.append('page', String(page.value))
    params.append('page_size', String(pageSize.value))
    if (startDate.value)
      params.append('start_date', startDate.value)
    if (endDate.value)
      params.append('end_date', endDate.value)

    const data = await api.get<{ records: VariableRecord[], total: number }>(`/dev/cloud-variables/${variable.value.id}/records?${params}`)
    records.value = data?.records || []
    total.value = data?.total || 0
  }
  catch (error) {
    console.error('获取记录失败:', error)
  }
  finally {
    loading.value = false
  }
}

async function handleDeleteSelected() {
  if (selectedIds.value.length === 0) {
    toast.error('请选择要删除的记录')
    return
  }

  try {
    await api.delete(`/dev/cloud-variables/${variable.value?.id}/records`, {
      ids: selectedIds.value,
    })
    toast.success('删除成功')
    selectedIds.value = []
    fetchRecords()
  }
  catch (error: any) {
    toast.error(error.message || '删除失败')
  }
}

function toggleSelectAll() {
  if (selectedIds.value.length === records.value.length) {
    selectedIds.value = []
  }
  else {
    selectedIds.value = records.value.map(r => r.id)
  }
}

function toggleSelect(id: number) {
  const index = selectedIds.value.indexOf(id)
  if (index > -1) {
    selectedIds.value.splice(index, 1)
  }
  else {
    selectedIds.value.push(id)
  }
}

function formatDate(date: string) {
  return new Date(date).toLocaleString('zh-CN')
}

function formatData(data: Record<string, any>) {
  try {
    return JSON.stringify(data, null, 2)
  }
  catch {
    return String(data)
  }
}

onMounted(async () => {
  await fetchVariable()
  if (variable.value) {
    fetchRecords()
  }
})
</script>

<template>
  <BasicPage
    title="变量记录"
    description="查看云端变量的记录数据"
    :breadcrumbs="[
      { title: '云端变量', href: '/admin/cloud-variables' },
      { title: '变量记录' },
    ]"
  >
    <div class="space-y-6">
      <div class="flex items-center justify-between">
        <div class="flex items-center gap-4">
          <div class="flex items-center gap-2">
            <UiLabel class="text-sm">开始日期</UiLabel>
            <UiInput
              v-model="startDate"
              type="date"
              class="w-40"
            />
          </div>
          <div class="flex items-center gap-2">
            <UiLabel class="text-sm">结束日期</UiLabel>
            <UiInput
              v-model="endDate"
              type="date"
              class="w-40"
            />
          </div>
          <UiButton @click="fetchRecords">
            <Search class="h-4 w-4 mr-2" />
            查询
          </UiButton>
        </div>
        <div class="flex items-center gap-2">
          <UiButton
            v-if="selectedIds.length > 0"
            variant="destructive"
            @click="handleDeleteSelected"
          >
            <Trash2 class="h-4 w-4 mr-2" />
            删除选中 ({{ selectedIds.length }})
          </UiButton>
        </div>
      </div>

      <div class="border rounded-lg">
        <div class="overflow-x-auto">
          <table class="w-full text-sm">
            <thead class="bg-muted/50">
              <tr>
                <th class="w-10 p-3 text-left">
                  <UiCheckbox
                    :checked="selectedIds.length === records.length && records.length > 0"
                    @update:checked="toggleSelectAll"
                  />
                </th>
                <th class="p-3 text-left font-medium">
                  ID
                </th>
                <th v-if="variable?.scope === 'user'" class="p-3 text-left font-medium">
                  用户
                </th>
                <th class="p-3 text-left font-medium">
                  数据
                </th>
                <th class="p-3 text-left font-medium">
                  创建时间
                </th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="record in records"
                :key="record.id"
                class="border-t hover:bg-muted/30"
              >
                <td class="p-3">
                  <UiCheckbox
                    :checked="selectedIds.includes(record.id)"
                    @update:checked="toggleSelect(record.id)"
                  />
                </td>
                <td class="p-3 text-muted-foreground">
                  {{ record.id }}
                </td>
                <td v-if="variable?.scope === 'user'" class="p-3">
                  <span v-if="record.user">{{ record.user.username }}</span>
                  <span v-else class="text-muted-foreground">-</span>
                </td>
                <td class="p-3">
                  <pre class="text-xs bg-muted p-2 rounded max-w-md overflow-auto max-h-32">{{ formatData(record.data) }}</pre>
                </td>
                <td class="p-3 text-muted-foreground">
                  {{ formatDate(record.created_at) }}
                </td>
              </tr>
              <tr v-if="records.length === 0">
                <td :colspan="variable?.scope === 'user' ? 5 : 4" class="p-8 text-center text-muted-foreground">
                  暂无记录
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <div class="flex items-center justify-between">
        <p class="text-sm text-muted-foreground">
          共 {{ total }} 条记录
        </p>
        <div class="flex items-center gap-2">
          <UiButton
            variant="outline"
            size="sm"
            :disabled="page <= 1"
            @click="page--; fetchRecords()"
          >
            上一页
          </UiButton>
          <span class="text-sm">第 {{ page }} 页</span>
          <UiButton
            variant="outline"
            size="sm"
            :disabled="page * pageSize >= total"
            @click="page++; fetchRecords()"
          >
            下一页
          </UiButton>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
