<template>
  <div>
    <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;"
        >
          <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>
          <template v-slot:prepend-item>
            <v-list-item
              ripple
              @mousedown.prevent
              @click="handleSelectAll"
            >
              <v-list-item-action>
                <v-icon :color="selectedColumns.length > 0 ? 'primary' : ''">
                  {{ icon }}
                </v-icon>
              </v-list-item-action>
              <v-list-item-content>
                <v-list-item-title>
                  全选
                </v-list-item-title>
              </v-list-item-content>
            </v-list-item>
            <v-divider class="mt-2"></v-divider>
          </template>
        </v-select>
      </div>
      <TableList
        v-if="displayColumns && displayColumns.length"
        :headers="tableHeaders"
        :items="previewData.data"
        :height="400"
        :show-select="false"
        :is-tools="false"
        :show-page="false"
        elevation="0"
        :disable-sort="true"
        :items-per-page="-1"
        :loading="false"
      >
        <template #actions="{ item }">
          <v-btn text color="primary" @click="handleVisualize(item)">可视化</v-btn>
        </template>
      </TableList>
      <div v-else class="text-center pa-10 text--secondary">
          暂无数据
      </div>
      <div v-if="previewData.preview_count > 0 && selectedColumns.length > 0" class="text-end text--secondary">
          <span>已加载 {{ previewData.preview_count || 0 }} / {{ previewData.total_count || 0 }} 条</span>
      </div>
    </div>

    <!-- 关系图谱弹窗 -->
    <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 TableList from '@/components/List/table.vue'
import { api } from '@/api/dataService'

export default {
  name: 'PreviewDialog',
  components: {
    MDialog,
    mGraph,
    TableList
  },
  props: {
    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))
    },
    tableHeaders () {
      const headers = this.displayColumns.map(col => ({
        text: col.name,
        value: col.name,
        align: 'left',
        sortable: false
      }))
      // 添加操作列
      headers.push({
        text: '操作',
        value: 'actions',
        align: 'center',
        sortable: false,
        width: '100px'
      })
      return headers
    },
    likesAllFruit () {
      return this.selectedColumns.length === this.previewData.columns.length
    },
    likesSomeFruit () {
      return this.selectedColumns.length > 0 && !this.likesAllFruit
    },
    icon () {
      if (this.likesAllFruit) return 'mdi-close-box'
      if (this.likesSomeFruit) return 'mdi-minus-box'
      return 'mdi-checkbox-blank-outline'
    }
  },
  watch: {
    'previewData.columns' (val) {
      if (val && val.length) {
        // 只在首次加载（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)
      }
    },
    // 表头项全选/取消全选
    handleSelectAll () {
      this.$nextTick(() => {
        if (this.likesAllFruit) {
          this.selectedColumns = []
        } else {
          this.selectedColumns = this.previewData.columns.map(col => col.name)
        }
      })
    },
    handleGraphDialogVisibleChange (val) {
      this.graphDialogVisible = val
      if (!val) {
        // 关闭时清空数据
        this.graphData = null
      }
    }
  }
}
</script>
