<template>
  <el-dialog title="数据表配置" :visible.sync="visible" width="700px" append-to-body @close="handleClose">
    <el-transfer
      v-model="selectedTables"
      :data="allTables"
      :titles="['可用数据表', '已选数据表']"
      :props="{ key: 'tableId', label: 'tableName' }"
      filterable
      filter-placeholder="请输入数据表名称"
    ></el-transfer>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" :loading="saving">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listTable } from '@/api/tool/gen'
import { listProjectTables, addProjectTable, delProjectTable } from '@/api/generator/project'

export default {
  name: 'ProjectTableConfig',
  data() {
    return {
      visible: false,
      saving: false,
      projectId: null,
      allTables: [], // All available tables { tableId, tableName, ... }
      selectedTables: [], // Array of tableId for selected tables in the transfer component
      projectTableRelations: [] // Stores original project-table relations { id, projectId, tableId }
    }
  },
  methods: {
    async init(projectId) {
      this.projectId = projectId
      this.visible = true
      this.selectedTables = []
      this.allTables = []
      this.projectTableRelations = []
      await this.loadAllTables()
      await this.loadProjectTables()
    },
    async loadAllTables() {
      // Placeholder: In a real scenario, you might fetch all tables from the database
      // or tables available for generation that are not yet part of any project.
      // For now, using a mock or assuming listTable fetches relevant tables.
      this.loadingAll = true
      try {
        // Assuming tables are not excessively numerous, otherwise pagination/search would be needed
        const response = await listTable({ pageNum: 1, pageSize: 1000 }) // Adjust params as needed
        this.allTables = response.rows.map(table => ({
          tableId: table.tableId, // Ensure your API returns tableId
          tableName: table.tableName // Ensure your API returns tableName
          // disabled: table.status === '1' // Example: disable selection if table is in a certain state
        }))
      } catch (error) {
        this.$modal.msgError('加载可用数据表列表失败')
        console.error('Error loading all tables:', error)
      } finally {
        this.loadingAll = false
      }
    },
    async loadProjectTables() {
      if (!this.projectId) return
      this.loadingProjectTables = true
      try {
        // Fetches tables already associated with this project
        const response = await listProjectTables(this.projectId, { pageNum: 1, pageSize: 1000 })
        this.projectTableRelations = response.rows // Store the full relation objects
        this.selectedTables = response.rows.map(pt => pt.tableId) // Populate transfer with tableIds
      } catch (error) {
        this.$modal.msgError('加载项目已选数据表失败')
        console.error('Error loading project tables:', error)
      } finally {
        this.loadingProjectTables = false
      }
    },
    async submitForm() {
      if (!this.projectId) {
        this.$modal.msgError('项目ID丢失，无法保存')
        return
      }

      this.saving = true
      try {
        const initialSelectedTableIds = this.projectTableRelations.map(r => r.tableId)

        // Tables to add: present in selectedTables but not in initialSelectedTableIds
        const tablesToAdd = this.selectedTables.filter(tableId =>
          !initialSelectedTableIds.includes(tableId)
        )

        // Relation IDs to delete: present in projectTableRelations but their tableId is NOT in selectedTables
        const relationIdsToDelete = this.projectTableRelations
          .filter(relation => !this.selectedTables.includes(relation.tableId))
          .map(relation => relation.id) // Corrected: PK is 'id', not 'projectTableId'

        if (relationIdsToDelete.length > 0) {
          // Assuming delProjectTable can handle an array or comma-separated string of IDs
          await delProjectTable(relationIdsToDelete.join(','))
        }

        const addPromises = tablesToAdd.map(tableId => {
          return addProjectTable({ projectId: this.projectId, tableId: tableId })
        })

        await Promise.all(addPromises)

        this.$modal.msgSuccess('数据表配置保存成功')
        this.visible = false
        this.$emit('ok') // Notify parent to refresh or take action
      } catch (error) {
        console.error('Error saving project tables:', error)
        this.$modal.msgError('数据表配置保存失败: ' + (error.message || '请查看控制台'))
      } finally {
        this.saving = false
      }
    },
    cancel() {
      this.visible = false
      this.handleClose()
    },
    handleClose() {
      // Reset data when dialog is closed
      this.visible = false
      this.projectId = null
      this.allTables = []
      this.selectedTables = []
      this.projectTableRelations = []
      this.saving = false
    }
  }
}
</script>

<style scoped>
.el-transfer {
  display: flex;
  justify-content: center; /* Center the transfer component */
  align-items: center;
}
/* Ensure transfer panels have enough width */
::v-deep .el-transfer-panel {
  width: 250px; /* Adjust as needed */
}
</style> 