<template>

  <cacp-dialog
    v-model="state.visible"
    :resizable="false"
    :title="state.title"
    width="50%"
    @closed="onClose"
  >
    <cacp-search-panel-layout
      :model="state.queryData"
      ref="queryFormRef"
      label-position="left"
      label-width="auto"
      :gutter="30"
      :colSpan="6"
    >
      <el-form-item label="表名称" prop="tableName">
        <el-input
          v-model="state.queryData.tableName"
          placeholder="请输入表名称"
          clearable
          @keyup.enter="onSearch"
        />
      </el-form-item>
      <el-form-item label="表描述" prop="tableComment">
        <el-input
          v-model="state.queryData.tableComment"
          placeholder="请输入表描述"
          clearable
          @keyup.enter="onSearch"
        />
      </el-form-item>
      <template #buttonGroup>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button type="info" @click="onReset">重置</el-button>
      </template>
    </cacp-search-panel-layout>

    <div  style="max-height: 60vh; overflow-y: auto; padding-right: 10px;">
      <cacp-complex-table
        :data="tableData"
        :pagination="tablePagination"
        @selection-change="handleSelectionChange"
        @on-page-change="onPageChange"
        @on-size-change="onSizeChange"
        :loading="loading"
      >
        <el-table-column type="selection" align="center" width="55" />
        <el-table-column
          label="表名称"
          align="center"
          prop="tableName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="表描述"
          align="center"
          prop="tableComment"
          :show-overflow-tooltip="true"
          width="220"
        />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="160"
        />
        <el-table-column
          label="更新时间"
          align="center"
          prop="updateTime"
          width="160"
        />
      </cacp-complex-table>
    </div>

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

<script setup lang="ts">
import { reactive, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useComplexTable,type SearchPanelLayoutInstance, SuccessResultCode,useLoading } from '@cacp/ui'
import type { DbTableInfo, GenTable, GenTableQuery, SelectionItem } from '@/types/gen/GenTable'
import config from '@/config'
// API
import { listDbTable, importTable } from '@/apis/gen/gen'

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

// Refs
const queryFormRef = ref<SearchPanelLayoutInstance>()

// 响应式数据
interface State {
  visible: boolean
  loading: boolean
  title: string
  total: number
  selectedTables: SelectionItem[]
  dbTableList: DbTableInfo[]
  queryData: GenTableQuery & {
    pageNum: number
    pageSize: number
    tableName?: string
    tableComment?: string
  }
}

const state = reactive<State>({
  visible: false,
  loading: false,
  title: '导入表',
  total: 0,
  selectedTables: [],
  dbTableList: [],
  queryData: {
    pageNum: 1,
    pageSize: 10,
    tableName: undefined,
    tableComment: undefined
  }
})

// 表格 Hook
const tableHooks = useComplexTable<GenTable>(config)
const { tableData, tablePagination, setPagination, setPageIndex, setPageSizes } = tableHooks

// 计算属性
const tableNames = computed(() => state.selectedTables.map(item => item.tableName).join(','))

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


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

/** 查询表数据 */
const onLoadData = async () => {
  try {
    state.loading = true
    const query = {
      ...state.queryData,
      pageIndex: tablePagination.currentPage,
      pageSize: tablePagination.pageSize
    }
    const res = await listDbTable(query)
    console.log('获取数据库表列表:', res)
    if (res.code === SuccessResultCode) {
      setPagination(res.data)
    } else {
      ElMessage.error(res.message || '获取数据失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
    console.error('获取数据库表列表失败:', error)
  } finally {
    state.loading = false
  }
}

/** 搜索按钮操作 */
const onSearch = () => {
  state.queryData.pageNum = 1  // 搜索时重置到第一页
  onLoadData()
}

/** 重置按钮操作 */
const onReset = () => {
  queryFormRef.value?.resetFields()
  state.queryData.pageNum = 1  // 重置时回到第一页
  state.queryData.tableName = undefined
  state.queryData.tableComment = undefined
  onLoadData()
}

/** 导入按钮操作 */
const onImportTable = async () => {
  if (!tableNames.value) {
    ElMessage.error('请选择要导入的表')
    return
  }

  try {

    const response = await importTable(tableNames.value)
    if (response.code === SuccessResultCode) {
      ElMessage.success(response.message || '导入成功')
      state.visible = false
      emit('ok')
    } else {
      ElMessage.error(response.message || '导入失败')
    }
  } catch (error) {
    ElMessage.error('导入失败')
    console.error('导入表失败:', error)
  }
}
// 加载状态
const { loading } = useLoading()
// 翻页查询
const onPageChange = (currentPage: number) => {
  setPageIndex(currentPage)
  onLoadData()
}

// 每页显示条数变化
const onSizeChange = (size: number) => {
  setPageSizes(size)
  onLoadData()
}
/** 关闭对话框 */
const onClose = () => {
  // 重置数据
  state.selectedTables = []
  queryFormRef.value?.resetFields()
  state.queryData.pageNum = 1
  state.queryData.pageSize = 10
  state.queryData.tableName = undefined
  state.queryData.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>
