<script setup>
import { ref, onMounted } from 'vue'
import { NIcon, NSpin } from 'naive-ui'
import { TimeOutline, CheckmarkCircleOutline, AlertCircleOutline, TrashOutline } from '@vicons/ionicons5'
import { getQueryHistory, clearQueryHistory } from '../../api/datasource'

const props = defineProps({
  datasourceId: { type: [Number, null], default: null }
})
const emit = defineEmits(['reuse'])

const loading = ref(false)
const history = ref([])
const page = ref(1)
const size = ref(20)
const total = ref(0)

async function load() {
  if (!props.datasourceId) return
  loading.value = true
  try {
    const res = await getQueryHistory(props.datasourceId, page.value, size.value)
    const data = res.data || {}
    history.value = data.content || data.records || []
    total.value = data.totalElements || data.total || 0
  } catch (e) {
    history.value = []
  } finally {
    loading.value = false
  }
}

async function clearAll() {
  if (!props.datasourceId) return
  if (!confirm('确定清空所有查询历史？此操作不可恢复。')) return
  try {
    await clearQueryHistory(props.datasourceId)
    await load()
  } catch (e) {
    // 全局拦截器已经弹消息
  }
}

function formatTime(iso) {
  if (!iso) return ''
  try {
    const d = new Date(iso)
    return d.toLocaleString('zh-CN', { hour12: false })
  } catch {
    return iso
  }
}

function truncate(s, n = 60) {
  if (!s) return ''
  return s.length > n ? s.slice(0, n) + '…' : s
}

onMounted(() => {
  if (props.datasourceId) load()
})
</script>

<template>
  <div class="query-history">
    <div class="history-header">
      <span class="header-title">查询历史</span>
      <button class="icon-btn-sm" @click="load" title="刷新">
        <n-icon size="12"><TimeOutline /></n-icon>
      </button>
      <button class="icon-btn-sm danger" @click="clearAll" :disabled="!history.length" title="清空">
        <n-icon size="12"><TrashOutline /></n-icon>
      </button>
    </div>

    <div class="history-body">
      <div v-if="loading" class="loading"><n-spin size="small" /></div>
      <div v-else-if="!datasourceId" class="empty-text">未选择数据源</div>
      <div v-else-if="!history.length" class="empty-text">暂无历史</div>
      <div v-else class="history-list">
        <div
          v-for="item in history"
          :key="item.id"
          class="history-item"
          @click="emit('reuse', item.sql)"
          :title="'点击重新加载到编辑器'"
        >
          <div class="item-header">
            <n-icon size="12" :color="item.status === 'SUCCESS' ? '#10b981' : '#ef4444'">
              <CheckmarkCircleOutline v-if="item.status === 'SUCCESS'" />
              <AlertCircleOutline v-else />
            </n-icon>
            <span class="item-time">{{ formatTime(item.executedAt) }}</span>
            <span class="item-meta" v-if="item.status === 'SUCCESS'">
              {{ item.rowCount }} 行 / {{ item.executionTimeMs }} ms
            </span>
          </div>
          <div class="item-sql">{{ truncate(item.sql) }}</div>
          <div class="item-error" v-if="item.status === 'FAILED' && item.errorMessage">
            {{ truncate(item.errorMessage, 80) }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.query-history {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
}
.history-header {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  border-bottom: 1px solid var(--border-color);
  background: var(--bg-card);
}
.header-title {
  flex: 1;
  font-size: 12px;
  font-weight: 600;
  color: var(--text-secondary);
}
.icon-btn-sm {
  background: none; border: none;
  color: var(--text-muted); cursor: pointer;
  padding: 4px; border-radius: 4px;
  display: flex; align-items: center;
}
.icon-btn-sm:hover { color: var(--color-accent); background: rgba(37,99,235,0.1); }
.icon-btn-sm.danger:hover { color: #ef4444; background: rgba(239,68,68,0.1); }
.icon-btn-sm:disabled { opacity: 0.4; cursor: not-allowed; }

.history-body { flex: 1; overflow-y: auto; }
.loading, .empty-text {
  display: flex; align-items: center; justify-content: center;
  padding: 24px; color: var(--text-muted); font-size: 12px;
}

.history-list { padding: 4px 0; }
.history-item {
  padding: 6px 12px;
  cursor: pointer;
  border-bottom: 1px dashed var(--border-color);
  transition: background 0.15s;
}
.history-item:hover { background: rgba(37,99,235,0.06); }
.item-header {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 10px;
  color: var(--text-muted);
}
.item-time { flex: 1; }
.item-meta {
  color: #10b981;
  font-family: 'JetBrains Mono', monospace;
}
.item-sql {
  margin-top: 3px;
  font-size: 11px;
  font-family: 'JetBrains Mono', monospace;
  color: var(--text-secondary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.item-error {
  margin-top: 2px;
  font-size: 10px;
  color: #ef4444;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
