<template>
  <!-- 导入表 -->
  <el-dialog
    :title="title"
    v-model="visible"
    width="800px"
    top="5vh"
    append-to-body
    @close="handleClose"
  >
    <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true">
      <el-form-item label="表名称" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入表名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表描述" prop="tableComment">
        <el-input
          v-model="queryParams.tableComment"
          placeholder="请输入表描述"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" size="small" @click="handleQuery">
          搜索
        </el-button>
        <el-button :icon="Refresh" size="small" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row>
      <el-table
        @row-click="clickRow"
        ref="tableRef"
        :data="dbTableList"
        @selection-change="handleSelectionChange"
        height="260px"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="tableName" label="表名称" :show-overflow-tooltip="true" />
        <el-table-column prop="tableComment" label="表描述" :show-overflow-tooltip="true" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handlePaginationChange"
      />
    </el-row>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleImportTable">确 定</el-button>
        <el-button @click="visible = false">取 消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'

// API
import { listDbTable, importTable, type DbTableInfo, type GenTableQuery } from '@/apis/gen/gen'
import Pagination from '@/components/Pagination/index.vue'

// 类型定义
interface SelectionItem {
  tableName: string
  tableComment: string
  createTime: string
  updateTime: string
}

// Emits
const emit = defineEmits<{
  ok: []
}>()

// Refs
const queryFormRef = ref<FormInstance>()
const tableRef = ref<InstanceType<typeof ElTable>>()

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const title = ref('导入表')
const total = ref(0)
const selectedTables = ref<SelectionItem[]>([])
const dbTableList = ref<DbTableInfo[]>([])

const queryParams = reactive<GenTableQuery>({
  pageNum: 1,
  pageSize: 10,
  tableName: undefined,
  tableComment: undefined
})

// 方法
/** 显示弹框 */
const show = () => {
  visible.value = true
  getList()
}

/** 点击行 */
const clickRow = (row: SelectionItem) => {
  if (tableRef.value) {
    tableRef.value.toggleRowSelection(row)
  }
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: SelectionItem[]) => {
  selectedTables.value = selection
}

/** 查询表数据 */
const getList = async () => {
  try {
    loading.value = true
    const response = await listDbTable(queryParams)
    console.log('获取数据库表列表:', response)
    if (response.code === 200) {
      dbTableList.value = response.rows
      total.value = response.total
    } else {
      ElMessage.error(response.msg || '获取数据失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
    console.error('获取数据库表列表失败:', error)
  } finally {
    loading.value = false
  }
}

/** 分页事件处理 */
const handlePaginationChange = (pagination: any) => {
  console.log('分页变化:', pagination)
  // 更新分页参数
  queryParams.pageNum = pagination.page
  queryParams.pageSize = pagination.limit
  // 重新获取数据
  getList()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1  // 搜索时重置到第一页
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields()
  }
  queryParams.pageNum = 1  // 重置时回到第一页
  queryParams.tableName = undefined
  queryParams.tableComment = undefined
  getList()
}

/** 导入按钮操作 */
const handleImportTable = async () => {
  const tableNames = selectedTables.value.map(item => item.tableName).join(',')

  if (!tableNames) {
    ElMessage.error('请选择要导入的表')
    return
  }

  try {
    const response = await importTable({ tables: tableNames })
    if (response.code === 200) {
      ElMessage.success(response.msg || '导入成功')
      visible.value = false
      emit('ok')
    } else {
      ElMessage.error(response.msg || '导入失败')
    }
  } catch (error) {
    ElMessage.error('导入失败')
    console.error('导入表失败:', error)
  }
}

/** 关闭对话框 */
const handleClose = () => {
  // 重置数据
  selectedTables.value = []
  if (queryFormRef.value) {
    queryFormRef.value.resetFields()
  }
  queryParams.pageNum = 1
  queryParams.pageSize = 10
  queryParams.tableName = undefined
  queryParams.tableComment = undefined
}

// 暴露方法给父组件
defineExpose({
  show
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table) {
  margin-bottom: 16px;
}

:deep(.el-table .el-table__body tr:hover > td) {
  background-color: #f5f7fa;
  cursor: pointer;
}
</style>
