<template>
  <div class="page-container">
    <h2 class="page-title">数据血缘分析</h2>
    <div class="card-shadow" style="padding: 16px; margin-bottom: 16px;">
      <el-form :model="form" label-width="80px">
        <el-form-item label="目标表">
          <el-input v-model="form.target_table" placeholder="如：dwd_order" style="width: 240px" />
        </el-form-item>
        <el-form-item label="SQL">
          <el-input v-model="form.sql" type="textarea" :rows="4" placeholder="输入ETL SQL，如：SELECT a.id, b.name FROM ods_order a JOIN dim_user b ON a.user_id = b.id" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="parseLoading" @click="handleParse">解析血缘</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="card-shadow" style="padding: 16px;">
      <div style="font-weight: 600; margin-bottom: 12px;">血缘关系图</div>
      <v-chart class="chart" :option="graphOption" autoresize />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { GraphChart } from 'echarts/charts'
import { TooltipComponent, LegendComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import { parseLineage, getLineageGraph } from '@/api/lineage'

use([CanvasRenderer, GraphChart, TooltipComponent, LegendComponent])

const form = ref({ sql: '', target_table: '' })
const parseLoading = ref(false)
const graphData = ref<{ nodes: any[]; links: any[] }>({ nodes: [], links: [] })

const graphOption = computed(() => ({
  tooltip: {},
  legend: [{ data: ['上游', '下游'] }],
  series: [{
    type: 'graph',
    layout: 'force',
    symbolSize: 50,
    roam: true,
    label: { show: true },
    edgeSymbol: ['circle', 'arrow'],
    edgeSymbolSize: [4, 10],
    data: graphData.value.nodes.map((n: any, idx: number) => ({ ...n, category: n.category || 0 })),
    links: graphData.value.links,
    categories: [{ name: '上游' }, { name: '下游' }],
    force: { repulsion: 300, edgeLength: 150 },
  }],
}))

async function handleParse() {
  if (!form.value.sql || !form.value.target_table) {
    ElMessage.warning('请输入SQL和目标表')
    return
  }
  parseLoading.value = true
  try {
    await parseLineage(form.value.sql, form.value.target_table)
    ElMessage.success('解析成功')
    fetchGraph()
  } catch (e: any) { ElMessage.error(e?.message || '解析失败') }
  finally { parseLoading.value = false }
}

async function fetchGraph() {
  try {
    const res: any = await getLineageGraph()
    graphData.value = res.data || { nodes: [], links: [] }
  } catch (e) { /* ignore */ }
}

onMounted(fetchGraph)
</script>

<style scoped lang="scss">
.chart {
  width: 100%;
  height: 500px;
}
</style>
