<template>
  <div class="page">
    <div class="apihub-container">
      <!-- 左侧分组树 -->
      <div class="apihub-sidebar">
        <el-card shadow="never" class="group-card">
          <template #header>
            <div class="card-header">
              <span>API分组</span>
              <div class="header-actions">
                <el-button type="primary" size="small" @click="addGroup" v-auth="'add'">
                  <el-icon><ele-Plus /></el-icon>
                </el-button>
                <el-button type="primary" size="small" @click="refreshGroups">
                  <el-icon><ele-Refresh /></el-icon>
                </el-button>
              </div>
            </div>
          </template>
          <div class="group-search">
            <el-input v-model="groupSearchKey" placeholder="搜索分组" clearable prefix-icon="ele-Search" @input="filterGroups" />
          </div>
          <div class="group-tree-container">
            <el-tree ref="groupTreeRef" :data="groupTreeData" :props="{ label: 'Name', children: 'Children' }" node-key="Id" highlight-current :expand-on-click-node="true" default-expand-all @node-click="handleGroupClick">
              <template #default="{ node, data }">
                <div class="custom-tree-node">
                  <span>{{ node.label }}</span>
                  <span class="api-count" v-if="data.ApiCount">{{ data.ApiCount }}</span>
                  <div class="node-actions">
                    <el-dropdown @command="(command: string) => handleGroupCommand(command, data)" trigger="click">
                      <el-icon><ele-More /></el-icon>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="edit" v-auth="'edit'">编辑</el-dropdown-item>
                          <el-dropdown-item command="add_child" v-auth="'add'">添加子分组</el-dropdown-item>
                          <el-dropdown-item command="delete" v-auth="'del'">删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
              </template>
            </el-tree>
          </div>
        </el-card>
      </div>

      <!-- 右侧API列表 -->
      <el-card shadow="never" class="apihub-content">
        <div class="api-header">
          <div class="current-group" v-if="currentGroup.Name">
            当前分组: <span class="group-name">{{ currentGroup.Name }}</span>
            <el-link type="primary" class="view-all-link" @click="viewAllData">查看全部API</el-link>
          </div>
          <div class="current-group" v-else>全部API</div>
        </div>
        <el-form :model="params" inline ref="queryRef">
          <el-form-item label="关键字" prop="keyWord">
            <el-input v-model="params.keyWord" placeholder="输入名称、路径或描述" clearable style="width: 170px" @keyup.enter.native="getList(1)" />
          </el-form-item>
          <el-form-item label="数据源" prop="dataSourceKey">
            <el-select v-model="params.dataSourceKey" placeholder="请选择数据源" clearable style="width: 170px">
              <el-option v-for="item in dataSources" :key="item.dsKey" :label="item.name" :value="item.dsKey" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="params.status" placeholder="请选择状态" clearable style="width: 90px">
              <el-option label="全部" value="" />
              <el-option label="草稿" value="Draft" />
              <el-option label="已发布" value="Published" />
              <el-option label="已废弃" value="Deprecated" />
            </el-select>
          </el-form-item>
<!--          <el-form-item label="日期范围" prop="dateRange">-->
<!--            <el-date-picker v-model="params.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 240px" />-->
<!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" class="ml10" @click="getList(1)">
              <el-icon>
                <ele-Search />
              </el-icon>
              查询
            </el-button>
<!--            <el-button @click="resetQuery()">-->
<!--              <el-icon>-->
<!--                <ele-Refresh />-->
<!--              </el-icon>-->
<!--              重置-->
<!--            </el-button>-->
            <el-button type="primary" @click="addOrEdit()" v-auth="'add'">
              <el-icon>
                <ele-FolderAdd />
              </el-icon>
              新增API
            </el-button>
          </el-form-item>
        </el-form>
        <el-table :data="tableData" style="width: 100%" v-loading="loading" row-key="id">
          <el-table-column type="selection" width="40" align="center" />
<!--          <el-table-column prop="id" label="ID" width="80" align="center" />-->
          <el-table-column prop="method" v-col="'method'" label="请求" width="85" align="center">
            <template #default="scope">
              <el-tag :type="getMethodTagType(scope.row.method)" size="small">
                {{ scope.row.method }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="name" v-col="'name'" label="API名称" min-width="140" show-overflow-tooltip></el-table-column>
          <el-table-column prop="path" v-col="'path'" label="API路径" min-width="150" show-overflow-tooltip></el-table-column>
<!--          <el-table-column prop="dataSourceName" label="数据源" width="120" show-overflow-tooltip></el-table-column>-->
<!--          <el-table-column prop="sqlType" label="SQL类型" width="100" align="center">-->
<!--            <template #default="scope">-->
<!--              <el-tag size="small" type="info" v-if="scope.row.sqlType === 'query'">查询</el-tag>-->
<!--              <el-tag size="small" type="warning" v-else-if="scope.row.sqlType === 'procedure'">存储过程</el-tag>-->
<!--              <span v-else>{{ scope.row.sqlType }}</span>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column prop="version" label="版本" width="80" align="center"></el-table-column>-->
          <el-table-column prop="description" v-col="'description'" label="描述" width="140" show-overflow-tooltip/>

          <el-table-column prop="status" v-col="'status'" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag size="small" v-if="scope.row.status === 'Draft'">草稿</el-tag>
              <el-tag size="small" type="success" v-else-if="scope.row.status === 'Published'">已发布</el-tag>
              <el-tag size="small" type="info" v-else-if="scope.row.status === 'Deprecated'">已废弃</el-tag>
              <span v-else>{{ scope.row.status }}</span>
            </template>
          </el-table-column>
<!--          <el-table-column prop="createdAt" label="创建时间" width="160" align="center"></el-table-column>-->
          <el-table-column label="操作" width="190" align="center" fixed="right" v-col="'handle'">
            <template #default="scope">
              <div class="flex-row">
                <el-button size="small" text type="primary" @click="viewDetail(scope.row)" v-auth="'detail'">查看</el-button>
                <el-button size="small" text type="warning" @click="addOrEdit(scope.row)" v-auth="'edit'">编辑</el-button>
                <el-button size="small" text type="success" @click="testApi(scope.row)" v-auth="'test'">测试</el-button>
                <el-dropdown @command="(command: string) => handleCommand(command, scope.row)" v-auth="'more'">
                  <el-button size="small" text type="primary" style="margin-left: 12px; vertical-align: top">
                    更多<el-icon class="el-icon--right" style="font-size: 12px !important"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="publish" v-if="scope.row.status === 'Draft'" v-auth="'publish'">发布</el-dropdown-item>
                      <el-dropdown-item command="deprecate" v-if="scope.row.status === 'Published'" v-auth="'deprecate'">废弃</el-dropdown-item>
                      <el-dropdown-item command="delete" v-auth="'del'">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-if="params.total" :total="params.total" v-model:page="params.pageNum" v-model:limit="params.pageSize" @pagination="getList()" />
      </el-card>
    </div>

    <!-- 组件 -->
    <EditForm ref="editFormRef" @getList="getList(1)"></EditForm>
    <ViewDetail ref="viewDetailRef"></ViewDetail>
    <TestApi ref="testApiRef"></TestApi>
    <GroupForm ref="groupFormRef" @refresh="refreshGroups"></GroupForm>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import EditForm from "./component/edit.vue";
import ViewDetail from "./component/view.vue";
import TestApi from "./component/test.vue";
import GroupForm from "./component/group.vue";
import { useSearch } from "/@/hooks/useCommon";
import { ElMessageBox, ElMessage } from "element-plus";
import { ArrowDown } from "@element-plus/icons-vue";
import api from "/@/api/modules/apiHub";

// 定义API接口类型
interface ApiDefinition {
  id?: number;
  name: string;
  path: string;
  method: string;
  dataSourceKey: string;
  dataSourceName?: string;
  sqlType: string;
  sqlContent: string;
  parameters?: any[];
  returnFormat: string;
  version: string;
  status: string;
  private: string;
  plugins?: any[];
  description?: string;
  createdAt?: string;
  updatedAt?: string;
}

// 引用组件
const editFormRef = ref();
const viewDetailRef = ref();
const testApiRef = ref();
const queryRef = ref();
const groupFormRef = ref();
const groupTreeRef = ref();

// 分组相关状态
const groupSearchKey = ref("");
const groupTreeData = ref<any[]>([]);
const currentGroup = reactive<any>({
  Id: undefined,
  GroupKey: "",
  Name: "",
  ParentId: 0,
  Description: "",
});
const originalGroupTree = ref<any[]>([]);

// 数据源列表
const dataSources = ref<any[]>([]);

// 使用通用搜索钩子
const { params, tableData, getList, loading } = useSearch<ApiDefinition[]>(api.list, "Data", {
  keyWord: "",
  dataSourceKey: "",
  status: "",
  private: "-1",
  dateRange: [],
  orderBy: "",
});

// 加载数据源列表
const loadDataSources = () => {
  api.dataSource.list().then((res: any) => {
    dataSources.value = res.list;
  });
};

// 页面加载时获取列表数据
onMounted(() => {
  // 获取API列表
  getList(1);

  // 加载数据源列表
  loadDataSources();

  // 加载分组树
  refreshGroups();
});

// 将扁平数组转换为树形结构
const convertToTree = (flatData: any[]) => {
  // 创建一个映射表，用于快速查找节点
  const map: any = {};
  const result: any[] = [];

  // 首先创建所有节点的映射
  flatData.forEach((item) => {
    // 确保每个节点都有Children属性
    map[item.Id] = { ...item, Children: [] };
  });

  // 然后建立父子关系
  flatData.forEach((item) => {
    const node = map[item.Id];

    if (item.ParentId === 0 || !map[item.ParentId]) {
      // 如果ParentId为0或者父节点不存在，则为顶级节点
      result.push(node);
    } else {
      // 否则将该节点添加到父节点的Children中
      map[item.ParentId].Children.push(node);
    }
  });

  // 清理空的Children数组
  flatData.forEach((item) => {
    if (map[item.Id].Children.length === 0) {
      map[item.Id].Children = null;
    }
  });

  return result;
};

// 检查数据是否已经是树形结构
const isTreeStructure = (data: any[]) => {
  // 检查数据中是否有包含非空的Children字段的项
  return data.some((item) => item.Children && Array.isArray(item.Children) && item.Children.length > 0);
};

// 刷新分组树
const refreshGroups = async () => {
  try {
    // 调用API获取分组树
    const res: any = await api.group.tree();

    // 使用API返回的数据
    if (res?.list) {
      // 获取原始数据
      const apiData = res.list || [];

      // 检查数据是否已经是树形结构
      const hasTreeStructure = isTreeStructure(apiData);

      let treeData: any[];
      if (hasTreeStructure) {
        // 如果已经是树形结构，直接使用
        treeData = apiData;
      } else {
        // 如果是扁平结构，通过ParentId构建树形结构
        treeData = convertToTree(apiData);
      }

      // 设置到组件中
      groupTreeData.value = treeData;
      originalGroupTree.value = JSON.parse(JSON.stringify(treeData));
      return;
    }

    // 如果没有数据，初始化为空数组
    groupTreeData.value = [];
    originalGroupTree.value = [];
  } catch (error) {
    ElMessage.error("获取分组数据失败");
  }
};

// 搜索过滤分组
const filterGroups = () => {
  if (!groupSearchKey.value) {
    // 如果搜索关键字为空，恢复原始数据
    groupTreeData.value = JSON.parse(JSON.stringify(originalGroupTree.value));
    return;
  }

  // 递归搜索函数
  const searchTree = (nodes: any[]) => {
    return nodes.filter((node) => {
      // 当前节点名称匹配
      const matchesName = node.Name.toLowerCase().includes(groupSearchKey.value.toLowerCase());

      // 递归搜索子节点
      if (node.Children && node.Children.length) {
        node.Children = searchTree(node.Children);
        // 如果子节点有匹配项，则保留父节点
        return matchesName || node.Children.length > 0;
      }

      return matchesName;
    });
  };

  groupTreeData.value = searchTree(JSON.parse(JSON.stringify(originalGroupTree.value)));
};

// 点击分组节点
const handleGroupClick = (data: any) => {
  console.log(data);
  // 设置当前选中分组
  Object.assign(currentGroup, data);

  // 更新查询参数，加入分组条件
  params.groupKey = data.GroupKey;

  // 重新获取列表
  getList(1);
};

// 添加分组
const addGroup = () => {
  groupFormRef.value.open();
};

// 处理分组操作
const handleGroupCommand = (command: string, data: any) => {
  switch (command) {
    case "edit":
      groupFormRef.value.open(data);
      break;
    case "add_child":
      groupFormRef.value.open(null, data.GroupKey);
      break;
    case "delete":
      deleteGroupConfirm(data);
      break;
  }
};

// 删除分组确认
const deleteGroupConfirm = (data: any) => {
  ElMessageBox.confirm(`确定要删除分组「${data.Name}」吗？如果包含子分组或API，将一并删除。`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        // 实际使用时调用API
        await api.group.delete([data.Id]);
        ElMessage.success("删除成功");

        // 如果当前选中的是要删除的分组，则清空当前分组
        if (currentGroup.GroupKey === data.GroupKey) {
          Object.assign(currentGroup, {
            Id: undefined,
            GroupKey: "",
            Name: "",
            ParentId: 0,
            Description: "",
          });
          params.groupKey = "";
          getList(1);
        }

        // 刷新分组树
        refreshGroups();
      } catch (error) {
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {});
};

// 根据请求方法返回不同的标签类型
const getMethodTagType = (method: string) => {
  switch (method.toUpperCase()) {
    case "GET":
      return "success";
    case "POST":
      return "primary";
    case "PUT":
      return "warning";
    case "DELETE":
      return "danger";
    default:
      return "info";
  }
};

// 重置查询表单
const resetQuery = () => {
  queryRef.value.resetFields();
  getList(1);
};

// 查看全部数据
const viewAllData = () => {
  // 清空当前分组条件
  params.groupKey = "";
  // 清空当前分组信息
  Object.assign(currentGroup, {
    Id: undefined,
    GroupKey: "",
    Name: "",
    ParentId: 0,
    Description: "",
  });
  // 保留其他查询条件
  getList(1);
};

// 新增或编辑API
const addOrEdit = (row?: ApiDefinition) => {
  if (row) {
    // 编辑现有API
    // 实际使用时，可能需要先获取详情
    editFormRef.value.open(row);
  } else {
    // 新增API，如果有选中分组，则传递分组标识
    editFormRef.value.open(null, currentGroup.GroupKey);
  }
};

// 查看API详情
const viewDetail = (row: ApiDefinition) => {
  viewDetailRef.value.open(row);
};

// 测试API
const testApi = (row: ApiDefinition) => {
  testApiRef.value.open(row);
};

// 处理下拉菜单命令
const handleCommand = (command: string, row: ApiDefinition) => {
  switch (command) {
    case "publish":
      publishApi(row);
      break;
    case "deprecate":
      deprecateApi(row);
      break;
    case "delete":
      deleteApi(row);
      break;
  }
};

// 发布API
const publishApi = (row: ApiDefinition) => {
  ElMessageBox.confirm(`确定要发布API「${row.name}」吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await api.publish(row.id!);
    ElMessage.success("发布成功");
    getList();
  });
};

// 废弃API
const deprecateApi = (row: ApiDefinition) => {
  ElMessageBox.confirm(`确定要废弃API「${row.name}」吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await api.deprecate(row.id!);
    ElMessage.success("废弃成功");
    getList();
  });
};

// 删除API
const deleteApi = (row: ApiDefinition) => {
  ElMessageBox.confirm(`确定要删除API「${row.name}」吗？此操作不可恢复！`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "error",
  }).then(async () => {
    await api.delete([row.id!]);
    ElMessage.success("删除成功");
    getList();
  });
};
</script>

<style scoped>
.ml10 {
  margin-left: 10px;
}

.apihub-container {
  display: flex;
  height: 100%;
  align-items: stretch;
}

.apihub-sidebar {
  width: 280px;
  min-width: 280px;
  margin-right: 16px;
  overflow-y: auto;
  height: 100%;
}

.apihub-content {
  flex: 1;
  overflow-y: auto;
  height: 100%;
  min-width: 0; /* 关键：防止flex子项内容溢出 */
  width: 0; /* 确保内容区域能够收缩 */
}

.group-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.group-search {
  margin-bottom: 12px;
}

.group-tree-container {
  overflow-y: auto;
  flex: 1;
  min-height: 200px;
  /* 确保容器有最小高度 */
  border: 1px solid #ebeef5;
  /* 添加边框以便于调试 */
  padding: 10px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.api-count {
  padding: 0 6px;
  background-color: #f0f0f0;
  border-radius: 10px;
  font-size: 12px;
  color: #606266;
}

.node-actions {
  margin-left: 8px;
  visibility: hidden;
}

.custom-tree-node:hover .node-actions {
  visibility: visible;
}

.api-header {
  margin-bottom: 16px;
  font-size: 16px;
}

.group-name {
  font-weight: bold;
  color: #409eff;
}

.view-all-link {
  margin-left: 10px;
  font-size: 14px;
}
</style>
