EmbeddingsList.vue 8.6 KB
<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection" @change="handleTableChange">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" v-auth="'embeddings:embeddings:add'" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
        <!--<a-button type="primary" v-auth="'embeddings:embeddings:exportXls'" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>-->
        <j-upload-button type="primary" v-auth="'embeddings:embeddings:importWord'" preIcon="ant-design:import-outlined" @click="onImportXls"
          >导入</j-upload-button
        >
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined" />
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button v-auth="'embeddings:embeddings:deleteBatch'"
            >批量操作
            <Icon icon="mdi:chevron-down" />
          </a-button>
        </a-dropdown>
        <!-- 高级查询 -->
<!--        <super-query :config="superQueryConfig" @search="handleSuperQuery" />-->
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
      <!--字段回显插槽-->
      <template #bodyCell="{ column, record, index, text }"> </template>
    </BasicTable>
    <!-- 表单区域 -->
    <TestModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" name="test-test" setup>
  import { ref, reactive, computed, onMounted } from 'vue';
  import { BasicColumn, BasicTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import TestModal from './components/TestModal.vue';
  import { searchFormSchema, superQuerySchema } from './Test.data';
  import { list, batchDelete, getImportUrl, getExportUrl, deleteOne, listknowledge } from './Test.api';
  import { useUserStore } from '/@/store/modules/user';
  import JUploadButton from '@/components/Button/src/JUploadButton.vue';
  import { columns as defaultColumns } from './Test.data';
  const queryParam = reactive<any>({});
  const checkedKeys = ref<Array<string | number>>([]);
  const userStore = useUserStore();
  // 添加知识库名称映射
  const knowledgeMap = ref<Record<string, string>>({});

  // 加载知识库列表
  async function loadKnowledgeMap() {
    try {
      const res = await listknowledge({});
      const map: Record<string, string> = {};
      res.forEach((item) => {
        if (item.id && item.name) {
          map[item.id] = item.name;
        }
      });
      knowledgeMap.value = map;
    } catch (e) {
      console.error('加载知识库列表失败', e);
    }
  }

  onMounted(() => {
    loadKnowledgeMap();
  });

  // 创建符合 BasicColumn 类型的知识库名称列
  const knowledgeColumn: BasicColumn = {
    title: '知识库名称',
    align: 'center',
    dataIndex: 'knowledgeName',
    width: 150,
    customRender: ({ record }) => {
      try {
        const metadata = typeof record.metadata === 'string' ? JSON.parse(record.metadata) : record.metadata;

        const knowledgeId = metadata?.knowledgeId;

        if (knowledgeId && knowledgeMap.value[knowledgeId]) {
          return knowledgeMap.value[knowledgeId];
        } else if (knowledgeId) {
          return `未知知识库(${knowledgeId})`;
        } else {
          return '无知识库';
        }
      } catch (e) {
        return '元数据解析失败';
      }
    },
  };

  // 创建完整的列配置
  const tableColumns = computed<BasicColumn[]>(() => {
    // 从默认列配置中过滤掉可能存在的旧知识库列
    const filteredColumns = defaultColumns.filter((col) => col.dataIndex !== 'name' && col.title !== '知识库名称');

    // 添加新的知识库列
    return [...filteredColumns, knowledgeColumn];
  });

  //注册model
  const [registerModal, { openModal }] = useModal();
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: 'test',
      api: async (params) => {
        const res = await list(params);
        // 处理序号 - 关键修改
        if (res?.records && Array.isArray(res.records)) {
          const startIndex = (params.pageNo - 1) * params.pageSize + 1;
          res.records = res.records.map((item, index) => ({
            ...item,
            index: startIndex + index,
          }));
        }
        return res;
      },
      columns: tableColumns,
      canResize: false,
      formConfig: {
        //labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [],
      },
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        // 处理知识库查询参数
        if (params.knowledgeId) {
          // 直接使用对象而不是JSON字符串
          queryParam.metadata = { knowledgeId: params.knowledgeId };
        } else {
          delete queryParam.metadata;
        }
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: 'test',
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });
  const [registerTable, { reload, setPagination }, { rowSelection, selectedRowKeys }] = tableContext;

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);
  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }
  /**
   * 新增事件
   */
  function handleAdd() {
    openModal(true, {
      isUpdate: false,
      showFooter: true,
      record: {
        // 关键:添加初始值
        docName: '',
        text: '',
      },
    });
  }
  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    console.log('当前行数据:', record);
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }
  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: false,
    });
  }
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    resetPaginationAfterDelete();
    await deleteOne({ id: record.id }, handleSuccess);
  }
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    resetPaginationAfterDelete();
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }

  // 新增:删除操作后重置分页状态
  function resetPaginationAfterDelete() {
    // 获取当前分页状态
    const currentPagination = pagination.value;

    // 计算删除后总页数
    const totalPages = Math.ceil((currentPagination.total - 1) / currentPagination.pageSize);

    // 如果当前页码大于总页数,则回到最后一页
    if (currentPagination.current > totalPages && totalPages > 0) {
      pagination.value = {
        ...currentPagination,
        current: totalPages,
        total: currentPagination.total - 1,
      };
    } else {
      // 否则保持当前页,但更新总数
      pagination.value = {
        ...currentPagination,
        total: currentPagination.total - 1,
      };
    }

    // 设置表格分页状态
    setPagination(pagination.value);
  }
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    console.log('record', record);
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
        auth: 'embeddings:embeddings:edit',
      },
    ];
  }
  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
        auth: 'embeddings:embeddings:edit',
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft',
        },
        auth: 'embeddings:embeddings:delete',
      },
    ];
  }
</script>

<style lang="less" scoped>
  :deep(.ant-picker),
  :deep(.ant-input-number) {
    width: 100%;
  }
</style>