<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import { Button, Card, message, Tabs } from 'ant-design-vue';

import {
  batchDeleteTableDataApi,
  deleteTableDataApi,
  dropIndexApi,
  getTableDataApi,
  getTableInfoApi,
  getTableListApi,
  updateTableStructureApi,
} from './api';
import AddColumnModal from './components/AddColumnModal.vue';
import AddIndexModal from './components/AddIndexModal.vue';
import EditColumnCommentModal from './components/EditColumnCommentModal.vue';
import EditColumnModal from './components/EditColumnModal.vue';
import EditDataModal from './components/EditDataModal.vue';
import EditTableCommentModal from './components/EditTableCommentModal.vue';
import ChangeLog from './components/ChangeLog.vue';
import SqlQuery from './components/SqlQuery.vue';
import TableData from './components/TableData.vue';
import TableIndex from './components/TableIndex.vue';
import TableList from './components/TableList.vue';
import TableStructure from './components/TableStructure.vue';

// 表列表
const tableList = ref<any[]>([]);
const tableLoading = ref(false);
const searchKeyword = ref('');
const selectedTable = ref<string>('');

// 主页标签页 (列表/SQL)
const activeMainTab = ref('list');

// 表信息
const tableInfo = ref<any>(null);
const tableInfoLoading = ref(false);

// 表数据
const tableData = ref<any[]>([]);
const tableDataLoading = ref(false);
const tableDataPagination = ref({
  current: 1,
  pageSize: 20,
  total: 0,
});

// 当前标签页
const activeTab = ref('structure');

// Modal
const [EditTableCommentModalComponent, editTableCommentModalApi] = useVbenModal({
  connectedComponent: EditTableCommentModal,
});

const [EditColumnCommentModalComponent, editColumnCommentModalApi] = useVbenModal({
  connectedComponent: EditColumnCommentModal,
});

const [EditColumnModalComponent, editColumnModalApi] = useVbenModal({
  connectedComponent: EditColumnModal,
});

const [AddColumnModalComponent, addColumnModalApi] = useVbenModal({
  connectedComponent: AddColumnModal,
});

const [EditDataModalComponent, editDataModalApi] = useVbenModal({
  connectedComponent: EditDataModal,
});

const [AddIndexModalComponent, addIndexModalApi] = useVbenModal({
  connectedComponent: AddIndexModal,
});

// 过滤后的表列表
const filteredTableList = computed(() => {
  if (!searchKeyword.value) {
    return tableList.value;
  }
  return tableList.value.filter(
    (table) =>
      table.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      (table.comment && table.comment.toLowerCase().includes(searchKeyword.value.toLowerCase())),
  );
});

// 加载表列表
const loadTableList = async () => {
  tableLoading.value = true;
  try {
    const res = await getTableListApi();
    tableList.value = res || [];
  } catch (error: any) {
    message.error(error.message || '加载表列表失败');
    tableList.value = [];
  } finally {
    tableLoading.value = false;
  }
};

// 选择表
const handleSelectTable = async (tableName: string) => {
  if (!tableName) {
    selectedTable.value = '';
    tableInfo.value = null;
    tableData.value = [];
    return;
  }

  selectedTable.value = tableName;
  activeTab.value = 'structure';
  await loadTableInfo();
};

// 返回列表
const handleBack = () => {
  selectedTable.value = '';
};

// 加载表信息
const loadTableInfo = async () => {
  if (!selectedTable.value) return;

  tableInfoLoading.value = true;
  try {
    const res = await getTableInfoApi(selectedTable.value);
    tableInfo.value = res;
  } catch (error: any) {
    message.error(error.message || '加载表信息失败');
    tableInfo.value = null;
  } finally {
    tableInfoLoading.value = false;
  }
};

// 搜索条件
const searchConditions = ref<any[]>([]);

// 加载表数据
const loadTableData = async (page = 1, pageSize = 20, where: any[] = []) => {
  if (!selectedTable.value) return;

  tableDataLoading.value = true;
  try {
    const res = await getTableDataApi({
      table_name: selectedTable.value,
      page,
      page_size: pageSize,
      where: where.length > 0 ? where : searchConditions.value,
    });
    tableData.value = res.items || [];
    tableDataPagination.value = {
      current: res.page || 1,
      pageSize: res.size || 20,
      total: res.total || 0,
    };
  } catch (error: any) {
    message.error(error.message || '加载表数据失败');
    tableData.value = [];
  } finally {
    tableDataLoading.value = false;
  }
};

// 处理搜索
const handleSearch = (conditions: any[]) => {
  searchConditions.value = conditions;
  loadTableData(1, tableDataPagination.value.pageSize, conditions);
};

// 切换标签页
const handleTabChange = (key: string) => {
  if (key === 'data' && tableData.value.length === 0) {
    loadTableData();
  }
};

// 编辑表注释
const handleEditTableComment = () => {
  if (!tableInfo.value) return;
  editTableCommentModalApi.setData({
    tableName: selectedTable.value,
    comment: tableInfo.value.comment || '',
    reload: loadTableInfo,
  }).open();
};

// 编辑字段
const handleEditColumn = (column: any) => {
  editColumnModalApi.setData({
    tableName: selectedTable.value,
    column,
    columns: tableInfo.value?.columns || [],
    reload: loadTableInfo,
  }).open();
};

// 编辑字段注释
const handleEditColumnComment = (column: any) => {
  editColumnCommentModalApi.setData({
    tableName: selectedTable.value,
    column,
    reload: loadTableInfo,
  }).open();
};

// 添加字段
const handleAddColumn = () => {
  addColumnModalApi.setData({
    tableName: selectedTable.value,
    columns: tableInfo.value?.columns || [],
    reload: loadTableInfo,
  }).open();
};

// 删除字段
const handleDeleteColumn = async (column: any) => {
  try {
    await updateTableStructureApi({
      table_name: selectedTable.value,
      action: 'drop',
      column_info: {
        name: column.name,
      },
    });
    message.success('删除成功');
    await loadTableInfo();
  } catch (error: any) {
    message.error(error.message || '删除失败');
  }
};

// 添加数据
const handleAddData = () => {
  editDataModalApi.setData({
    tableName: selectedTable.value,
    columns: tableInfo.value?.columns || [],
    values: {},
    update: false,
    reload: () => loadTableData(tableDataPagination.value.current, tableDataPagination.value.pageSize),
  }).open();
};

// 编辑数据
const handleEditData = (record: any) => {
  editDataModalApi.setData({
    tableName: selectedTable.value,
    columns: tableInfo.value?.columns || [],
    values: record,
    update: true,
    reload: () => loadTableData(tableDataPagination.value.current, tableDataPagination.value.pageSize),
  }).open();
};

// 删除数据
const handleDeleteData = async (record: any) => {
  try {
    const firstKey = Object.keys(record)[0];
    await deleteTableDataApi({
      table_name: selectedTable.value,
      where: [
        {
          field: firstKey,
          operator: '=',
          value: record[firstKey],
        },
      ],
    });
    message.success('删除成功');
    await loadTableData(tableDataPagination.value.current, tableDataPagination.value.pageSize);
  } catch (error: any) {
    message.error(error.message || '删除失败');
  }
};

// 批量删除数据
const handleBatchDeleteData = async (records: any[]) => {
  try {
    // 构建批量删除的WHERE条件
    const whereConditions = records.map((record) => {
      const firstKey = Object.keys(record)[0];
      return {
        field: firstKey,
        operator: '=',
        value: record[firstKey],
      };
    });

    // 使用OR连接多个条件
    await batchDeleteTableDataApi({
      table_name: selectedTable.value,
      where: whereConditions,
    });
    message.success(`成功删除 ${records.length} 条数据`);
    await loadTableData(tableDataPagination.value.current, tableDataPagination.value.pageSize);
  } catch (error: any) {
    message.error(error.message || '批量删除失败');
  }
};

// 添加索引
const handleAddIndex = () => {
  addIndexModalApi.setData({
    tableName: selectedTable.value,
    columns: tableInfo.value?.columns || [],
    reload: loadTableInfo,
  }).open();
};

// 删除索引
const handleDeleteIndex = async (indexName: string) => {
  try {
    await dropIndexApi({
      table_name: selectedTable.value,
      index_name: indexName,
    });
    message.success('删除成功');
    await loadTableInfo();
  } catch (error: any) {
    message.error(error.message || '删除失败');
  }
};

onMounted(() => {
  loadTableList();
});
</script>

<template>
  <Page auto-content-height title="数据库管理">
    <div class="database-management">

      <!-- 列表页 / 主页 -->
      <div v-show="!selectedTable" class="h-full bg-white dark:bg-gray-900 rounded-lg p-2">
        <!-- 增加 Tabs 切换：数据表列表 / 全局 SQL 查询 -->
        <Tabs v-model:activeKey="activeMainTab" class="h-full flex flex-col [&>.ant-tabs-content]:flex-1 [&>.ant-tabs-content]:overflow-auto">
          <Tabs.TabPane key="list" tab="数据表列表">
            <TableList
              :table-list="filteredTableList"
              :loading="tableLoading"
              :selected-table="selectedTable"
              :search-keyword="searchKeyword"
              @update:search-keyword="searchKeyword = $event"
              @select-table="handleSelectTable"
            />
          </Tabs.TabPane>
          <Tabs.TabPane key="sql" tab="全局 SQL 查询">
            <!-- 主页面的 SQL 查询组件，传入表列表 -->
            <div class="h-full p-2">
              <SqlQuery :table-list="tableList" />
            </div>
          </Tabs.TabPane>
        </Tabs>
      </div>

      <!-- 详情页：选择表后显示 -->
      <div v-if="selectedTable" class="h-full">
        <Card class="h-full flex flex-col" :body-style="{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }">
          <template #title>
            <div class="flex items-center gap-2">
              <Button type="link" size="small" @click="handleBack" class="!px-0 !mr-2 text-gray-600 hover:text-primary">
                <i class="fa-solid fa-arrow-left mr-1"></i>
                返回
              </Button>
              <span class="font-bold text-lg">{{ selectedTable }}</span>
            </div>
          </template>

          <div class="flex-1 overflow-hidden flex flex-col">
            <Tabs v-model:activeKey="activeTab" @change="handleTabChange" class="h-full flex flex-col [&>.ant-tabs-content]:flex-1 [&>.ant-tabs-content]:overflow-auto">
              <!-- 表结构 -->
              <Tabs.TabPane key="structure" tab="表结构">
                <TableStructure
                  :table-info="tableInfo"
                  :loading="tableInfoLoading"
                  @edit-table-comment="handleEditTableComment"
                  @edit-column-comment="handleEditColumnComment"
                  @edit-column="handleEditColumn"
                  @add-column="handleAddColumn"
                  @delete-column="handleDeleteColumn"
                />
              </Tabs.TabPane>

              <!-- 表数据 -->
              <Tabs.TabPane key="data" tab="表数据">
                <TableData
                  :table-info="tableInfo"
                  :table-data="tableData"
                  :loading="tableDataLoading"
                  :pagination="tableDataPagination"
                  @add-data="handleAddData"
                  @edit-data="handleEditData"
                  @delete-data="handleDeleteData"
                  @batch-delete="handleBatchDeleteData"
                  @search="handleSearch"
                  @page-change="loadTableData"
                />
              </Tabs.TabPane>

              <!-- 索引管理 -->
              <Tabs.TabPane key="index" tab="索引管理">
                <TableIndex
                  :table-info="tableInfo"
                  @add-index="handleAddIndex"
                  @delete-index="handleDeleteIndex"
                />
              </Tabs.TabPane>

              <!-- SQL查询 -->
              <Tabs.TabPane key="sql" tab="SQL查询">
                <!-- 详情页 SQL 组件，同时传入 tableName 和 tableList -->
                <SqlQuery :table-name="selectedTable" :table-list="tableList" />
              </Tabs.TabPane>

              <!-- 变更记录 -->
              <Tabs.TabPane key="changelog" tab="变更记录">
                <ChangeLog />
              </Tabs.TabPane>
            </Tabs>
          </div>
        </Card>
      </div>
    </div>

    <!-- Modals -->
    <EditTableCommentModalComponent />
    <EditColumnCommentModalComponent />
    <EditColumnModalComponent />
    <AddColumnModalComponent />
    <EditDataModalComponent />
    <AddIndexModalComponent />
  </Page>
</template>

<style scoped>
.database-management {
  min-height: calc(100vh - 200px);
}
/* 确保 Tabs 内容区域能撑满剩余高度，防止滚动条问题 */
:deep(.ant-tabs) {
  display: flex;
  flex-direction: column;
  height: 100%;
}
:deep(.ant-tabs-content) {
  flex: 1;
  height: 100%;
  overflow-y: auto;
}
</style>
