<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useMessage } from 'naive-ui'
import {
  NButton, NIcon, NSpin, NTabs, NTabPane, NTag
} from 'naive-ui'
import {
  AddOutline, RefreshOutline, ServerOutline, CreateOutline,
  TrashOutline, FlashOutline, AlertCircleOutline
} from '@vicons/ionicons5'
import DataSourceForm from '../../components/knowledge/DataSourceForm.vue'
import TableExplorer from '../../components/knowledge/TableExplorer.vue'
import SqlConsole from '../../components/knowledge/SqlConsole.vue'
import QueryHistory from '../../components/knowledge/QueryHistory.vue'
import {
  getDataSources, deleteDataSource, getStructuredRagProfile, refreshStructuredRagProfile, testExistingDataSource
} from '../../api/datasource'

const message = useMessage()

// ============ 状态 ============
const loading = ref(false)
const dataSources = ref([])
const selectedId = ref(null)
const activeTab = ref('tables')

const showForm = ref(false)
const editing = ref(null)
const ragProfile = ref(null)
const profileLoading = ref(false)

const historyVersion = ref(0)  // 用于触发 QueryHistory 刷新

const selectedDs = computed(() =>
  dataSources.value.find(d => d.id === selectedId.value) || null
)

// ============ 加载 ============
async function loadDataSources() {
  loading.value = true
  try {
    const res = await getDataSources()
    const list = res.data || []
    dataSources.value = list
    // 自动选择第一个
    if (!selectedId.value && list.length) {
      selectedId.value = list[0].id
    }
  } catch (e) {
    message.error('加载数据源失败：' + e.message)
  } finally {
    loading.value = false
  }
}

// ============ 操作 ============
function onAdd() {
  editing.value = null
  showForm.value = true
}

function onEdit(ds) {
  editing.value = ds
  showForm.value = true
}

async function onDelete(ds) {
  if (!confirm(`确定删除数据源「${ds.name}」？关联的连接池和查询历史将一并清理。`)) return
  try {
    await deleteDataSource(ds.id)
    if (selectedId.value === ds.id) {
      selectedId.value = dataSources.value.length > 1
        ? dataSources.value.find(d => d.id !== ds.id)?.id || null
        : null
    }
    await loadDataSources()
    message.success('已删除')
  } catch (e) {
    // 全局拦截器已经弹消息
  }
}

async function onTestExisting(ds) {
  try {
    const res = await testExistingDataSource(ds.id)
    if (res.data?.success) {
      message.success('连接成功')
    } else {
      message.error('连接失败：' + (res.data?.message || '未知错误'))
    }
    await loadDataSources()
  } catch (e) {
    // 全局拦截器已经弹消息
  }
}

function onSaved() {
  loadDataSources()
}

function selectDs(id) {
  selectedId.value = id
}

async function loadRagProfile() {
  if (!selectedId.value) { ragProfile.value = null; return }
  profileLoading.value = true
  try { ragProfile.value = (await getStructuredRagProfile(selectedId.value)).data || null }
  catch (error) { message.error('加载RAG画像失败：' + error.message) }
  finally { profileLoading.value = false }
}

async function refreshRagProfile() {
  if (!selectedId.value) return
  profileLoading.value = true
  try {
    ragProfile.value = (await refreshStructuredRagProfile(selectedId.value)).data || null
    message.success('画像刷新任务已提交')
    setTimeout(loadRagProfile, 2500)
  } catch (error) { message.error('刷新RAG画像失败：' + error.message) }
  finally { profileLoading.value = false }
}

// TableExplorer / SqlConsole 双击插入字段回调
function onInsertTable(name) {
  message.info(`已选中表：${name}（在 SQL Console 中双击表名/字段名可快速插入）`)
}

// ============ 类型显示 ============
const typeColorMap = {
  MYSQL: 'success',
  POSTGRESQL: 'info',
  DAMENG: 'error',
  DM: 'error',
  ORACLE: 'warning',
  SQLSERVER: 'warning',
  SQLITE: 'default',
  H2: 'default'
}

// ============ 生命周期 ============
onMounted(() => {
  loadDataSources()
})
watch(selectedId, loadRagProfile)
</script>

<template>
  <div class="ds-page">

    <div class="ds-layout">
      <!-- 左侧：数据源列表 -->
      <aside class="ds-sidebar">
        <div class="sidebar-header">
          <span class="sidebar-title">数据源</span>
          <div class="sidebar-actions">
            <button class="icon-btn-sm" @click="onAdd" title="新增数据源">
              <n-icon size="14">
                <AddOutline />
              </n-icon>
            </button>
            <button class="icon-btn-sm" @click="loadDataSources" title="刷新">
              <n-icon size="14">
                <RefreshOutline />
              </n-icon>
            </button>
          </div>
        </div>

        <div class="sidebar-body">
          <div v-if="loading && !dataSources.length" class="loading">
            <n-spin size="small" />
          </div>
          <div v-else-if="!dataSources.length" class="empty-block">
            <n-icon size="32" color="var(--text-muted)">
              <ServerOutline />
            </n-icon>
            <div class="empty-title">暂无数据源</div>
            <n-button size="small" type="primary" @click="onAdd">
              <template #icon><n-icon>
                  <AddOutline />
                </n-icon></template>
              新增数据源
            </n-button>
          </div>
          <div v-else class="ds-list">
            <div v-for="ds in dataSources" :key="ds.id" class="ds-card" :class="{ active: selectedId === ds.id }"
              @click="selectDs(ds.id)">
              <div class="ds-card-header">
                <n-icon size="14" color="var(--color-accent)">
                  <ServerOutline />
                </n-icon>
                <span class="ds-name" :title="ds.name">{{ ds.name }}</span>
                <n-tag size="tiny" :type="typeColorMap[ds.type] || 'default'" round>
                  {{ ds.type }}
                </n-tag>
              </div>
              <div class="ds-jdbc" :title="ds.jdbcUrl">{{ ds.jdbcUrl }}</div>
              <div class="ds-status">
                <span v-if="ds.testStatus === 'SUCCESS'" class="status-ok">
                  <n-icon size="10">
                    <FlashOutline />
                  </n-icon> 已连通
                </span>
                <span v-else-if="ds.testStatus === 'FAILED'" class="status-fail">
                  <n-icon size="10">
                    <AlertCircleOutline />
                  </n-icon> 连接失败
                </span>
                <span v-else class="status-unknown">未测试</span>
                <span class="ds-user">{{ ds.username }}@{{ ds.schemaName || '-' }}</span>
              </div>
              <div class="ds-card-footer">
                <button class="action-btn" title="测试连接" @click.stop="onTestExisting(ds)">
                  <n-icon size="12">
                    <FlashOutline />
                  </n-icon>
                </button>
                <button class="action-btn" title="编辑" @click.stop="onEdit(ds)">
                  <n-icon size="12">
                    <CreateOutline />
                  </n-icon>
                </button>
                <button class="action-btn danger" title="删除" @click.stop="onDelete(ds)">
                  <n-icon size="12">
                    <TrashOutline />
                  </n-icon>
                </button>
              </div>
            </div>
          </div>
        </div>
      </aside>

      <!-- 右侧：详情区 -->
      <main class="ds-main">
        <div v-if="!selectedDs" class="main-empty">
          <n-icon size="48" color="var(--text-muted)">
            <ServerOutline />
          </n-icon>
          <div class="empty-title">请选择左侧数据源</div>
          <div class="empty-sub">选择数据源后可浏览表结构、执行 SQL 查询</div>
        </div>
        <div v-else class="main-content">
          <div class="profile-strip">
            <div><b>Text2SQL画像</b><n-tag size="small" :type="ragProfile?.scanStatus === 'SUCCESS' ? 'success' : ragProfile?.scanStatus === 'FAILED' ? 'error' : 'warning'">{{ ragProfile?.scanStatus || '加载中' }}</n-tag></div>
            <span>表 {{ ragProfile?.tableCount || 0 }}</span>
            <span>物理关系 {{ ragProfile?.physicalRelationships || 0 }}</span>
            <span>推断关系 {{ ragProfile?.inferredRelationships || 0 }}</span>
            <span>条件关系 {{ ragProfile?.conditionalRelationships || 0 }}</span>
            <span v-if="ragProfile?.scannedAt">{{ new Date(ragProfile.scannedAt).toLocaleString('zh-CN') }}</span>
            <n-button size="tiny" :loading="profileLoading" @click="refreshRagProfile">刷新画像</n-button>
          </div>
          <n-tabs v-model:value="activeTab" type="line" animated style="height: 100%">
            <n-tab-pane name="tables" tab="表结构" style="height: 100%">
              <TableExplorer :datasource-id="selectedId" @insert-table="onInsertTable" />
            </n-tab-pane>
            <n-tab-pane name="sql" tab="SQL 控制台" style="height: 100%">
              <SqlConsole :datasource-id="selectedId" @executed="historyVersion++" />
            </n-tab-pane>
            <n-tab-pane name="history" tab="查询历史" style="height: 100%">
              <QueryHistory :key="historyVersion" :datasource-id="selectedId" />
            </n-tab-pane>
          </n-tabs>
        </div>
      </main>
    </div>

    <DataSourceForm v-model:show="showForm" :editing="editing" @saved="onSaved" />
  </div>
</template>

<style scoped>
.ds-page {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
}

.driver-banner {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: rgba(245, 158, 11, 0.08);
  border-bottom: 1px solid rgba(245, 158, 11, 0.2);
  color: #f59e0b;
  font-size: 12px;
}

.banner-text {
  line-height: 1.5;
}

.ds-layout {
  display: grid;
  grid-template-columns: 280px 1fr;
  flex: 1;
  min-height: 0;
}

/* 左侧 */
.ds-sidebar {
  display: flex;
  flex-direction: column;
  border-right: 1px solid var(--border-color);
  background: var(--bg-secondary);
  min-height: 0;
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 14px;
  border-bottom: 1px solid var(--border-color);
}

.sidebar-title {
  font-size: 13px;
  font-weight: 600;
  color: var(--text-secondary);
}

.sidebar-actions {
  display: flex;
  gap: 4px;
}

.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);
}

.sidebar-body {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.loading,
.empty-block {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 16px;
  gap: 12px;
  color: var(--text-muted);
  font-size: 12px;
}

.empty-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-secondary);
}

.empty-sub {
  font-size: 12px;
  color: var(--text-muted);
}

.ds-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.ds-card {
  padding: 10px 12px;
  background: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.15s;
}

.ds-card:hover {
  border-color: var(--color-accent);
}

.ds-card.active {
  border-color: var(--color-accent);
  background: rgba(37, 99, 235, 0.08);
}

.ds-card-header {
  display: flex;
  align-items: center;
  gap: 6px;
}

.ds-name {
  flex: 1;
  font-size: 13px;
  font-weight: 500;
  color: var(--text-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.ds-jdbc {
  margin-top: 4px;
  font-size: 10px;
  color: var(--text-muted);
  font-family: 'JetBrains Mono', monospace;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.ds-status {
  margin-top: 4px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 10px;
}

.status-ok {
  color: #10b981;
  display: flex;
  align-items: center;
  gap: 3px;
}

.status-fail {
  color: #ef4444;
  display: flex;
  align-items: center;
  gap: 3px;
}

.status-unknown {
  color: var(--text-muted);
}

.ds-user {
  color: var(--text-muted);
  font-family: 'JetBrains Mono', monospace;
}

.ds-card-footer {
  display: flex;
  gap: 4px;
  margin-top: 8px;
  justify-content: flex-end;
  border-top: 1px dashed var(--border-color);
  padding-top: 6px;
}

.action-btn {
  background: none;
  border: none;
  color: var(--text-muted);
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.action-btn:hover {
  color: var(--color-accent);
  background: rgba(37, 99, 235, 0.1);
}

.action-btn.danger:hover {
  color: #ef4444;
  background: rgba(239, 68, 68, 0.1);
}

/* 右侧 */
.ds-main {
  display: flex;
  flex-direction: column;
  min-height: 0;
  background: var(--bg-primary);
}

.main-empty {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  color: var(--text-muted);
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  padding: 0 8px;
}

:deep(.n-tabs) {
  display: flex;
  flex-direction: column;
}

:deep(.n-tab-pane) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.n-tabs-pane-wrapper) {
  flex: 1;
  min-height: 0;
}
.profile-strip{display:flex;align-items:center;gap:14px;min-height:44px;padding:8px 14px;border-bottom:1px solid var(--border-color);font-size:12px;color:var(--text-secondary)}
.profile-strip>div{display:flex;align-items:center;gap:8px;color:var(--text-primary)}
.profile-strip .n-button{margin-left:auto}
</style>
