<template>
  <div class="page-shell">
    <section class="page-card table-fill">
      <div class="page-toolbar">
        <h2 class="page-toolbar-title">OpenAPI</h2>
        <div class="page-toolbar-actions">
          <n-button :loading="loading" @click="load">
            <template #icon><n-icon :component="RefreshCw" /></template>
            刷新
          </n-button>
        </div>
      </div>

      <div class="card-body card-body-fill table-fill">
        <n-data-table
          flex-height
          size="small"
          :columns="columns"
          :data="rows"
          :loading="loading"
          :pagination="{ pageSize: 12 }"
          :row-key="(row: OpenApiStatisticsItem) => `${row.digitalAccountId}-${row.interfaceCode}`"
          :scroll-x="1040"
        />
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { h, onMounted, ref } from 'vue'
import type { DataTableColumns } from 'naive-ui'
import { NButton, NDataTable, NIcon, NTag } from 'naive-ui'
import { RefreshCw } from 'lucide-vue-next'
import { openApiStatisticsApi } from '@/api/piaotong'
import type { OpenApiStatisticsItem } from '@/api/piaotong'

const loading = ref(false)
const rows = ref<OpenApiStatisticsItem[]>([])

const columns: DataTableColumns<OpenApiStatisticsItem> = [
  { title: '数电账号ID', key: 'digitalAccountId', minWidth: 220 },
  { title: '接口', key: 'interfaceCode', minWidth: 180 },
  { title: '调用次数', key: 'total', width: 100 },
  { title: '成功', key: 'success', width: 100, render: (row) => h(NTag, { type: 'success' }, { default: () => row.success }) },
  { title: '失败', key: 'failed', width: 100, render: (row) => h(NTag, { type: row.failed > 0 ? 'error' : 'default' }, { default: () => row.failed }) },
  { title: '平均耗时(ms)', key: 'avgCostMs', width: 140 },
  { title: '最近调用', key: 'lastCalledAt', minWidth: 180 }
]

async function load() {
  loading.value = true
  try {
    rows.value = await openApiStatisticsApi()
  } finally {
    loading.value = false
  }
}

onMounted(load)
</script>
