<template>
  <div>
    <MDialog :visible="visible" title="数据预览" widthType="1" :footer="false" max-width="90%" @update:visible="handleVisibleChange">
    <div v-if="previewData.product" class="mb-4">
      <v-card outlined>
        <v-card-text>
          <div class="d-flex align-center mb-2">
            <span class="text-h6 mr-3">{{ previewData.product.product_name }}</span>
            <v-chip small>{{ previewData.total_count }} 条记录</v-chip>
          </div>
          <div class="text-body-2">
            <span class="mr-4">目标表: {{ previewData.product.target_schema }}.{{ previewData.product.target_table }}</span>
            <span>列数: {{ previewData.product.column_count }}</span>
          </div>
        </v-card-text>
      </v-card>
      <v-alert v-if="previewData.error" type="warning" dense class="ma-3">{{ previewData.error }}</v-alert>
    </div>
    <div v-loading="loading" style="max-height: 600px; overflow-y: auto;">
      <div v-if="previewData.columns && previewData.columns.length" class="mb-2 d-flex justify-end align-center">
        <v-select
          v-model="selectedColumns"
          :items="allColumns"
          hide-details
          label="选择表头"
          placeholder="选择表头"
          height="36"
          class="mt-2"
          outlined
          multiple
          dense
          style="max-width: 300px;"
          @change="handleColumnChange"
        >
          <template v-slot:selection="{ item, index }">
            <v-chip v-if="index === 0" small>
              <span>{{ item }}</span>
            </v-chip>
            <span
              v-if="index === 1"
              class="grey--text text-caption"
            >
              (+{{ selectedColumns.length - 1 }} others)
            </span>
          </template>
        </v-select>
      </div>
      <v-simple-table v-if="displayColumns && displayColumns.length" fixed-header height="400px">
        <template v-slot:default>
          <thead>
            <tr>
              <th v-for="col in displayColumns" :key="col.name" class="text-left">
                <div>
                  <div>{{ col.name }}</div>
                </div>
              </th>
              <th class="text-center" width="100">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(row, index) in previewData.data" :key="index">
              <td v-for="col in displayColumns" :key="col.name">
                {{ row[col.name] }}
              </td>
              <td class="text-center">
                <v-btn text color="primary" @click="handleVisualize(row)">可视化</v-btn>
              </td>
            </tr>
          </tbody>
        </template>
      </v-simple-table>
      <div v-else class="text-center pa-10 text--secondary">
        暂无数据
      </div>
      <div v-if="previewData.preview_count > 0" class="text-end text--secondary">
        <span>已加载 {{ previewData.preview_count || 0 }} / {{ previewData.total_count || 0 }} 条</span>
      </div>
    </div>
    <template #footer>
      <v-divider></v-divider>
      <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn
          v-if="previewData.preview_count < previewData.total_count && limit < 1000"
          text
          color="primary"
          @click="handleLoadMore"
        >
          加载更多
        </v-btn>
        <v-btn v-if="previewData?.data?.length > 0" text color="success" @click="handleDownload">下载Excel</v-btn>
        <v-btn text @click="handleClose">关闭</v-btn>
      </v-card-actions>
    </template>
    </MDialog>
    <!-- 可视化图谱弹窗 -->
    <MDialog
      :visible="graphDialogVisible"
      title="数据加工可视化"
      widthType="1"
      :footer="false"
      max-width="95%"
      @update:visible="handleGraphDialogVisibleChange"
    >
      <div style="height: 80vh;">
        <m-graph :graph-data="graphData"></m-graph>
      </div>
    </MDialog>
  </div>
</template>

<script>
import MDialog from '@/components/Dialog'
import mGraph from './mGraph.vue'
import { api } from '@/api/dataService'

export default {
  name: 'PreviewDialog',
  components: {
    MDialog,
    mGraph
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    },
    previewData: {
      type: Object,
      default: () => ({
        product: null,
        columns: [],
        data: [],
        total_count: 0,
        preview_count: 0,
        error: null
      })
    },
    limit: {
      type: Number,
      default: 200
    }
  },
  data () {
    return {
      selectedColumns: [],
      graphDialogVisible: false,
      graphData: null
    }
  },
  computed: {
    allColumns () {
      return this.previewData.columns ? this.previewData.columns.map(col => col.name) : []
    },
    displayColumns () {
      if (!this.previewData.columns || !this.previewData.columns.length) {
        return []
      }
      // 返回选中的列，如果没有选中则返回空数组（等待默认选中前10条）
      if (this.selectedColumns.length === 0) {
        return []
      }
      return this.previewData.columns.filter(col => this.selectedColumns.includes(col.name))
    }
  },
  watch: {
    visible (val) {
      if (!val) {
        // 关闭时重置
        this.selectedColumns = []
      }
    },
    'previewData.columns' (val) {
      if (val && val.length && this.visible) {
        // 只在首次加载（selectedColumns为空）时，默认选中前6条
        // 如果已经有选中的列，则保持用户的选择
        if (this.selectedColumns.length === 0) {
          const defaultCount = Math.min(6, val.length)
          this.selectedColumns = val.slice(0, defaultCount).map(col => col.name)
        }
      }
    }
  },
  methods: {
    // 数据可视化
    async handleVisualize (row) {
      const sampleData = { ...row, target_table: this.previewData.product.target_table }
      try {
        const { data } = await api.getVisualizeData(this.previewData.product.id, { sample_data: sampleData })
        this.graphData = data
        this.graphDialogVisible = true
      } catch (error) {
        this.$snackbar.error(error.message)
      }

      // const data = {
      //   nodes: [
      //     {
      //       id: 212,
      //       name_zh: '用户标签库',
      //       name_en: 'user_tag_library',
      //       node_type: 'BusinessDomain',
      //       labels: ['BusinessDomain'],
      //       is_target: true,
      //       is_source: false,
      //       matched_data: [row, row, row, row, row, row, row, row, row, row, row, row, row, row]
      //     },
      //     {
      //       id: 183,
      //       name_zh: '用户标签生成',
      //       name_en: 'user_tag_generate',
      //       node_type: 'DataFlow',
      //       labels: ['DataFlow'],
      //       is_target: false,
      //       is_source: false
      //     },
      //     {
      //       id: 159,
      //       name_zh: '用户画像',
      //       name_en: 'user_profile',
      //       node_type: 'BusinessDomain',
      //       labels: ['BusinessDomain'],
      //       is_target: false,
      //       is_source: false,
      //       matched_data: [row]
      //     },
      //     {
      //       id: 154,
      //       name_zh: '用户基础数据',
      //       name_en: 'user_base_info',
      //       node_type: 'DataResource',
      //       labels: ['DataResource', 'BusinessDomain'],
      //       is_target: false,
      //       is_source: true,
      //       matched_data: row
      //     }
      //   ],
      //   lines: [
      //     { from: '183', to: '212', text: 'OUTPUT' },
      //     { from: '159', to: '183', text: 'INPUT' },
      //     { from: '156', to: '159', text: 'OUTPUT' },
      //     { from: '154', to: '156', text: 'INPUT' }
      //   ],
      //   lineage_depth: 2
      // }
      // this.graphData = data
      // this.graphDialogVisible = true
    },
    handleColumnChange () {
      // 列选择变化时的处理
      this.$emit('column-change', this.selectedColumns)
    },
    handleLoadMore () {
      this.$emit('load-more')
    },
    handleDownload () {
      this.$emit('download', this.previewData.total_count > 10000 ? 10000 : this.previewData.total_count)
    },
    handleVisibleChange (val) {
      this.$emit('update:visible', val)
    },
    handleClose () {
      this.$emit('update:visible', false)
    },
    handleGraphDialogVisibleChange (val) {
      this.graphDialogVisible = val
      if (!val) {
        // 关闭时清空数据
        this.graphData = null
      }
    }
  }
}
</script>
