<template>
  <div class="app-container">
    <el-card class="box-card" shadow="always">
      <div class="body-wrapper">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="数据库">
            <el-select v-model="searchForm.sourceId" placeholder="数据库">
              <el-option
                v-for="item in sourceOptions"
                :key="item.id"
                :label="item.sourceName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="数据表">
            <el-select v-model="searchForm.tableId" clearable placeholder="数据表">
              <el-option
                v-for="item in tableOptions"
                :key="item.id"
                :label="item.tableComment ? item.tableComment : item.tableName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </el-form-item>
        </el-form>
        <el-divider />
        <el-row>
          <el-col :span="24">
            <el-table
              :data="tableDataList"
              stripe
              border
              :max-height="200"
              style="width: 100%; margin: 15px 0;"
            >
              <el-table-column prop="CONSTRAINT_NAME" label="映射名称" align="center" show-overflow-tooltip />
              <el-table-column prop="TABLE_NAME" label="源表" align="center" show-overflow-tooltip />
              <el-table-column prop="REFERENCED_TABLE_NAME" label="目标表" align="center" show-overflow-tooltip />
              <el-table-column prop="COLUMN_NAME" label="映射字段" align="center" show-overflow-tooltip />
            </el-table>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div id="chart" style="width: 100%; height: 500px;" />
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script>
import echarts from 'echarts'
import { listDataSource } from '@/api/metadata/datasource'
import { listDataTable } from '@/api/metadata/datatable'
import { getMetadatablood } from '@/api/metadata/datasource'

export default {
  name: 'DataBlood',
  data: function() {
    return {
      searchForm: {
        sourceId: '',
        tableId: ''
      },
      queryParams: {
        tableName: ''
      },
      sourceOptions: [],
      tableOptions: [],
      chart: null,
      tableDataList: []
    }
  },
  watch: {
    'searchForm.sourceId': {
      immediate: true,
      // handler:是一个回调函数，即监听到变化应该执行的函数
      handler(value) {
        if (value) {
          // 清空数据
          this.searchForm.tableId = ''
          this.getDataTableList(value)
        }
      }
    }
  },
  created() {
    this.getDataSourceList()
  },
  mounted() {
    this.chart = echarts.init(document.getElementById('chart'))
    this.handleQuery()
  },
  beforeDestroy() {
    if (!this.chart) {
      return false
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    getDataSourceList() {
      listDataSource().then(response => {
        if (response.success) {
          this.sourceOptions = response.data
          this.searchForm.sourceId = this.sourceOptions[0].id
          this.getDataTableList(this.sourceOptions[0].id)
        }
      })
    },
    getDataTableList(sourceId) {
      const data = {}
      data.sourceId = sourceId
      listDataTable(data).then(response => {
        if (response.success) {
          console.log('ddddddd', response)
          this.tableOptions = response.data
        }
      })
    },
    handleQuery() {
      getMetadatablood({ sourceId: this.searchForm.sourceId, tableId: this.searchForm.tableId }).then(response => {
        if (response.success) {
          const { data } = response
          this.tableDataList = data
          console.log('datadata', data)
          this.reloadData()
        }
      })
    },
    reloadData() {
      let data = { nodes: [], links: [] }
      const nodes = []
      const links = []
      const colors = ['#fbb4ae', '#b3cde3', '#ccebc5', '#decbe4']
      this.tableDataList.forEach(item => {
        nodes.push({
          name: item.TABLE_NAME,
          itemStyle: {
            normal: {
              color: colors[Math.floor(Math.random() * colors.length)]
            }
          }
        })
        nodes.push({
          name: item.REFERENCED_TABLE_NAME,
          itemStyle: {
            normal: {
              color: colors[Math.floor(Math.random() * colors.length)]
            }
          }
        })
        links.push({
          source: item.TABLE_NAME,
          target: item.REFERENCED_TABLE_NAME,
          value: item.CONSTRAINT_NAME.length,
          mapping: item.CONSTRAINT_NAME
        })
      })
      // nodes数组去重
      const res = new Map()
      const nodes_uniq = nodes.filter((node) => !res.has(node.name) && res.set(node.name, 1))
      data = {
        nodes: nodes_uniq,
        links: links
      }
      this.chart.clear()
      this.chart.setOption({
        title: {
          text: '血缘流向'
        },
        tooltip: {
          trigger: 'item',
          triggerOn: 'mousemove',
          formatter: function(x) {
            return x.data.mapping
          }
        },
        animation: false,
        series: [
          {
            type: 'sankey',
            focusNodeAdjacency: 'allEdges',
            nodeAlign: 'left',
            data: data.nodes,
            links: data.links,
            lineStyle: {
              color: 'source',
              curveness: 0.5
            }
          }
        ]
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card ::v-deep .el-card__body {
  height: calc(100vh - 170px);
}
</style>
