<template>
  <div class="page-container metadata-page">
    <h2 class="page-title">数据资产</h2>

    <el-row :gutter="16" class="content-row">
      <!-- Tree -->
      <el-col :xs="24" :md="7" :lg="6">
        <div class="tree-card card-shadow">
          <div class="tree-header">资产目录</div>
          <el-input
            v-model="treeKeyword"
            placeholder="搜索表名"
            clearable
            size="small"
            class="tree-search"
          />
          <el-tree
            :data="treeData"
            :props="{ children: 'children', label: 'name' }"
            :filter-node-method="filterNode"
            ref="treeRef"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <el-icon v-if="data.type === 'source'" size="14"><DataLine /></el-icon>
                <el-icon v-else-if="data.type === 'database'" size="14"><FolderOpened /></el-icon>
                <el-icon v-else size="14"><Document /></el-icon>
                <span class="node-label">{{ node.label }}</span>
                <span v-if="data.type === 'table' && data.meta?.column_count" class="node-badge">
                  {{ data.meta.column_count }}
                </span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-col>

      <!-- Table Detail -->
      <el-col :xs="24" :md="17" :lg="18">
        <div class="detail-card card-shadow">
          <div class="detail-header">
            <div class="detail-title">
              <span v-if="selectedTable">{{ selectedTable.name }}</span>
              <span v-else class="placeholder">请从左侧选择数据表</span>
              <el-tag v-if="selectedTable?.meta?.row_count" size="small" type="info">
                约 {{ selectedTable.meta.row_count.toLocaleString() }} 行
              </el-tag>
            </div>
            <el-input
              v-if="selectedTable"
              v-model="columnKeyword"
              placeholder="搜索字段"
              clearable
              size="small"
              style="width: 200px"
            />
          </div>

          <el-table
            v-if="selectedTable"
            :data="columnList"
            v-loading="columnLoading"
            stripe
            size="default"
            height="calc(100vh - 280px)"
          >
            <el-table-column prop="name" label="字段名" min-width="140" />
            <el-table-column prop="data_type" label="类型" width="120" />
            <el-table-column prop="comment" label="注释" min-width="180" show-overflow-tooltip />
            <el-table-column prop="is_nullable" label="可空" width="80">
              <template #default="{ row }">
                <el-tag size="small" :type="row.is_nullable ? 'info' : 'success'">
                  {{ row.is_nullable ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sample_data" label="采样数据" min-width="200" show-overflow-tooltip>
              <template #default="{ row }">
                <span class="sample-text">{{ row.sample_data }}</span>
              </template>
            </el-table-column>
          </el-table>

          <el-empty v-else description="请选择左侧数据表查看字段详情" />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { DataLine, FolderOpened, Document } from '@element-plus/icons-vue'
import { getMetadataTree, getColumns } from '@/api/metadata'
import type { TreeNode, DataColumn } from '@/api/metadata'

const treeData = ref<TreeNode[]>([])
const treeKeyword = ref('')
const treeRef = ref()
const selectedTable = ref<TreeNode | null>(null)
const columnList = ref<DataColumn[]>([])
const columnLoading = ref(false)
const columnKeyword = ref('')

watch(treeKeyword, (val) => {
  treeRef.value?.filter(val)
})

function filterNode(value: string, data: TreeNode) {
  if (!value) return true
  return data.name.toLowerCase().includes(value.toLowerCase())
}

async function fetchTree() {
  try {
    const res: any = await getMetadataTree()
    treeData.value = res.data || []
  } catch (e: any) {
    ElMessage.error(e?.message || '加载失败')
  }
}

async function handleNodeClick(data: TreeNode) {
  if (data.type === 'table') {
    selectedTable.value = data
    await fetchColumns(data.id)
  }
}

async function fetchColumns(tableId: number) {
  columnLoading.value = true
  try {
    const res: any = await getColumns({
      table_id: tableId,
      keyword: columnKeyword.value || undefined,
      page: 1,
      page_size: 500,
    })
    columnList.value = res.data || []
  } finally {
    columnLoading.value = false
  }
}

watch(columnKeyword, () => {
  if (selectedTable.value) {
    fetchColumns(selectedTable.value.id)
  }
})

onMounted(fetchTree)
</script>

<style scoped lang="scss">
.metadata-page {
  .page-title {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 16px;
    color: #303133;
  }
}

.content-row {
  .el-col {
    margin-bottom: 16px;
  }
}

.tree-card {
  padding: 16px;
  height: calc(100vh - 140px);
  overflow-y: auto;

  .tree-header {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 12px;
    color: #303133;
  }

  .tree-search {
    margin-bottom: 12px;
  }
}

.custom-tree-node {
  display: flex;
  align-items: center;
  gap: 6px;
  flex: 1;
  overflow: hidden;

  .node-label {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .node-badge {
    font-size: 11px;
    color: #909399;
    background: #f2f6fc;
    padding: 0 6px;
    border-radius: 10px;
  }
}

.detail-card {
  padding: 16px;
  height: calc(100vh - 140px);
  display: flex;
  flex-direction: column;

  .detail-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
    flex-wrap: wrap;
    gap: 12px;

    .detail-title {
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 16px;
      font-weight: 600;
      color: #303133;

      .placeholder {
        color: #909399;
        font-weight: normal;
      }
    }
  }
}

.sample-text {
  color: #909399;
  font-size: 12px;
}
</style>
