<template>
  <div class="template-location-container" style="padding: 20px 10px">
    <!--  <el-tabs v-model="activeTab" @tab-click="handleTabClick"
      > --><!-- 新增的第二个标签页 -->
    <!--  <el-tab-pane label="文献项目输入表" name="first">
        <div class="project-selector">
          <el-form :inline="true">
            <el-form-item label="当前项目">
              <el-select
                v-model="selectedProjectId"
                placeholder="请选择项目"
                style="width: 300px"
                @change="handleProjectConfirm"
              >
                <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="handleAddGspr"
                v-if="!hasExistingData"
                >创建输入项目</el-button
              >
              <el-button type="primary" @click="handleUpdateGspr" v-else
                >更新输入项目</el-button
              >
              <el-button type="danger" @click="handleDeleteItems"
                >删除</el-button
              >
            </el-form-item>
          </el-form>
        </div>
       
        <template v-if="currentProjectId">
          <div class="operation-bar">
            <el-form :inline="true" :model="gsprSearchForm" class="search-form">
              <el-form-item label="内容">
                <el-input
                  v-model="gsprSearchForm.keyword"
                  placeholder="请输入项目名称/技术报告位置"
                  style="width: 300px"
                  clearable
                />
              </el-form-item>
              <el-form-item label="部门">
                <el-select
                  v-model="gsprSearchForm.department"
                  placeholder="请选择部门"
                  clearable
                >
                  <el-option
                    v-for="(item, index) in departList"
                    :key="index"
                    :label="item.label"
                    :value="item.label"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleGsprSearch"
                  >搜索</el-button
                >
                <el-button @click="handleGsprReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table
            :data="gsprTableData"
            style="width: 100%"
            :default-sort="{ prop: sort_field, order: sort_order }"
            @sort-change="handleSortChange"
          >
            <el-table-column prop="name" label="项目名称" sortable="custom" />
            <el-table-column prop="tech_report_location" label="技术报告位置" />
            <el-table-column prop="department" label="部门" sortable="custom" />
            <el-table-column prop="content" label="内容">
              <template slot-scope="scope">
                <div style="display: flex; align-items: center">
                  <span style="margin-right: 10px">{{
                    scope.row.content
                  }}</span>
                  <i
                    class="el-icon-edit"
                    @click="handleEditContent(scope.row)"
                    style="cursor: pointer; margin-left: 5px"
                  ></i>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button type="primary" @click="handleEditGspr(scope.row)"
                  >编辑</el-button
                >
                <el-button type="danger" @click="handleDeleteGspr(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              @size-change="handleGsprSizeChange"
              @current-change="handleGsprCurrentChange"
              :current-page="gsprPageForm.page"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="gsprPageForm.page_size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="gsprTotal"
            />
          </div>

      
          <el-dialog
            :title="gsprDialogTitle"
            :visible.sync="gsprDialogVisible"
            width="700px"
          >
            <el-form
              :model="gsprForm"
              ref="gsprForm"
              :rules="gsprRules"
              label-width="120px"
            >
              <el-form-item label="名称" prop="name">
                <el-input v-model="gsprForm.name" />
              </el-form-item>
              <el-form-item label="技术报告位置" prop="tech_report_location">
                <el-input v-model="gsprForm.tech_report_location" />
              </el-form-item>

              <el-form-item label="部门" prop="department">
                <el-select
                  v-model="gsprForm.department"
                  placeholder="请选择状态"
                >
                  <el-option
                    v-for="(item, index) in departList"
                    :key="index"
                    :label="item.label"
                    :value="item.label"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="内容" prop="content">
                <el-input
                  type="textarea"
                  v-model="gsprForm.content"
                  :rows="4"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-form>
            <div slot="footer">
              <el-button @click="gsprDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleGsprSubmit"
                >确定</el-button
              >
            </div>
          </el-dialog>
          
          <el-dialog
            title="编辑内容"
            :visible.sync="contentDialogVisible"
            width="600px"
          >
            <el-form :model="contentForm" ref="contentForm">
              <el-form-item label="内容" prop="content">
                <el-input
                  type="textarea"
                  v-model="contentForm.content"
                  :rows="4"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-form>
            <div slot="footer">
              <el-button @click="contentDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleContentSubmit"
                >确定</el-button
              >
            </div>
          </el-dialog>
        </template>

        <el-empty
          v-else
          description="请先选择一个项目"
          :image-size="200"
        ></el-empty>
      </el-tab-pane> -->
    <!-- 第一个标签页 - 原有的模板位置表 -->
    <!--  <el-tab-pane label="模板位置表" name="first"> -->
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <el-form
        :inline="true"
        :model="searchForm"
        class="search-form"
        label-width="100px"
      >
        <el-form-item label="动作类型">
          <!-- <el-input
                v-model="searchForm.action_type"
                placeholder="请输入动作类型"
                clearable
              /> -->
          <el-select
            v-model="searchForm.action_type"
            placeholder="请选择动作类型"
            clearable
          >
            <el-option
              v-for="(item, index) in typeList"
              :key="index"
              :label="item.value"
              :value="item.value"
            />
            <!-- <el-option label="WE" value="WE" /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="模板位置">
          <el-input
            v-model="searchForm.template_location"
            placeholder="请输入模板位置"
            clearable
          />
        </el-form-item>
        <el-form-item label="技术报告位置">
          <el-input
            v-model="searchForm.tech_report_location"
            placeholder="请输入技术报告位置"
            clearable
          />
        </el-form-item>
        <el-form-item label="中间层位置">
          <el-input
            v-model="searchForm.middle_layer_location"
            placeholder="请输入中间层位置"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="handleImport">导入模版位置表</el-button>
      <el-button type="primary" @click="handleExport">导出模版位置表</el-button>
    </div>

    <!-- 数据列表 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="action_type" label="动作类型" width="100" />
      <el-table-column prop="template_location" label="模板位置" />
      <el-table-column prop="middle_layer_location" label="中间层位置" />
      <el-table-column prop="tech_report_location" label="技术报告位置" />
      <el-table-column prop="other_location" label="其他位置" />
      <el-table-column prop="create_time" label="创建时间" width="160" sortable/>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageForm.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageForm.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>
    <!-- </el-tab-pane> -->
    <!--  </el-tabs> -->
    <!-- 添加删除确认对话框 -->
    <el-dialog
      title="删除确认"
      :visible.sync="deleteDialogVisible"
      width="400px"
    >
      <!-- 添加提示信息区域 -->
      <div class="delete-warning" style="margin-bottom: 20px">
        <i
          class="el-icon-warning"
          style="color: #e6a23c; margin-right: 8px"
        ></i>
        <span
          >此操作将永久删除该项目下的所有输入项目，请输入'DELETE'确认删除</span
        >
      </div>

      <el-form
        :model="deleteForm"
        :rules="deleteRules"
        ref="deleteForm"
        label-width="100px"
      >
        <el-form-item label="确认文本" prop="confirmText">
          <el-input
            v-model="deleteForm.confirmText"
            placeholder="请输入'DELETE'"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确认删除</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  
  <script>
import {
  rawSearch,
  export_template,
  rawImport,
  rawList,
  projectList,
  projectAdd,
  departments,
  projectUpdate,
  projectDelete,
  get_action_types,
  create_items,
  delete_items,
  update_items,
} from "@/api/knowledge";
import { searchProject } from "@/api/project";
import axios from "axios";
import { mapState } from "vuex";
export default {
  name: "TemplateLocation",
  data() {
    // 自定义验证规则
    const validateDeleteConfirm = (rule, value, callback) => {
      if (value !== "DELETE") {
        callback(new Error("请输入正确的确认文本"));
      } else {
        callback();
      }
    };
    return {
      tableData: [],
      dialogVisible: false,
      dialogTitle: "",
      form: {
        project_id: "",
        group_name: "",
        project_name: "",
        content: "",
        template_location: "",
        status: "",
      },
      pageForm: {
        page: 1,
        page_size: 30, // 修改默认每页显示数量
      },
      total: 0, // 添加总数据量
      rules: {
        project_id: [
          { required: true, message: "请输入项目ID", trigger: "blur" },
        ],
        group_name: [
          { required: true, message: "请输入组名", trigger: "blur" },
        ],
        project_name: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
      },

      // 新增的数据
      activeTab: "first",
      isSecondTabLoaded: false, // 新增：标记第二个标签页是否已加载
      gsprTableData: [],
      gsprDialogVisible: false,
      gsprDialogTitle: "",
      gsprForm: {
        id: "",
        name: "",
        tech_report_location: "",
        department: "",
        content: "",
        status: 5,
      },
      gsprPageForm: {
        page: 1,
        page_size: 30,
      },
      gsprTotal: 0,
      gsprRules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        tech_report_location: [
          { required: true, message: "请输入技术报告位置", trigger: "blur" },
        ],
        department: [
          { required: true, message: "请输入部门", trigger: "blur" },
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
      },
      departList: [] /* 部门数据 */,
      searchForm: {
        action_type: "",
        template_location: "",
        tech_report_location: "", // 添加技术报告位置字段
        middle_layer_location: "",
      },
      gsprSearchForm: {
        keyword: "",
        department: "",
      },
      /* 动作类型列表 */
      typeList: [],

      contentDialogVisible: false,
      contentForm: {
        id: "",
        content: "",
        name: "",
        department: "",
      },
      /* 排序 */
      sort_field: "name", // 默认排序字段
      sort_order: "desc", // 默认排序方向
      /* 新增项目 */
      selectedProjectId: null, // 新增本地属性来存储选中的项目ID
      projectOptions: [], // 项目选项列表
      gsprSearchForm: {
        keyword: "",
        department: "",
        project_id: null, // 添加项目ID字段
      },
      /* 删除逻辑 */
      deleteDialogVisible: false,
      deleteForm: {
        confirmText: "",
      },
      deleteRules: {
        confirmText: [
          { required: true, message: "请输入确认文本", trigger: "blur" },
          { validator: validateDeleteConfirm, trigger: "blur" },
        ],
      },
      hasExistingData: false, // 添加标记是否有现有数据的属性
    };
  },
  computed: {
    ...mapState("project", ["currentProjectId"]),
  },
  // created 钩子中的修改
  created() {
    // 从 localStorage 恢复项目状态
    const savedProject = localStorage.getItem("currentProject");
    if (savedProject) {
      const { id, name } = JSON.parse(savedProject);
      this.$store.dispatch("project/setCurrentProject", { id, name });
      this.selectedProjectId = id; // 同步设置本地选中状态
    }
  },

  // 添加 watch 来监听 Vuex 中的 currentProjectId 变化
  watch: {
    currentProjectId: {
      immediate: true, // 添加 immediate: true 确保组件创建时就执行
      handler(newVal) {
        if (newVal) {
          this.selectedProjectId = newVal;
          this.gsprSearchForm.project_id = newVal;
          this.fetchGsprData(); // 自动加载数据
        }
      },
    },
  },
  mounted() {
    /* this.fetchProjects(); */
    this.fetchData();
    /*  this.fetchGsprData(); */
    this.init();
  },
  methods: {
    // 处理删除按钮点击
    handleDeleteItems() {
      if (!this.currentProjectId) {
        this.$message.warning("请先选择一个项目");
        return;
      }

      const selectedProject = this.projectOptions.find(
        (p) => p.id === this.currentProjectId
      );

      this.$confirm(
        `您确定要删除项目 "${selectedProject.name}" 的所有输入项目吗？此操作不可恢复。`,
        "警告",
        {
          confirmButtonText: "继续删除",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.deleteForm.confirmText = "";
          this.deleteDialogVisible = true;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 确认删除
    confirmDelete() {
      this.$refs.deleteForm.validate(async (valid) => {
        if (!valid) {
          return false;
        }

        try {
          const loading = this.$loading({
            lock: true,
            text: "正在删除...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });

          const response = await delete_items({
            project_id: this.currentProjectId,
          });

          loading.close();

          if (response.status === 200) {
            this.$message.success("删除成功");
            this.deleteDialogVisible = false;
            // 重新加载数据
            this.fetchGsprData();
          } else {
            this.$message.error(response.message || "删除失败");
          }
        } catch (error) {
          this.$message.error("删除失败：" + (error.message || "未知错误"));
        }
      });
    },
    /* 初始化请求项目列表接口 */
    async fetchProjects() {
      try {
        const response = await searchProject({ page: 1, pageSize: 999 });
        if (response.status === 200) {
          this.projectOptions = response.data.dataList;

          // 如果有当前项目ID但没有选中项目，自动选中
          if (this.currentProjectId && !this.selectedProjectId) {
            this.selectedProjectId = this.currentProjectId;
            this.handleProjectConfirm();
          }
        }
      } catch (error) {
        this.$message.error("获取项目列表失败");
      }
    },

    // 修改 handleProjectConfirm 方法
    handleProjectConfirm() {
      if (!this.selectedProjectId) {
        this.$message.warning("请先选择一个项目");
        return;
      }

      const selectedProject = this.projectOptions.find(
        (p) => p.id === this.selectedProjectId
      );

      if (!selectedProject) {
        this.$message.error("未找到选中的项目");
        return;
      }

      this.$store.dispatch("project/setCurrentProject", {
        id: selectedProject.id,
        name: selectedProject.name,
      });

      // 保存到 localStorage
      localStorage.setItem(
        "currentProject",
        JSON.stringify({
          id: selectedProject.id,
          name: selectedProject.name,
        })
      );

      this.gsprSearchForm.project_id = this.selectedProjectId;
      this.fetchGsprData();
    },

    // 创建项目的方法
    async handleAddGspr() {
      if (!this.currentProjectId) {
        this.$message.warning("请先选择一个项目");
        return;
      }
      const selectedProject = this.projectOptions.find(
        (p) => p.id === this.currentProjectId
      );

      const loading = this.$loading({
        lock: true,
        text: "正在创建项目...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      try {
        const res = await create_items({
          project_id: selectedProject.id,
          project_name: selectedProject.name,
        });

        if (res.status !== 200) {
          throw new Error("创建失败");
        }

        this.$message.success(
          `成功创建 ${res.data.data.created_count} 个输入项目!`
        );
        await this.fetchGsprData();
      } catch (error) {
        this.$message.error("创建失败: " + (error.message || "未知错误"));
      } finally {
        loading.close();
      }
    },

    // 新增更新项目的方法
    async handleUpdateGspr() {
      if (!this.currentProjectId) {
        this.$message.warning("请先选择一个项目");
        return;
      }
      const selectedProject = this.projectOptions.find(
        (p) => p.id === this.currentProjectId
      );

      try {
        await this.$confirm(
          "此操作将更新当前项目的所有输入项目，是否继续？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        const loading = this.$loading({
          lock: true,
          text: "正在更新项目...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });

        try {
          const res = await update_items({
            // 假设有一个update_items的API
            project_id: selectedProject.id,
            project_name: selectedProject.name,
          });

          if (res.status !== 200) {
            throw new Error("更新失败");
          }

          this.$message.success(
            `成功更新 ${res.data.data.updated_count} 个输入项目!`
          );
          await this.fetchGsprData();
        } finally {
          loading.close();
        }
      } catch (error) {
        if (error !== "cancel") {
          this.$message.error("更新失败: " + (error.message || "未知错误"));
        }
      }
    },
    /* 编辑内容 */
    handleEditContent(row) {
      const selectedProject = this.projectOptions.find(
        (p) => p.id === this.currentProjectId
      );
      this.contentForm = {
        project: selectedProject.id,
        project_name: selectedProject.name,
        id: row.id,
        tech_report_location: row.tech_report_location,
        content: row.content,
        name: row.name,
        department: row.department,
      };
      this.contentDialogVisible = true;
    },

    async handleContentSubmit() {
      try {
        await projectUpdate(this.contentForm);
        this.$message.success("内容更新成功");
        this.contentDialogVisible = false;
        this.fetchGsprData();
      } catch (error) {
        this.$message.error("内容更新失败");
      }
    },
    // 第一个表格的搜索方法
    async handleSearch() {
      this.pageForm.page = 1;
      await this.fetchData();
    },

    handleReset() {
      this.searchForm = {
        action_type: "",
        template_location: "",
        tech_report_location: "", // 添加技术报告位置字段
        middle_layer_location: "",
      };
      this.handleSearch();
    },

    // 修改 fetchData 方法，添加搜索参数
    async fetchData() {
      try {
        const params = {
          ...this.pageForm,
          ...this.searchForm,
        };
        const response = await rawList(params);
        if (response.status === 200) {
          this.tableData = response.data.list;
          this.total = response.data.total;
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("获取数据失败");
      }
    },

    // 添加分页方法
    handleSizeChange(val) {
      this.pageForm.page_size = val;
      this.fetchData();
    },

    handleCurrentChange(val) {
      this.pageForm.page = val;
      this.fetchData();
    },

    // 打开新增弹窗
    handleAdd() {
      this.dialogTitle = "新增";
      this.form = {
        project_id: "",
        group_name: "",
        project_name: "",
        content: "",
        template_location: "",
        status: "",
      };
      this.dialogVisible = true;
    },

    async handleImport() {
      try {
        const input = document.createElement("input");
        input.type = "file";
        input.accept = ".xlsx,.xls";

        input.onchange = async (e) => {
          const file = e.target.files[0];
          if (!file) {
            this.$message.warning("请选择文件");
            return;
          }

          // 验证文件类型
          const validTypes = [
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "application/vnd.ms-excel",
          ];
          if (!validTypes.includes(file.type)) {
            this.$message.error("请上传Excel文件(.xlsx或.xls)");
            return;
          }

          // 验证文件大小（例如：10MB限制）
          const maxSize = 10 * 1024 * 1024;
          if (file.size > maxSize) {
            this.$message.error("文件大小不能超过10MB");
            return;
          }

          const formData = new FormData();
          formData.append("file", file);

          // 添加loading
          const loading = this.$loading({
            lock: true,
            text: "正在导入...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });

          try {
            // 使用 axios 直接发送请求
            const response = await axios.post(
              `${process.env.VUE_APP_BASE_API}/project-raw-data/import`,
              formData,
              {
                headers: {
                  "Content-Type": "multipart/form-data",
                },
              }
            );

            loading.close();

            if (response.status === 200) {
              this.$message.success("导入成功");
              this.fetchData();
            } else {
              this.$message.error(response.data.message || "导入失败");
            }
          } catch (error) {
            loading.close();
            this.$message.error(error.response?.data?.message || "导入失败");
          }
        };

        input.click();
      } catch (error) {
        console.error("导入失败:", error);
        this.$message.error(error.response?.data?.message || "导入失败");
      }
    },

    // 添加导出处理方法
    async handleExport() {
      try {
        const response = await export_template();

        // 检查并清理 base64 字符串
        let base64String = response.data.file_content;
        // 移除可能存在的换行符和空格
        base64String = base64String.replace(/[\n\r\s]/g, "");

        // 如果字符串包含引号，需要去除
        if (base64String.startsWith('"') && base64String.endsWith('"')) {
          base64String = base64String.slice(1, -1);
        }

        try {
          // 将 base64 字符串解码为二进制数据
          const binaryString = window.atob(base64String);
          const len = binaryString.length;
          const bytes = new Uint8Array(len);

          for (let i = 0; i < len; i++) {
            bytes[i] = binaryString.charCodeAt(i);
          }

          // 创建 blob 对象
          const blob = new Blob([bytes], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          });

          // 创建下载链接并触发下载
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement("a");
          link.href = url;
          link.download = "模板位置表.xlsx";
          document.body.appendChild(link);
          link.click();

          // 清理
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);

          this.$message.success("导出成功");
        } catch (decodeError) {
          console.error("Base64解码失败:", decodeError);
          console.log("问题字符串:", base64String);
          this.$message.error("文件格式错误");
        }
      } catch (error) {
        console.error("导出失败:", error);
        this.$message.error("导出失败");
      }
    },

    /* 新表 */
    // 新增：处理标签页切换
    handleTabClick(tab) {
      if (tab.name === "second" && !this.isSecondTabLoaded) {
        this.fetchData();
        this.isSecondTabLoaded = false;
      } else {
        this.fetchGsprData();
        this.isSecondTabLoaded = true;
      }
    },
    // 第二个表格的搜索方法
    async handleGsprSearch() {
      this.gsprPageForm.page = 1;
      await this.fetchGsprData();
    },

    handleGsprReset() {
      this.gsprSearchForm = {
        keyword: "",
        department: "",
      };
      this.handleGsprSearch();
    },
    /* 排序 */
    handleSortChange({ prop, order }) {
      this.sort_field = prop;
      // 将 Element UI 的排序值转换为 API 需要的格式
      this.sort_order = order === "ascending" ? "asc" : "desc";
      // 如果排序被取消，设置默认值
      if (!order) {
        this.sort_field = "name";
        this.sort_order = "desc";
      }
      // 这里可以调用接口重新获取排序后的数据
      this.fetchGsprData();
    },
    // 修改 fetchGsprData 方法，添加搜索参数
    async fetchGsprData() {
      if (!this.currentProjectId) {
        return; // 如果没有选择项目，直接返回
      }

      const loading = this.$loading({
        lock: true,
        text: "加载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      try {
        const params = {
          sort_field: this.sort_field,
          sort_order: this.sort_order,
          project_id: this.currentProjectId,
          ...this.gsprPageForm,
          ...this.gsprSearchForm,
        };
        const response = await projectList(params);
        if (response.status === 200) {
          this.gsprTableData = response.data.list;
          this.gsprTotal = response.data.total;
          this.hasExistingData = this.gsprTotal > 0;
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("获取数据失败");
      } finally {
        loading.close();
      }
    },

    // GSPR分页处理
    handleGsprSizeChange(val) {
      this.gsprPageForm.page_size = val;
      this.fetchGsprData();
    },

    handleGsprCurrentChange(val) {
      this.gsprPageForm.page = val;
      this.fetchGsprData();
    },

    // GSPR表单操作
    /* handleAddGspr() {
      this.gsprDialogTitle = "新增文献项目";
      this.gsprForm = {
        name: "",
        tech_report_location: "",
        department: "",
        status: 5,
      };
      this.gsprDialogVisible = true;
    }, */

    handleEditGspr(row) {
      this.gsprDialogTitle = "编辑文献项目";
      this.gsprForm = { ...row };
      console.log(this.gsprForm);
      this.gsprDialogVisible = true;
    },

    async handleDeleteGspr(row) {
      try {
        await this.$confirm("确认删除该记录?", "提示", {
          type: "warning",
        });
        // 替换为实际的删除API调用
        await projectDelete({ id: row.id });
        this.$message.success("删除成功");
        this.fetchGsprData();
      } catch (error) {
        if (error !== "cancel") {
          this.$message.error("删除失败");
        }
      }
    },

    async handleGsprSubmit() {
      try {
        await this.$refs.gsprForm.validate();
        // 替换为实际的保存API调用
        if (this.gsprForm.id) {
          await projectUpdate(this.gsprForm);
        } else {
          await projectAdd(this.gsprForm);
        }
        this.$message.success(this.gsprForm.id ? "更新成功" : "创建成功");
        this.gsprDialogVisible = false;
        this.fetchGsprData();
      } catch (error) {
        if (error !== false) {
          this.$message.error("保存失败");
        }
      }
    },
    /* 加载初始化数据 */
    init() {
      departments().then((res) => {
        if (res.status !== 200) return;
        this.departList = res.data.departments;
      });
      get_action_types().then((res) => {
        if (res.status !== 200) return;
        this.typeList = res.data.action_types;
      });
    },
  },
};
</script>
  
  <style scoped>
.project-selector {
  margin-bottom: 20px;
}
/* .el-form-item {
  margin-bottom: 0;
} */
.template-location-container {
  padding: 20px;
}
.operation-bar {
  margin-bottom: 20px;
}
.pagination-container {
  display: flex;
  justify-content: end;
}
.delete-warning {
  padding: 12px 16px;
  background-color: #fdf6ec;
  border-radius: 4px;
  color: #e6a23c;
  line-height: 1.4;
  font-size: 14px;
  display: flex;
  align-items: center;
}
::v-deep .el-tabs__nav-wrap::after {
  width: 13%;
}
</style>