<template>
  <div class="gpu-list">
    <!-- 顶部筛选区域 -->
    <div class="filter-section">
      <el-select
        v-model="selectedBucket"
        placeholder="请选择知识库"
        @change="handleBucketChange"
      >
        <el-option
          v-for="item in buckets"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>

      <el-select
        v-model="selectedType"
        placeholder="请选择目录"
        :disabled="!selectedBucket"
        class="ml-15"
      >
        <el-option
          v-for="item in types"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>

      <el-button
        type="primary"
        :loading="isSyncing"
        :disabled="!selectedType"
        class="ml-15"
        @click="handleSyncData"
      >
        {{ isSyncing ? "同步中..." : "同步数据" }}
      </el-button>
    </div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <!-- 原有的文献列表 tab -->
      <el-tab-pane label="文献列表" name="first">
        <!-- 添加搜索表单 -->
        <div class="search-form">
          <el-form
            :inline="true"
            :model="searchForm"
            class="demo-form-inline"
            label-width="80px"
            ><el-form-item label="内容:">
              <el-input
                style="width: 260px"
                v-model="searchForm.name"
                clearable
                placeholder="请输入名称\文献编号\ID"
              ></el-input>
            </el-form-item>
            <el-form-item label="创建时间:">
              <el-date-picker
                v-model="searchForm.createTimeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
            <el-form-item label="更新时间:">
              <el-date-picker
                v-model="searchForm.updateTimeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
             <el-form-item label="项目:">
              <el-select
                v-model="searchForm.project_id"
                clearable
                placeholder="请选择项目"
              >
              <el-option
              v-for="project in projectOptions"
                :key="project.id"
                :label="project.name"
                :value="project.id"
              />
              </el-select>
            </el-form-item>
            <el-form-item label="处理状态:">
              <el-select
                v-model="searchForm.processing_status"
                clearable
                placeholder="请选择处理状态"
              >
                <el-option
                  v-for="(value, key) in STATUS_MAP"
                  :key="key"
                  :label="value.text"
                  :value="key"
                />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="文本时间:">
              <el-date-picker
                v-model="searchForm.textTimeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
              />
            </el-form-item> -->
            <el-form-item label="标签:">
              <el-select
                v-model="searchForm.id"
                multiple
                filterable
                remote
                reserve-keyword
                :remote-method="searchFormTags"
                :loading="searchTagsLoading"
                placeholder="请输入标签关键词"
                clearable
              >
                <el-option
                  v-for="tag in searchTagOptions"
                  :key="tag.id"
                  :label="tag.name"
                  :value="tag.name"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetSearch" type="danger">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="batch-operations">
          <el-button
            type="primary"
            @click="handleBatchProcess"
            :loading="isProcessing"
            :disabled="selectedRows.length === 0"
            class="ml-15"
          >
            {{ isProcessing ? "处理中..." : "批量处理文献" }}
          </el-button>
          <el-button
            type="primary"
            @click="handleBatchTag"
            :disabled="selectedRows.length == 0"
            >批量绑定标签</el-button
          >
          <el-button
            type="primary"
            @click="handleBatchProject"
            :disabled="selectedRows.length == 0"
            >批量绑定项目</el-button
          >
          <el-button
            type="primary"
            @click="handleExport"
            :disabled="selectedRows.length == 0"
            >文件导出</el-button
          >
            <el-button type="danger" :disabled="selectedRows.length === 0" @click="endAnalysis()">
            <!-- <i data-feather="stop-circle" style="width: 12px;"></i> -->
            终止选中任务
          </el-button>
        </div>
        <!-- 添加选择提示区域  :title="selectionText"-->
        <div class="selection-control" v-if="selectedRows.length > 0">
          <el-alert
            type="info"
            show-icon
            :closable="false"
            style="margin-bottom: 10px"
          >
            <template v-if="!isAllDataSelected">
              <span
                type="text"
                style="cursor: pointer; color: #409eff"
                @click="handleSelectAllData"
              >
                选择全部{{ total }}条数据
              </span>
            </template>
            <template v-else>
              <span
                type="text"
                style="cursor: pointer; color: #409eff"
                @click="handleCancelAllSelection"
              >
                取消全选
              </span>
            </template>
          </el-alert>
        </div>
        <!-- 数据表格区域 -->
        <el-table
          v-loading="isLoading"
          :data="gpuList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          @select-all="handleSelectAll"
          ref="gpuTable"
          :row-key="getRowKey"
        >
          <el-table-column
            type="selection"
            width="55"
            :selectable="checkSelectable"
            :reserve-selection="true"
          />
          <el-table-column prop="projects" label="项目" >
            <template #default="{ row }">
              <el-tag
                v-for="(item, index) in row.projects"
                :key="index"
                type=""
                style="margin-right: 5px; margin-bottom: 5px"
              >
                {{ item.name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="identifier" label="文献编号"></el-table-column>

          <el-table-column prop="name" label="名称" sortable>
            <!-- <template #default="{ row }">
              <el-link @click="handleNameClick(row)">{{ row.name }}</el-link>
            </template> -->
          </el-table-column>
          
          <el-table-column prop="tags" label="已绑定标签">
            <template #default="{ row }">
              <el-tag
                v-for="(item, index) in row.tags"
                :key="index"
                type=""
                style="margin-right: 5px; margin-bottom: 5px"
              >
                {{ item.name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="文档类型" width="100" />
          <el-table-column
            prop="create_time"
            label="创建时间"
            width="200"
            sortable
          />
          <el-table-column prop="status" label="处理状态" width="100">
            <template #default="{ row }">
              <el-tooltip
                effect="dark"
                placement="top"
                :disabled="![1, 3, 5].includes(Number(row.processing_status))"
              >
                <template #content>
                  <div style="padding: 5px">
                    <div style="margin-top: 5px; font-size: 12px">
                      {{
                        row.progress_msg + " " + row.progress + "%" ||
                        (row.processing_status === 3
                          ? "处理失败"
                          : "正在处理中...")
                      }}
                    </div>
                  </div>
                </template>
                <div class="status-wrapper">
                  <template
                    v-if="[1, 5].includes(Number(row.processing_status))"
                  >
                    <el-tag type="warning">处理中</el-tag>
                    <!-- <el-progress 
                      v-if="row.progress" 
                      :percentage="row.progress" 
                      :format="percentFormat"
                      style="width: 80px; margin-left: 10px;"
                    /> -->
                  </template>
                  <template v-else>
                    <el-tag :type="getStatusType(row.processing_status)">
                      {{ getStatusText(row.processing_status) }}
                    </el-tag>
                  </template>
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-dropdown trigger="click">
                <el-button
                  type="text"
                  size="small"
                  circle
                  class="operation-button"
                  style="font-size: 15px; margin-left: 10px"
                  icon="el-icon-more"
                ></el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click.native="handleNameClick(row)">
                      <i class="el-icon-view"></i> 查看
                    </el-dropdown-item>
                    <el-dropdown-item @click.native="handlePreview(row)">
                      <i class="el-icon-tickets"></i> 预览
                    </el-dropdown-item>
                    <el-dropdown-item
                      @click.native="handleSingleProcess(row)"
                      v-if="row.processing_status !== 2"
                    >
                      <i class="el-icon-caret-right"></i> 处理文献
                    </el-dropdown-item>
                    <el-dropdown-item
                      @click.native="handleReprocess(row)"
                      v-if="row.processing_status === 2"
                    >
                      <i class="el-icon-refresh"></i> 重新处理
                    </el-dropdown-item>
                    <el-dropdown-item
                      @click.native="handleRemoveTag(row)"
                      v-if="row.tags && row.tags.length > 0"
                    >
                      <i class="el-icon-delete"></i> 删除绑定标签
                    </el-dropdown-item>
                    <el-dropdown-item
                      @click.native="handleRemoveProject(row)"
                      v-if="row.projects && row.projects.length > 0"
                    >
                      <i class="el-icon-delete"></i> 删除关联项目
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <el-pagination
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </el-tab-pane>

      <!-- 添加 SOTA详情 tab -->
      <el-tab-pane label="Outcomes详情" name="second">
        <!-- 添加搜索表单 -->
        <div class="search-form">
          <el-form
            :inline="true"
            :model="Sota_searchForm"
            class="demo-form-inline"
            label-width="80px"
            ><el-form-item label="内容:">
              <el-input
                style="width: 260px"
                v-model="Sota_searchForm.keyword"
                clearable
                placeholder="请输入文献名称\ID"
              ></el-input>
            </el-form-item>
            <el-form-item label="项目:">
              <el-select
                v-model="Sota_searchForm.project_id"
                clearable
                placeholder="请选择项目"
              >
              <el-option
              v-for="project in projectOptions"
                :key="project.id"
                :label="project.name"
                :value="project.id"
              />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSotaSearch"
                >搜索</el-button
              >
              <el-button @click="resetSotaSearch" type="danger">重置</el-button>
              <el-button @click="outExport" type="primary">导出</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="sotaDetailsList" style="width: 100%">
          <el-table-column prop="projects" label="项目" >
            <template #default="{ row }">
              <el-tag
                v-for="(item, index) in row.projects"
                :key="index"
                type=""
                style="margin-right: 5px; margin-bottom: 5px"
              >
                {{ item.name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="文献ID" prop="literature_id" />
          <el-table-column label="文献名称" prop="literature_name" />
          <!--   <el-table-column label="Identifier" prop="identifier" /> -->
          <el-table-column label="Outcomes Name" prop="outcome_name" />
          <el-table-column
            label="Outcome Definition"
            prop="outcome_definition"
          ></el-table-column>
          <el-table-column label="Group" prop="group"></el-table-column>
          <el-table-column label="Patient" prop="patient" />
          <el-table-column label="Outcomes Value" prop="value" />
          <!-- <el-table-column label="Unit for analysis" prop="unit" /> -->
          <el-table-column label="创建时间" prop="create_time" />
          <!-- 操作列与原有类似 -->
        </el-table>

        <!-- 分页器 -->
        <el-pagination
          class="pagination"
          @size-change="handleStoaSizeChange"
          @current-change="handleStoaCurrentChange"
          :current-page="Sota_searchForm.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="Sota_searchForm.page_size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="Stoa_total"
        />
      </el-tab-pane>

      <!-- 添加 SOTA汇总表 tab -->
      <!-- <el-tab-pane label="SOTA汇总表" name="third">
        <el-table :data="sotaSummaryList" style="width: 100%">
          <el-table-column label="Summary" prop="summary" />
          <el-table-column label="EqMD" prop="eqmd" />
          <el-table-column label="Pain:VAS" prop="painVas" />
        
        </el-table>
      </el-tab-pane> -->
    </el-tabs>

    <!-- 添加标签对话框 -->
    <el-dialog
      title="批量绑定标签"
      :visible.sync="tagDialogVisible"
      width="800px"
    >
      <el-form :model="tagForm" label-width="150px">
        <el-form-item label="标签分类:">
          <el-select
            v-model="tagForm.category_id"
            placeholder="请选择分类"
            clearable
            style="width: 350px"
            @change="handleCategoryChange"
          >
            <el-option label="全部分类" value="" />
            <el-option
              v-for="item in categoriesList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签:">
          <el-select
            style="width: 350px"
            v-model="tagForm.tags"
            multiple
            filterable
            remote
            reserve-keyword
            :remote-method="handleTagSearch"
            :loading="tagsLoading"
            placeholder="请输入关键词搜索标签"
          >
            <el-option
              v-for="tag in tagOptions"
              :key="tag.id"
              :label="tag.name"
              :value="tag.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tagDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchTag">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加项目对话框 -->
    <el-dialog
      title="批量绑定项目"
      :visible.sync="projectDialogVisible"
      width="800px"
    >
    
      <el-form :model="projectForm" label-width="150px">
        <el-form-item label="项目:">
          <el-select
            style="width: 350px"
            v-model="projectForm.projects"
            multiple
            filterable
          
            :loading="projectsLoading"
            placeholder="请输入关键词搜索项目"
          >
            <el-option
              v-for="project in projectOptions"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="projectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchProject">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 导出设置对话框 -->
    <el-dialog
      title="导出设置"
      :visible.sync="exportDialogVisible"
      width="500px"
    >
      <el-form :model="exportForm" label-width="100px">
        <el-form-item label="选择项目:">
          <el-select
            v-model="exportForm.project_id"
            clearable
            filterable
            style="width: 100%"
            placeholder="请选择项目（可选）"
          >
            <el-option
              v-for="project in projectOptions"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="exportDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmExport">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除标签对话框 -->
    <el-dialog
      title="删除标签"
      :visible.sync="removeTagDialogVisible"
      width="800px"
    >
      <el-form :model="removeTagForm" label-width="150px">
        <el-form-item label="标签分类:">
          <el-select
            v-model="removeTagForm.category_id"
            placeholder="请选择分类"
            clearable
            style="width: 350px"
            @change="handleRemoveTagCategoryChange"
          >
            <el-option label="全部分类" value="" />
            <el-option
              v-for="item in categoriesList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签:">
          <el-select
            style="width: 350px"
            v-model="removeTagForm.tags"
            multiple
            filterable
            remote
            reserve-keyword
            :remote-method="handleRemoveTagSearch"
            :loading="removeTagsLoading"
            placeholder="请选择要删除的标签"
          >
            <el-option
              v-for="tag in currentRowTags"
              :key="tag.id"
              :label="tag.name"
              :value="tag.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="removeTagDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRemoveTag">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除项目对话框 -->
    <el-dialog
      title="删除项目"
      :visible.sync="removeProjectDialogVisible"
      width="800px"
    >
      <el-form :model="removeProjectForm" label-width="150px">
        <el-form-item label="项目:">
          <el-select
            style="width: 350px"
            v-model="removeProjectForm.projects"
            multiple
            filterable
            placeholder="请选择要删除的项目"
          >
            <el-option
              v-for="project in currentRowProjects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="removeProjectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRemoveProject">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { debounce } from "lodash-es";
import {
  GET_list,
  GET_sync,
  listBuckets,
  selectTypeList,
  getDetail,
  search_tags,
  edit_tags,
  search,
  process_model_generation,
  process_model_regeneration,
  categories,
  literResult,
  getSotaDetails,
  exportOutcoms,
  literEndClear,
  getProgress
} from "@/api/knowledge";
import axios from "axios";
// 状态映射表
const STATUS_MAP = {
  0: { text: "未处理", type: "info" },
  1: { text: "处理中", type: "warning" },
  2: { text: "处理完成", type: "success" },
  3: { text: "处理失败", type: "danger" },
  5: { text: "待处理", type: "warning" },
};

export default {
  name: "GpuList",

  data() {
    return {
      gpuList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      isLoading: false,
      isSyncing: false,
      buckets: [],
      types: [],
      selectedBucket: null,
      selectedType: null,
      activeName: "first", // 当前激活的tab
      sotaDetailsList: [], // SOTA详情列表数据
      sotaSummaryList: [], // SOTA汇总表数据
      projectDialogVisible: false, // 项目对话框显示状态
      projectForm: {
        projects: [], // 选中的项目ID数组
      },
      projectOptions: [], // 项目选项
      projectsLoading: false, // 项目加载状态
      searchForm: {
        name: "",
        createTimeRange: [],
        textTimeRange: [],
        id: [],
        type: "", // 新增文档类型
        processing_status: "", // 新增处理状态
        updateTimeRange: [], // 新增更新时间范围
        project_id:[]
      },
      selectedRows: [], // 选中的行
      tagDialogVisible: false, // 标签对话框显示状态
      categoriesList: [], // 添加分类列表
      tagForm: {
        tags: [], // 选中的标签ID数组
        category_id: null, // 添加分类ID
      },
      tagOptions: [], // 标签选项
      tagsLoading: false, // 标签加载状态

      searchTagOptions: [], // 搜索表单的标签选项
      searchTagsLoading: false, // 搜索表单的标签加载状态
      isProcessing: false, // 批量处理的加载状态
      pollingTimers: {}, // 新增：存储每个文献的轮询定时器
      STATUS_MAP: {
        0: { text: "未处理", type: "info" },
        1: { text: "处理中", type: "warning" },
        2: { text: "处理完成", type: "success" },
        3: { text: "处理失败", type: "danger" },
        5: { text: "待处理", type: "warning" },
      },
      multipleSelection: [], // 存储跨页选中的数据
      selectedRows: [], // 当前页选中的行
      allSelectedRows: new Map(), // 存储所有选中的行
      isAllDataSelected: false, // 是否选中所有数据

      /* 导出设置 */
      exportDialogVisible: false,
      exportForm: {
        project_id: ''
      },
      /* SOTA搜索 */
      Sota_searchForm: {
        page: 1,
        page_size: 10,
        keyword: "",
        pproject_id:[]
      },
      /* SOTA详情 总数 */
      Stoa_total: 0,
      
      /* 删除标签相关 */
      removeTagDialogVisible: false,
      removeTagForm: {
        tags: [],
        category_id: "",
      },
      removeTagsLoading: false,
      currentRowTags: [], // 当前行的标签列表
      currentRow: null, // 当前选中的行

      /* 删除项目相关 */
      removeProjectDialogVisible: false,
      removeProjectForm: {
        projects: [],
      },
      currentRowProjects: [], // 当前行的项目列表
    };
  },

  created() {
    // 使用抖处理数据加载
    this.debouncedFetchGpuList = debounce(this.fetchGpuList, 300);
  },

  mounted() {
    this.initialize();
    this.handleProjectSearch();
  },

  computed: {
    // 添加选择提示文本计算属性
    selectionText() {
      const selectedCount = this.isAllDataSelected
        ? this.total
        : this.allSelectedRows.size;
      return `已选择 ${selectedCount} 项`;
    },
  },
  methods: {
    // 打开项目对话框
    handleBatchProject() {
      this.projectDialogVisible = true;
      this.projectForm = {
        projects: [],
      };
       // 获取初始项目列表
    },

    // 项目搜索
    async handleProjectSearch() {
      this.projectsLoading = true;
      try {
        const response = await axios.post(
          `${process.env.VUE_APP_BASE_API}/project/search`,
          {
            page: 1,
            page_size: 50
          }
        );
        console.log(response);
        if (response.data.status === 200) {
         
          this.projectOptions = response.data.data.dataList;
           console.log( this.projectOptions);
        }
      } catch (error) {
        console.error("搜索项目失败:", error);
        this.$message.error("搜索项目失败");
      } finally {
        this.projectsLoading = false;
      }
    },

    // 提交批量绑定项目
    async submitBatchProject() {
      try {
        const selectedIds = this.isAllDataSelected
          ? await this.getAllDataIds()
          : Array.from(this.allSelectedRows.keys());

        if (selectedIds.length === 0) {
          this.$message.warning("请选择需要绑定的文献");
          return;
        }

        if (this.projectForm.projects.length === 0) {
          this.$message.warning("请选择要绑定的项目");
          return;
        }

        const response = await axios.post(
          `${process.env.VUE_APP_BASE_API}/literature/batch_associate_to_projects`,
          {
            literature_ids: selectedIds,
            project_ids: this.projectForm.projects
          }
        );

        if (response.status === 200) {
          this.$message.success("批量绑定项目成功");
          this.projectDialogVisible = false;
          // 保持当前页码和搜索条件刷新列表
          const currentSearchParams = {
            page: this.currentPage,
            page_size: this.pageSize,
            ...this.searchForm
          };
          await this.fetchGpuList(currentSearchParams);
        }
      } catch (error) {
        console.error("批量绑定项目失败:", error);
        this.$message.error(error.response?.data?.message || "批量绑定项目失败");
      }
    },

    /* outcoms导出 */
    async outExport() {
      try {
        this.exportForm.project_id = '';
        this.exportDialogVisible = true;
      } catch (error) {
        this.$message.error(error.message || "导出失败");
        console.error("导出错误:", error);
      }
    },

    // 确认导出
    async confirmExport() {
      try {
        // 准备导出参数
        const params = {
          keyword: this.Sota_searchForm.keyword || undefined,
          project_id: this.exportForm.project_id || undefined
        };

        // 调用导出接口
        const response = await exportOutcoms(params);

        if (response.status === 200) {
          const downloadUrl = response.data.data.download_url;

          // 显示下载链接对话框
          await this.$alert(
            `<div>
              <p>导出成功！请点击下方链接下载文件：</p>
              <p style="word-break: break-all;">
                <a href="${downloadUrl}" target="_blank">${downloadUrl}</a>
              </p>
              <p>您也可以复制链接后在新窗口打开</p>
            </div>`,
            "下载链接",
            {
              dangerouslyUseHTMLString: true,
              confirmButtonText: "复制链接",
              callback: (action) => {
                if (action === "confirm") {
                  // 复制链接到剪贴板
                  const textarea = document.createElement("textarea");
                  textarea.value = downloadUrl;
                  document.body.appendChild(textarea);
                  textarea.select();
                  document.execCommand("copy");
                  document.body.removeChild(textarea);
                  this.$message.success("链接已复制到剪贴板");
                  this.exportDialogVisible = false;
                }
              },
            }
          );
        }
      } catch (error) {
        if (error === "cancel") return;
        this.$message.error(error.message || "导出失败");
        console.error("导出错误:", error);
      }
    },
    // 添加获取分类列表方法
    async fetchCategories() {
      try {
        const res = await categories();
        if (res.status === 200) {
          this.categoriesList = res.data.data.items;
        }
      } catch (error) {
        console.error("获取分类列表失败:", error);
        this.$message.error("获取分类列表失败");
      }
    },
    // 修改导出处理方法
    async handleExport() {
      try {
        const ids = this.selectedRows.map((row) => row.id);

        // 添加确认对话框
        await this.$confirm("确认要导出选中的文献吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        // 调用导出接口获取下载链接
        const response = await axios.post(
          `${process.env.VUE_APP_BASE_API}/literature-data/export/`,
          { ids }
        );

        if (response.status === 200) {
          const downloadUrl = response.data.data.data.download_url;

          // 显示下载链接对话框
          await this.$alert(
            `<div>
              <p>导出成功！请点击下方链接下载文件：</p>
              <p style="word-break: break-all;">
                <a href="${downloadUrl}" target="_blank">${downloadUrl}</a>
              </p>
              <p>您也可以复制链接后在新窗口打开</p>
            </div>`,
            "下载链接",
            {
              dangerouslyUseHTMLString: true,
              confirmButtonText: "复制链接",
              callback: (action) => {
                if (action === "confirm") {
                  // 复制链接到剪贴板
                  const textarea = document.createElement("textarea");
                  textarea.value = downloadUrl;
                  document.body.appendChild(textarea);
                  textarea.select();
                  document.execCommand("copy");
                  document.body.removeChild(textarea);
                  this.$message.success("链接已复制到剪贴板");
                }
              },
            }
          );
        }
      } catch (error) {
        if (error === "cancel") return;
        this.$message.error(error.message || "导出失败");
        console.error("导出错误:", error);
      }
    },
    // 修改重新处理方法
    async handleReprocess(row) {
      try {
        await this.$confirm("确认要重新处理该文献吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        // 调用重新处理的接口
        const res = await process_model_regeneration([row.id]);

        if (res.status === 200) {
          this.$message.success("重新处理任务已提交");
          // 更新状态并开始轮询
          this.$set(row, "processing_status", 1);
          this.$set(row, "progress", 0);
          this.startPolling(row.id);
          await this.fetchGpuList();
        }
      } catch (error) {
        if (error === "cancel") return;
        this.$message.error(error.message || "重新处理提交失败");
        console.error("重新处理错误:", error);
      }
    },
    // 在中添加单个处理方法
    async handleSingleProcess(row) {
      try {
        await this.$confirm("确认要处理该文献吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        const res = await process_model_regeneration([row.id]);

        if (res.status === 200) {
          this.$message.success("处理任务已提交");
          // 更新状态并开始轮询
          this.$set(row, "processing_status", 1);
          this.$set(row, "progress", 0);
          this.startPolling(row.id);
          await this.fetchGpuList();
        }
      } catch (error) {
        if (error === "cancel") {
          return;
        }
        this.$message.error(error.message || "处理提交失败");
        console.error("处理错误:", error);
      }
    },
    /* 搜索栏模糊查找 */
    async searchFormTags(query) {
      if (query !== "") {
        this.searchTagsLoading = true;
        try {
          const { data } = await search_tags({ keyword: query });
          this.searchTagOptions = data.data.items;
        } catch (error) {
          this.$message.error("搜索标签失败");
        } finally {
          this.searchTagsLoading = false;
        }
      } else {
        this.searchTagOptions = [];
      }
    },
    // 获取行的唯一键
    getRowKey(row) {
      return row.id;
    },

    // 处理表格选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection;

      if (!this.isAllDataSelected) {
        // 更新选中数据集合
        selection.forEach((row) => {
          this.allSelectedRows.set(row.id, row);
        });

        // 当前页取消选中的数据从总选中集合中移除
        this.gpuList.forEach((row) => {
          if (!selection.find((item) => item.id === row.id)) {
            this.allSelectedRows.delete(row.id);
          }
        });
      }
    },

    // 处理全选按钮
    handleSelectAll(selection) {
      if (selection.length > 0) {
        this.$message.success(`已全选当前页${selection.length}条数据`);
      } else {
        // 取消当前页所有选择
        this.gpuList.forEach((row) => {
          this.allSelectedRows.delete(row.id);
        });
        this.$message.info("已取消选中当前页全部数据");
      }
    },

    // 选择全部数据
    async handleSelectAllData() {
      try {
        // 获取所有数据的查询参数
        const params = {
          page: 1,
          page_size: this.total,
          keyword: this.searchForm.name,
          tag_names: this.searchForm.id,
          create_time_start: this.searchForm.createTimeRange?.[0] || "",
          create_time_end: this.searchForm.createTimeRange?.[1] || "",
          update_time_start: this.searchForm.updateTimeRange?.[0] || "",
          update_time_end: this.searchForm.updateTimeRange?.[1] || "",
          processing_status: this.searchForm.processing_status || null,
          project_id: this.searchForm.project_id || null,
        };

        const response = await axios.post(
          `${process.env.VUE_APP_BASE_API}/literature-data/search/`,
          params
        );

        if (response.status === 200) {
          const allData = response.data.data.list;
          // 清空之前的选择
          this.allSelectedRows.clear();
          // 将所有数据添加到选中集合
          allData.forEach((item) => {
            this.allSelectedRows.set(item.id, item);
          });

          this.isAllDataSelected = true;

          // 选中当前页显示的所有行
          this.$nextTick(() => {
            if (this.$refs.gpuTable) {
              this.gpuList.forEach((row) => {
                this.$refs.gpuTable.toggleRowSelection(row, true);
              });
            }
          });

          this.$message.success(`已选中全部${this.total}条数据`);
        }
      } catch (error) {
        console.error("获取全部数据失败:", error);
        this.$message.error("选择全部数据失败");
      }
    },

    // 取消全选
    handleCancelAllSelection() {
      this.clearSelection();
      this.$message.info("已取消全部选择");
    },

    // 检查行是否可选
    checkSelectable(row) {
      // 可以根据需要添加选择限制条件
      return true;
    },

    // 修改分页方法
    async handleCurrentChange(val) {
      this.currentPage = val;
      await this.fetchGpuList();

      // 恢复选中状态
      this.$nextTick(() => {
        if (this.$refs.gpuTable) {
          this.gpuList.forEach((row) => {
            if (this.allSelectedRows.has(row.id) || this.isAllDataSelected) {
              this.$refs.gpuTable.toggleRowSelection(row, true);
            }
          });
        }
      });
    },

    // 修改每页条数切换方法
    async handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      await this.fetchGpuList();

      // 恢复选中状态
      this.$nextTick(() => {
        if (this.$refs.gpuTable) {
          this.gpuList.forEach((row) => {
            if (this.allSelectedRows.has(row.id) || this.isAllDataSelected) {
              this.$refs.gpuTable.toggleRowSelection(row, true);
            }
          });
        }
      });
    },

    // 清空选择
    clearSelection() {
      if (this.$refs.gpuTable) {
        this.$refs.gpuTable.clearSelection();
      }
      this.selectedRows = [];
      this.allSelectedRows.clear();
      this.isAllDataSelected = false;
    },

    // 打开标签对话框时重置表单
    handleBatchTag() {
      this.tagDialogVisible = true;
      this.tagForm = {
        tags: [],
        category_id: "",
      };
      this.tagOptions = [];
      this.fetchCategories(); // 获取分类列表
      this.handleCategoryChange(""); // 获取所有标签
    },
    // 修改分类变更处理方法
    async handleCategoryChange(categoryId) {
      this.tagForm.tags = []; // 清空已选标签
      this.tagOptions = []; // 清空标签选项

      try {
        this.tagsLoading = true;
        const { data } = await search_tags({
          page: 1,
          pagesize: 999,
          keyword: "",
          category_id: categoryId === "" ? undefined : categoryId, // 修改判断条件
        });

        if (data?.data?.items) {
          this.tagOptions = data.data.items;
        }
      } catch (error) {
        console.error("获取标签列表失败:", error);
        this.$message.error("获取标签列表失败");
      } finally {
        this.tagsLoading = false;
      }
    },

    // 修改标签搜索方法
    async handleTagSearch(query) {
      this.tagsLoading = true;
      try {
        const { data } = await search_tags({
          keyword: query,
          category_id:
            this.tagForm.category_id === ""
              ? undefined
              : this.tagForm.category_id, // 修改判断条件
        });

        if (data?.data?.items) {
          this.tagOptions = data.data.items;
        }
      } catch (error) {
        console.error("搜索标签失败:", error);
        this.$message.error("搜索标签失败");
      } finally {
        this.tagsLoading = false;
      }
    },

    /* 批量处理文献 */
    async handleBatchProcess() {
      try {
        const selectedIds = this.isAllDataSelected
          ? await this.getAllDataIds()
          : Array.from(this.allSelectedRows.keys());

        if (selectedIds.length === 0) {
          this.$message.warning("请选择需要处理的文献");
          return;
        }

        this.isProcessing = true;

        await this.$confirm("确认要批量处理选中的文献吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        const res = await process_model_regeneration(selectedIds);

        if (res.status === 200) {
          this.$message.success("批量处理已提交");

          // 更新选中行的状态并启动轮询
          selectedIds.forEach((id) => {
            const row = this.gpuList.find((item) => item.id === id);
            if (row) {
              this.$set(row, "processing_status", 1);
              this.$set(row, "progress", 0);
              this.startPolling(id);
            }
          });

          this.selectedRows = [];
          this.clearSelection();
          this.allSelectedRows.clear();
          
          // 保持当前页码和搜索条件刷新列表
          const currentSearchParams = {
            page: this.currentPage,
            page_size: this.pageSize,
            ...this.searchForm
          };
          await this.fetchGpuList(currentSearchParams);
        }
      } catch (error) {
        if (error === "cancel") return;
        this.$message.error(error.message || "批量处理提交失败");
        console.error("批量处理错误:", error);
      } finally {
        this.isProcessing = false;
      }
    },
    // 获取所有数据的ID
    async getAllDataIds() {
      try {
        const params = {
          page: 1,
          page_size: this.total,
          keyword: this.searchForm.name,
          tag_names: this.searchForm.id,
          create_time_start: this.searchForm.createTimeRange?.[0] || "",
          create_time_end: this.searchForm.createTimeRange?.[1] || "",
          update_time_start: this.searchForm.updateTimeRange?.[0] || "",
          update_time_end: this.searchForm.updateTimeRange?.[1] || "",
          processing_status: this.searchForm.processing_status || null,
          project_id: this.searchForm.project_id || null,
        };

        const response = await axios.post(
          `${process.env.VUE_APP_BASE_API}/literature-data/search/`,
          params
        );

        if (response.status === 200) {
          return response.data.data.list.map((item) => item.id);
        }
        return [];
      } catch (error) {
        console.error("获取所有数据ID失败:", error);
        return [];
      }
    },

    /* 模糊搜索 */
    async searchTags(query) {
      if (query !== "") {
        this.tagsLoading = true;
        try {
          const { data } = await search_tags({
            keyword: query,
          });
          this.tagOptions = data.data.items;
        } catch (error) {
          this.$message.error("搜索标签失败");
        } finally {
          this.tagsLoading = false;
        }
      } else {
        this.tagOptions = [];
      }
    },

    // 修改提交方法
    async submitBatchTag() {
      try {
        const selectedIds = this.isAllDataSelected
          ? await this.getAllDataIds()
          : Array.from(this.allSelectedRows.keys());

        if (selectedIds.length === 0) {
          this.$message.warning("请选择需要绑定标签的文献");
          return;
        }

        const idObject = { literature_ids: selectedIds, tag_ids: this.tagForm.tags };
        const response = await axios.post(
          `${process.env.VUE_APP_BASE_API}/literature-tags/relation_tags/`,
          idObject,
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        );
        if (response.status !== 200) return;
        
        this.$message.success("标签更新成功");
        this.tagDialogVisible = false;
        
        // 保持当前页码和搜索条件刷新列表
        const currentSearchParams = {
          page: this.currentPage,
          page_size: this.pageSize,
          ...this.searchForm
        };
        await this.fetchGpuList(currentSearchParams);
      } catch (error) {
        this.$message.error("标签更新失败");
      }
    },
    // 处理搜索
    handleSearch() {
      this.currentPage = 1; // 重置页码
      this.fetchGpuList();
    },

    // 修改重置搜索方法
    resetSearch() {
      this.searchForm = {
        name: "",
        createTimeRange: [],
        textTimeRange: [],
        id: [],
        type: "",
        processing_status: "",
        project_id:[]
      };
      this.clearSelection(); // 清空选择
      this.handleSearch();
    },

    // 初始化数据
    async initialize() {
      try {
        await this.fetchBuckets();
        await this.fetchGpuList();
      } catch (error) {
        this.$message.error("初始化数据失败");
        console.error("初始化失败:", error);
      }
    },

    // 获取状态文本
    getStatusText(status) {
      return STATUS_MAP[status]?.text || "未知状态";
    },

    // 获取状态样式类型
    getStatusType(status) {
      return STATUS_MAP[status]?.type || "info";
    },

    // 获取知识库列表
    async fetchBuckets() {
      try {
        const { data } = await listBuckets();
        this.buckets = data;
      } catch (error) {
        this.$message.error("获取知识库列表失败");
        console.error("获取知识库失败:", error);
      }
    },

    // 处理知识库变更
    async handleBucketChange(val) {
      this.selectedType = null;
      this.types = [];

      if (!val) return;

      try {
        const { data } = await selectTypeList({ kb_id: val });
        this.types = data.dataList;
        this.debouncedFetchGpuList();
      } catch (error) {
        this.$message.error("获取目录列表失败");
      }
    },

    // 同步数据处理
    async handleSyncData() {
      if (!this.selectedType) {
        this.$message.warning("请先选择目录");
        return;
      }

      this.isSyncing = true;
      try {
        await GET_sync({ doc_type_id: this.selectedType });
        this.$message.success("同步成功");
        await this.fetchGpuList();
      } catch (error) {
        this.$message.error("同步失败");
      } finally {
        this.isSyncing = false;
      }
    },

    // 修改 fetchGpuList 方法
    async fetchGpuList(customParams = null) {
      this.isLoading = true;
      try {
        const params = customParams || {
          page: this.currentPage,
          page_size: this.pageSize,
          keyword: this.searchForm.name,
          tag_names: this.searchForm.id,
          create_time_start: this.searchForm.createTimeRange?.[0] || "",
          create_time_end: this.searchForm.createTimeRange?.[1] || "",
          update_time_start: this.searchForm.updateTimeRange?.[0] || "",
          update_time_end: this.searchForm.updateTimeRange?.[1] || "",
          processing_status: this.searchForm.processing_status || null,
          project_id: this.searchForm.project_id || null,
        };

        const response = await axios.post(
          `${process.env.VUE_APP_BASE_API}/literature-data/search/`,
          params
        );

        if (response.status !== 200) return;

        // 更新数据和分页信息
        const { list, total, current_page, page_size } = response.data.data;

        // 处理列表数据
        this.gpuList = list.map((item) => {
          const nameParts = item.name.split(".");
          return {
            ...item,
            name: nameParts[0],
            type: nameParts.length > 1 ? nameParts.pop() : "未知",
            processing_status: Number(item.processing_status),
          };
        });

        // 获取需要查询详细状态的文献ID（处理中和处理失败的）
        const needStatusCheckIds = this.gpuList
          .filter((item) => [1, 3, 5].includes(Number(item.processing_status)))
          .map((item) => item.id);

        if (needStatusCheckIds.length > 0) {
          await this.fetchBatchStatus(needStatusCheckIds);
        }

        // 更新分页信息
        this.total = parseInt(total);
        this.currentPage = parseInt(current_page);
        this.pageSize = parseInt(page_size);
      } catch (error) {
        console.error("获取列表数据失败:", error);
        this.$message.error("获取列表数据失败");
      } finally {
        this.isLoading = false;
      }
    },

    // 修改批量获取状态的方法
    async fetchBatchStatus(ids) {
      try {
        const statusPromises = ids.map((id) => literResult(id));
        const responses = await Promise.allSettled(statusPromises);

        responses.forEach((response, index) => {
          if (
            response.status === "fulfilled" &&
            response.value.status === 200
          ) {
            const id = ids[index];
            const item = this.gpuList.find((item) => item.id === id);
            if (item) {
              const literatureInfo = response.value.data.data.literature_info;
              const status = Number(literatureInfo.processing_status);

              // 只更新处理中和处理失败的状态信息
              if ([1, 3, 5].includes(status)) {
                this.$set(item, "processing_status", status);
                this.$set(
                  item,
                  "progress_msg",
                  literatureInfo.status_description
                );

                // 如果状态是处理中，启动轮询
                if (status === 1 || status === 5) {
                  this.startPolling(id);
                }
              }
            }
          }
        });
      } catch (error) {
        console.error("批量获取状态失败:", error);
      }
    },

    // 新增：开始轮询
    startPolling(id) {
      if (this.pollingTimers[id]) return;

      const checkStatus = async () => {
        try {
          const [statusResponse, progressResponse] = await Promise.all([
            literResult(id),
            getProgress([id])
          ]);

          if (statusResponse.status === 200) {
            const item = this.gpuList.find((item) => item.id === id);
            if (item) {
              // 获取状态信息
              const literatureInfo = statusResponse.data.data.literature_info;
              const newStatus = Number(literatureInfo.processing_status);
              const newProgressMsg = literatureInfo.status_description;

              // 获取进度信息
              if (progressResponse.status === 200) {
                const progressInfo = progressResponse.data.data.literature_progress[0];
                if (progressInfo && progressInfo.literature_id === id) {
                  this.$set(item, "progress", progressInfo.current_progress || 0);
                }
              }

              // 更新状态相关数据
              this.$set(item, "processing_status", newStatus);
              this.$set(item, "progress_msg", newProgressMsg);

              // 根据状态处理结果
              if (newStatus === 2) {
                // 处理完成
                this.$message.success("处理成功");
                this.stopPolling(id);
                await this.fetchGpuList();
              } else if (newStatus === 3) {
                // 处理失败 - 保存失败原因
                const failureReason =
                  literatureInfo.status_description || "处理失败";
                this.$set(item, "progress_msg", failureReason);
                this.$message.error(failureReason);
                this.stopPolling(id);
              } else if (newStatus === 1 || newStatus === 5) {
                // 继续轮询
                this.pollingTimers[id] = setTimeout(checkStatus, 5000);
              }
            }
          } else {
            this.$message.error("获取处理状态失败");
            delete this.pollingTimers[id];
          }
        } catch (error) {
          console.error("获取处理状态错误:", error);
          this.$message.error("获取处理状态时出现错误");
          this.stopPolling(id);
        }
      };

      // 立即开始检查
      checkStatus();
    },

    // 新增：停止轮询
    stopPolling(id) {
      if (this.pollingTimers[id]) {
        clearTimeout(this.pollingTimers[id]);
        delete this.pollingTimers[id];
      }
    },

    /*  // 修改分页处理方法
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1; // 切换每页数量时重置为第一页
      this.fetchGpuList(); // 移除防抖，直接调用
    }, */

    /*  handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchGpuList(); // 移除防抖，直接调用
    }, */
    /* 预览 */
    handlePreview(row) {
      console.log(row);
      let _this = this;
      let a = document.createElement("a");
      a.href = `#/infoList?id=${row.id}&type=${row.type.toLowerCase()}`; // 使用 hash
      a.target = "_blank";
      a.click();
    },
    // 处理名称点击
    async handleNameClick(row) {
      try {
        /* const res = await getDetail({ id: row.id })
        console.log('详情数据:', res) */
        this.$router.push({
          path: "/knowledge/middPage/index",
          query: {
            id: row.id,
            name: row.name,
            tag: JSON.stringify(row.tags),
            identifier: row.identifier,
            type: row.type,
          },
        });
        // 这里可以添加详情处理逻辑
      } catch (error) {
        this.$message.error("获取详情失败");
      }
    },
    // Tab切换处理
    handleClick(tab) {
      // 根据tab加载相应数据
      switch (tab.name) {
        case "second":
          this.loadSotaDetails();
          break;
        case "third":
          this.loadSotaSummary();
          break;
      }
    },

    // 加载SOTA详情数据
    async loadSotaDetails() {
      try {
        // 这里调用API获取SOTA详情数据
        const response = await getSotaDetails(this.Sota_searchForm);
        this.sotaDetailsList = response.data.list;
        this.Sota_searchForm.page_size = response.data.page_size;
        this.Sota_searchForm.page = response.data.current_page;
        this.Stoa_total = response.data.total;
      } catch (error) {
        /* this.$message.error("获取SOTA详情失败");
        console.error(error); */
      }
    },

    /* 详情翻页 */
    async handleStoaSizeChange(val) {
      this.Sota_searchForm.page_size = val;
      this.Sota_searchForm.page = 1;
      await this.loadSotaDetails();
    },

    /* 详情 */
    async handleStoaCurrentChange(val) {
      this.Sota_searchForm.page = val;
      await this.loadSotaDetails();
    },
    /* 详情搜索 */
    handleSotaSearch() {
      this.loadSotaDetails();
    },
    /* 详情重置 */
    resetSotaSearch() {
      this.Sota_searchForm = {
        keyword: "",
        project_id:[]
      };
      this.loadSotaDetails();
    },

    // 加载SOTA汇总表数据
    async loadSotaSummary() {
      try {
        // 这里调用API获取SOTA汇总数据
        const response = await getSotaSummary();
        this.sotaSummaryList = response.data;
      } catch (error) {
        /*  this.$message.error("获取SOTA汇总数据失败");
        console.error(error); */
      }
    },

    // 获取进度状态
    getProgressStatus(progress) {
      if (progress >= 100) {
        return "success";
      }
      return undefined;
    },

    // 处理删除标签按钮点击
    handleRemoveTag(row) {
      this.currentRow = row;
      this.currentRowTags = row.tags || [];
      this.removeTagDialogVisible = true;
      this.removeTagForm = {
        tags: [],
        category_id: "",
      };
      this.fetchCategories();
    },

    // 处理删除标签分类变更
    async handleRemoveTagCategoryChange(categoryId) {
      this.removeTagForm.tags = [];
      const filteredTags = this.currentRowTags.filter(tag => 
        categoryId === "" || tag.category_id === categoryId
      );
      this.currentRowTags = filteredTags;
    },

    // 处理删除标签搜索
    async handleRemoveTagSearch(query) {
      if (query !== "") {
        this.removeTagsLoading = true;
        try {
          const filteredTags = this.currentRowTags.filter(tag => 
            tag.name.toLowerCase().includes(query.toLowerCase())
          );
          this.currentRowTags = filteredTags;
        } catch (error) {
          this.$message.error("搜索标签失败");
        } finally {
          this.removeTagsLoading = false;
        }
      } else {
        this.currentRowTags = this.currentRow.tags || [];
      }
    },

    // 提交删除标签
    async submitRemoveTag() {
      try {
        if (this.removeTagForm.tags.length === 0) {
          this.$message.warning("请选择要删除的标签");
          return;
        }

        const params = {
          literature_ids: [this.currentRow.id],
          tag_ids: this.removeTagForm.tags
        };

        const response = await axios.post(
          `${process.env.VUE_APP_BASE_API}/literature-tags/remove_tags/`,
          params,
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        );

        if (response.status === 200) {
          this.$message.success("标签删除成功");
          this.removeTagDialogVisible = false;
          
          // 更新当前行的标签列表
          this.currentRow.tags = this.currentRow.tags.filter(
            tag => !this.removeTagForm.tags.includes(tag.id)
          );
          
          // 刷新列表
          await this.fetchGpuList();
        }
      } catch (error) {
        this.$message.error(error.response?.data?.message || "标签删除失败");
      }
    },

    // 处理删除项目按钮点击
    handleRemoveProject(row) {
      this.currentRow = row;
      this.currentRowProjects = row.projects || [];
      this.removeProjectDialogVisible = true;
      this.removeProjectForm = {
        projects: [],
      };
    },

    // 提交删除项目
    async submitRemoveProject() {
      try {
        if (this.removeProjectForm.projects.length === 0) {
          this.$message.warning("请选择要删除的项目");
          return;
        }

        const params = {
          literature_ids: [this.currentRow.id],
          project_ids: this.removeProjectForm.projects
        };

        const response = await axios.post(
          `${process.env.VUE_APP_BASE_API}/literature/batch_unassociate_from_projects`,
          params,
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        );

        if (response.status === 200) {
          this.$message.success("项目删除成功");
          this.removeProjectDialogVisible = false;
          
          // 更新当前行的项目列表
          this.currentRow.projects = this.currentRow.projects.filter(
            project => !this.removeProjectForm.projects.includes(project.id)
          );
          
          // 刷新列表
          await this.fetchGpuList();
        }
      } catch (error) {
        this.$message.error(error.response?.data?.message || "项目删除失败");
      }
    },

    // 格式化百分比
    percentFormat(percentage) {
      return `${percentage}%`;
    },
      /*终止 */
      async endAnalysis() {
      try {
        const selectedIds = this.isAllDataSelected
          ? await this.getAllDataIds()
          : Array.from(this.allSelectedRows.keys());
        if (selectedIds.length === 0) {
          this.$message.warning("请选择需要终止的文献");
          return;
        }

        const res = await literEndClear(selectedIds);
        if (res.status === 200) {
          this.$message.success("终止任务成功");
          this.selectedRows = [];
          this.clearSelection();
          
          // 保持当前页码和搜索条件刷新列表
          const currentSearchParams = {
            page: this.currentPage,
            page_size: this.pageSize,
            ...this.searchForm
          };
          await this.fetchGpuList(currentSearchParams);
        }
      } catch (error) {
        this.$message.error("终止任务失败");
        console.error("终止任务错误:", error);
      }
    },
  },
  // 在组件销毁时清理所有轮询
  beforeDestroy() {
    // 清理轮询
    Object.keys(this.pollingTimers).forEach((id) => {
      this.stopPolling(id);
    });
    // 清空选择
    this.clearSelection();
  },
};
</script>

<style lang="scss" scoped>
.gpu-list {
  padding: 20px;
}

.filter-section {
  margin-bottom: 20px;
}

.ml-15 {
  margin-left: 15px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

.status-wrapper {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transition: none !important;
}

.progress-wrapper {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 2px;
  transition: none !important;

  ::v-deep .el-progress {
    line-height: 1;
    transition: none !important;

    .el-progress__text {
      font-size: 12px !important;
      color: inherit;
      transition: none !important;
    }

    .el-progress-circle {
      margin: 0;
      transition: none !important;
    }

    svg {
      transition: none !important;
    }

    .el-progress-circle__track,
    .el-progress-circle__path {
      transition: none !important;
    }
  }
}
</style>