<script setup>
import { computed, h } from 'vue'
import { NDataTable, NEmpty } from 'naive-ui'

const props = defineProps({
  result: { type: Object, default: null },
  // 后端 QueryResult: { columns: ['c1','c2'], rows: [[v1,v2]], executionTimeMs }
  loading: { type: Boolean, default: false }
})

const columns = computed(() => {
  if (!props.result?.columns?.length) return []
  return props.result.columns.map(name => ({
    title: name,
    key: name,
    minWidth: 120,
    ellipsis: { tooltip: true },
    render(row) {
      const v = row[name]
      if (v === null || v === undefined) return h('span', { class: 'cell-null' }, 'NULL')
      if (typeof v === 'object') return JSON.stringify(v)
      return String(v)
    }
  }))
})

const data = computed(() => {
  if (!props.result?.columns?.length || !props.result?.rows?.length) return []
  return props.result.rows.map(rowArr => {
    const obj = {}
    props.result.columns.forEach((name, i) => {
      obj[name] = rowArr[i]
    })
    return obj
  })
})
</script>

<template>
  <div class="query-result">
    <div v-if="result" class="result-meta">
      <span class="meta-item success">
        {{ data.length }} 行
      </span>
      <span class="meta-item">{{ result.executionTimeMs }} ms</span>
    </div>

    <div class="result-table-wrapper">
      <n-data-table
        v-if="data.length"
        :columns="columns"
        :data="data"
        :loading="loading"
        size="small"
        :bordered="true"
        :single-line="false"
        :pagination="{ pageSize: 50 }"
        :max-height="400"
        :scroll-x="columns.length * 140"
        virtual-scroll
      />
      <n-empty v-else description="无数据或未执行查询" style="padding: 40px 0" />
    </div>
  </div>
</template>

<style scoped>
.query-result {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
}
.result-meta {
  display: flex;
  gap: 12px;
  padding: 6px 12px;
  font-size: 12px;
  background: var(--bg-card);
  border-bottom: 1px solid var(--border-color);
}
.meta-item {
  color: var(--text-muted);
}
.meta-item.success { color: #10b981; font-weight: 500; }

.result-table-wrapper {
  flex: 1;
  overflow: auto;
  min-height: 0;
}
:deep(.cell-null) {
  color: var(--text-muted);
  font-style: italic;
  opacity: 0.6;
}
:deep(.n-data-table-th) {
  font-family: 'JetBrains Mono', monospace;
  font-size: 12px;
  background: var(--bg-secondary) !important;
}
:deep(.n-data-table-td) {
  font-family: 'JetBrains Mono', monospace;
  font-size: 12px;
}
</style>
