<template>
  <!-- 导入表 -->
  <el-dialog title="导入表" v-model="visible" width="800px" top="5vh" append-to-body>
    <basic-table
      ref="tableRef"
      :columns="columns"
      :search-columns="searchColumns"
      :query="queryList"
      row-key="tableName"
      size="small"
      height="260px"
      :show-toolbar="false"
      :auto-load="false"
      @row-click="clickRow"
      @selection-change="handleSelectionChange"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleImportTable">确 定</el-button>
        <el-button @click="visible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { listDbTable, importTable } from "@/api/tool/gen"

const tableRef = ref()
const visible = ref(false)
const tables = ref([])
const { proxy } = getCurrentInstance()

// 搜索项配置
const searchColumns = [
  { label: "表名称", prop: "tableName", component: "input", placeholder: "请输入表名称", width: "200px" },
  { label: "表描述", prop: "tableComment", component: "input", placeholder: "请输入表描述", width: "200px" }
]

// 表格列配置
const columns = [
  { label: "表名称", prop: "tableName", align: "center" },
  { label: "表描述", prop: "tableComment", align: "center" },
  { label: "创建时间", prop: "createTime", align: "center" },
  { label: "更新时间", prop: "updateTime", align: "center" }
]

// 查询函数（BasicTable 调用，返回 { rows, total }）
function queryList(params) {
  return listDbTable(params)
}

const emit = defineEmits(["ok"])

/** 显示弹框 */
function show() {
  visible.value = true
  nextTick(() => {
    tableRef.value?.reload()
  })
}

/** 单击选择行 */
function clickRow(row) {
  tableRef.value?.getTableRef()?.toggleRowSelection(row)
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  tables.value = selection.map(item => item.tableName)
}

/** 导入按钮操作 */
function handleImportTable() {
  const tableNames = tableRef.value?.getSelection().map(t => t.tableName).join(",") || ""
  if (tableNames === "") {
    proxy.$modal.msgError("请选择要导入的表")
    return
  }
  importTable({ tables: tableNames, tplWebType: 'element-plus' }).then(res => {
    proxy.$modal.msgSuccess(res.msg)
    if (res.code === 200) {
      visible.value = false
      emit("ok")
    }
  })
}

defineExpose({
  show,
})
</script>
