<!-- 项目输入页面 -->
<template>
  <div class="project-input-container">
    <!-- 从原代码中移动第一个 tab-pane 的内容 -->
    <div class="project-selector">
      <el-form :inline="true">
        <el-form-item label="当前项目">
          <el-select
            disabled
            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>
    <!-- 使用 v-if 控制其余内容的显示 -->
    <template v-if="selectedProjectId">
      <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 label="创建时间">
            <el-date-picker
              v-model="gsprSearchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
            />
          </el-form-item>
          <!-- 添加内容状态筛选 -->
          <el-form-item label="内容状态">
            <el-select
              v-model="gsprSearchForm.content_empty"
              placeholder="请选择"
              clearable
            >
              <!-- <el-option label="请选择状态" value="null" /> -->
              <el-option label="有内容" :value="false" />
              <el-option label="无内容" :value="true" />
            </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>
      <div>
        <el-button type="primary" @click="handleExport">导出输入项目</el-button>
        <!-- <el-button type="primary" @click="handleDocViewGspr"
          >文档预览</el-button
        > -->
      </div>
      <el-table
        :data="gsprTableData"
        style="width: 100%"
        :default-sort="{ prop: sort_field, order: sort_order }"
        @sort-change="handleSortChange"
      >
        <el-table-column
          prop="sequence"
          label="排序"
          sortable
          width="80"
        >
          <template slot-scope="scope">
            <div style="display: flex; align-items: center">
              <span style="margin-right: 10px">{{ scope.row.sequence }}</span>
              <i
                class="el-icon-edit"
                @click="handleEditSequence(scope.row)"
                style="cursor: pointer; margin-left: 5px"
              ></i>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="项目名称" sortable />
        <el-table-column prop="tech_report_location" label="技术报告位置" />
        <el-table-column prop="department" label="部门" sortable />
        <el-table-column prop="content" label="内容" width="450">
          <template slot-scope="scope">
            <div class="content-cell">
             <!--  <el-tooltip
                placement="top-start"
                :disabled="!scope.row.content"
                popper-class="custom-tooltip"
              >
                <template slot="content">
                  <div
                    class="tooltip-content"
                    style="color: #fff !important"
                    v-html="scope.row.content"
                  ></div>
                </template>
                
              </el-tooltip> -->
              <span class="content-text">{{
                  getPlainText(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 prop="" label="难度" sortable>
          <template slot-scope="scope">
            <el-rate
              v-model="scope.row.score"
              show-score
              text-color="#ff9900"
              score-template="{value}"
              @change="(value) => rateScope(value, scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="备注" width="200">
          <template slot-scope="scope">
            <div style="display: flex; align-items: center">
              <span style="margin-right: 10px">{{ scope.row.remarks }}</span>
              <i
                class="el-icon-edit"
                @click="handleEditRemark(scope.row)"
                style="cursor: pointer; margin-left: 5px"
              ></i>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" @click="handleViewGspr(scope.row)"
              >查看</el-button
            >
            <!--   <el-button type="primary" @click="handleDocViewGspr(scope.row)"
              >文档预览</el-button
            > -->
            <!--   <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> -->

      <!-- GSPR表单弹窗 -->
      <el-dialog
        :title="gsprDialogTitle"
        :visible.sync="gsprDialogVisible"
        :close-on-click-modal="false"
        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">
            <div class="editor-area sticky-editor">
              <ckeditor
                ref="editor"
                v-model="gsprForm.content"
                :config="editorConfig"
                :editorUrl="editorUrl"
              ></ckeditor>
            </div>
          </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"
        :close-on-click-modal="false"
        width="80%"
      >
        <!--  <el-form :model="contentForm" ref="contentForm">
          <el-form-item label="内容" prop="content"> -->
        <!-- <el-inputwidth="600px"
              type="textarea"
              v-model="contentForm.content"
              :rows="4"
              placeholder="请输入内容"
            /> -->
        <!-- <ckeditor
          ref="editor"
          v-model="contentForm.content"
          :config="editorConfig"
          :editorUrl="editorUrl"
        ></ckeditor> -->
        <CanvasEditor
          ref="wordEditor"
          :edit-mode="Modetype"
          :html-data="htmlData"
          :doc-json="docJson"
          :key="keys"
          @save="save"
          @is-save="getSave"
        ></CanvasEditor>
        <!--   </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>
      <!-- 查看弹窗 -->
      <el-dialog
        title="查看详情"
        :visible.sync="viewDialogVisible"
        :close-on-click-modal="false"
        width="80%"
      >
        <div class="view-details">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="项目名称">{{
              viewForm.name
            }}</el-descriptions-item>
            <el-descriptions-item label="技术报告位置">{{
              viewForm.tech_report_location
            }}</el-descriptions-item>
            <el-descriptions-item label="部门">{{
              viewForm.department
            }}</el-descriptions-item>
            <el-descriptions-item label="难度">
              <el-rate
                v-model="viewForm.score"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
              />
            </el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">{{
              viewForm.remarks || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="内容" :span="2">
              <div class="content-view" v-html="viewForm.content || '-'"></div>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-dialog>
      <!-- 添加文档预览对话框 -->
      <el-dialog
        title="文档预览"
        :visible.sync="docPreviewDialogVisible"
        :close-on-click-modal="false"
        width="65%"
        class="doc-preview-dialog"
      >
        <div class="doc-preview-header">
          <span>当前文档:</span>
          <el-select
            v-model="docPreviewSel"
            placeholder="请选择文档"
            style="width: 300px"
            @change="handleDocPreviewChange"
          >
            <el-option
              v-for="doc in boundTemplateList"
              :key="doc.id"
              :label="doc.title"
              :value="doc"
            />
          </el-select>
        </div>
        <div class="doc-preview-content" v-loading="previewLoading">
          <div v-if="previewContent" v-html="previewContent"></div>
          <el-empty v-else description="请选择要预览的文档"></el-empty>
        </div>
      </el-dialog>
    </template>

    <!-- 未选择项目时显示提示 -->
    <el-empty
      v-else
      description="请先选择一个项目"
      :image-size="200"
    ></el-empty>

    <!-- 添加删除确认对话框 -->
    <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>
    <!-- 其余第一个tab的内容... -->
    <!-- 修改序号 -->
    <el-dialog
      :visible.sync="dialogVisible"
      title="修改序号"
      width="30%"
      :close-on-click-modal="false"
      append-to-body
      v-el-drag-dialog
    >
      <el-form :model="sequenceForm" label-width="80px">
        <el-form-item label="序号">
          <el-input-number
            v-model="sequenceForm.sequence"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSequence">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 添加备注编辑对话框 -->
    <el-dialog
      title="编辑备注"
      :visible.sync="remarkDialogVisible"
      :close-on-click-modal="false"
      width="500px"
    >
      <el-form :model="remarkForm">
        <el-form-item label="备注">
          <el-input
            type="textarea"
            v-model="remarkForm.remarks"
            :rows="4"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="remarkDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRemarkSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
import {
  projectList,
  projectAdd,
  departments,
  projectUpdate,
  projectDelete,
  create_items,
  delete_items,
  update_items,
  rateScope,
  sequence,
} from "@/api/knowledge";
import {
  searchProject,
  exportItems,
  getProjectInfo,
  searchTemplateList,
} from "@/api/project";
import { mapState } from "vuex";
import CKEditor from "ckeditor4-vue";
import axios from "axios";
import elDragDialog from "@/directive/el-drag-dialog";
import CanvasEditor from "@/components/CanvasEditor/index"; // 确保路径正确
export default {
  name: "ProjectInput",
  components: {
    CanvasEditor, // 使用驼峰式注册
    // 或者使用短横线式注册
    // 'canvas-editor': CanvasEditor,
  },
  directives: { elDragDialog },
  data() {
    // 自定义验证规则
    const validateDeleteConfirm = (rule, value, callback) => {
      if (value !== "DELETE") {
        callback(new Error("请输入正确的确认文本"));
      } else {
        callback();
      }
    };
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 1);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      selectedProjectId: null,
      projectOptions: [],
      gsprTableData: [],
      gsprSearchForm: {
        keyword: "",
        department: "",
        project_id: null,
        dateRange: [], // 添加时间范围
        content_empty: null, // 添加内容状态
      },
      gsprPageForm: {
        page: 1,
        page_size: 30,
        /*  sort_field:'sequence',
        sort_order:"asc", */
      },
      gsprTotal: 0,
      departList: [],
      sort_field: "sequence",
      sort_order: "asc",
      hasExistingData: false,
      gsprDialogVisible: false,
      gsprDialogTitle: "",
      gsprForm: {
        id: "",
        name: "",
        tech_report_location: "",
        department: "",
        content: "",
        status: 5,
      },
      gsprPageForm: {
        page: 1,
        page_size: 999,
      },
      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" }],
      },

      contentDialogVisible: false,
      contentForm: {
        id: "",
        content: "",
        name: "",
        department: "",
      },
      /* 删除逻辑 */
      deleteDialogVisible: false,
      deleteForm: {
        confirmText: "",
      },
      deleteRules: {
        confirmText: [
          { required: true, message: "请输入确认文本", trigger: "blur" },
          { validator: validateDeleteConfirm, trigger: "blur" },
        ],
      },
      editorUrl: "/ckeditor/ckeditor.js",
      editorConfig: {
        language: "zh-cn",
        height: "300px",
      },
      dialogVisible: false,
      sequenceForm: {
        sequence: 1,
        id: null,
      },
      remarkDialogVisible: false,
      remarkForm: {
        id: "",
        remarks: "",
      },
      /* 已绑定项目 */
      documentIds: [],
      templateLocations: [], // 存储传递过来的位置信息
      matchedContents: {}, // 存储技术报告位置匹配的内容

      Modetype: "edit",
      htmlData: "", // 编辑器html数据
      docJson: null, // 编辑器getValue数据
      keys: new Date().getTime(), // 给编辑器赋值不刷新的时候，改变key

      /* 查看 */
      viewDialogVisible: false,
      viewForm: {
        name: "",
        tech_report_location: "",
        department: "",
        score: 0,
        remarks: "",
        content: "",
      },
      /* 文档预览 */
      docPreviewDialogVisible: false,
      previewData: {
        name: "",
        tech_report_location: "",
        interpretation: "",
        content: "",
      },
      /* 文档列表 */
      boundTemplateList: [],
      docPreviewSel: "",
      previewLoading: false,
      previewContent: "",
    };
  },
  mounted() {
    this.fetchProjects().then(() => {
      // Get project ID from URL query parameter
      const urlProjectId = this.$route.query.id;
      if (urlProjectId) {
        this.selectedProjectId = parseInt(urlProjectId);
        this.handleProjectConfirm();
      }
    });

    // 获取并处理传递过来的模板位置数据
    const projectDataStr = this.$route.query.projectData;
    if (projectDataStr) {
      try {
        const projectData = JSON.parse(decodeURIComponent(projectDataStr));
        this.templateLocations = projectData.locations;

        // 创建位置到内容的映射
        this.matchedContents = this.templateLocations.reduce((acc, loc) => {
          if (loc.type === "template_location") {
            // 移除位置标记中的括号以便匹配
            const cleanLocation = loc.tech_report_location;
            acc[cleanLocation] = loc;
          }

          return acc;
        }, {});
      } catch (error) {
        console.error("解析项目数据失败:", error);
      }
    }
    this.init();
  },

  methods: {
    /* 当前文档选择 */
    // 处理文档选择变化
    async handleDocPreviewChange(docId) {
      if (!docId) {
        this.previewContent = "";
        return;
      }

      this.previewLoading = true;
      try {
        const docData=JSON.parse(docId.data)
        // 假设这是获取文档预览内容的API
        this.previewContent=docData[0].content
      } catch (error) {
        this.$message.error(
          "获取文档预览失败：" + (error.message || "未知错误")
        );
        this.previewContent = "";
      } finally {
        this.previewLoading = false;
      }
    },
    /* 处理文字 */
    getPlainText(html) {
      if (!html) return "";

      // 创建临时 DOM 元素来解析 HTML
      const temp = document.createElement("div");
      temp.innerHTML = html;

      // 获取纯文本内容
      const plainText = temp.textContent || temp.innerText;

      // 截断文本
      return plainText.length > 50
        ? plainText.substring(0, 50) + "..."
        : plainText;
    },
    // 添加 CanvasEditor 相关的方法
    save(data) {
      // 处理保存逻辑
      console.log("保存数据:", data);
      // 这里可以添加具体的保存实现
    },

    getSave(isSaved) {
      // 处理保存状态
      console.log("是否已保存:", isSaved);
      // 这里可以添加保存状态的处理逻辑
    },

    // 修改 handleEditContent 方法，添加编辑器数据的处理
    handleEditContent(row) {
      const selectedProject = this.projectOptions.find(
        (p) => p.id === this.selectedProjectId
      );

      // 处理 content 内容，将文本格式转换为 HTML 并清理空样式
      const processedContent = this.cleanEmptyStyles(
        this.convertTextToHtml(row.content)
      );

      this.contentForm = {
        sequence: row.sequence,
        project: selectedProject.id,
        project_name: selectedProject.name,
        id: row.id,
        tech_report_location: row.tech_report_location,
        content: row.content, //processedContent,
        name: row.name,
        department: row.department,
      };

      // 设置编辑器数据
      this.htmlData = processedContent;
      this.Modetype = "edit";
      this.keys = new Date().getTime(); // 强制刷新编辑器

      this.contentDialogVisible = true;
    },

    // 修改 handleContentSubmit 方法
    async handleContentSubmit() {
      try {
        // 获取编辑器的最新内容
        const editorContent = this.$refs.wordEditor.editorRef.command.getHTML();

        // 更新 contentForm
        this.contentForm.content = editorContent.main;
        // 处理富文本内容
        const processContent = (htmlContent) => {
          /* const tempDiv = document.createElement("div");
          tempDiv.innerHTML = htmlContent;

          // 处理图片：保留样式属性
          const images = tempDiv.getElementsByTagName("img");
          Array.from(images).forEach((img) => {
            const style = img.getAttribute("style") || "";
            const className = img.getAttribute("class") || "";
            const imgPlaceholder = `[图片:${img.src}|style=${style}|class=${className}]`;
            img.replaceWith(document.createTextNode(imgPlaceholder));
          });

          // 处理表格：保留完整的样式属性，包括边框
          const tables = tempDiv.getElementsByTagName("table");
          Array.from(tables).forEach((table) => {
            const tableStyle = table.getAttribute("style") || "";
            const tableClass = table.getAttribute("class") || "";
            const tableBorder = table.getAttribute("border") || "";

            const rows = Array.from(table.rows).map((row) => {
              return Array.from(row.cells)
                .map((cell) => {
                  const cellStyle = cell.getAttribute("style") || "";
                  const cellClass = cell.getAttribute("class") || "";
                  const cellBorder = cell.getAttribute("border") || "";
                  const content = cell.textContent.trim();

                  // 合并所有样式属性
                  const cellStyles = [
                    cellStyle,
                    cellBorder ? `border: ${cellBorder}px solid #000;` : "",
                  ]
                    .filter(Boolean)
                    .join(" ");

                  return `${content}${
                    cellStyles || cellClass
                      ? `[style=${cellStyles}|class=${cellClass}]`
                      : ""
                  }`;
                })
                .join("|");
            });

            // 合并表格的样式属性
            const tableStyles = [
              tableStyle,
              tableBorder ? `border: ${tableBorder}px solid #000;` : "",
            ]
              .filter(Boolean)
              .join(" ");

            const tablePlaceholder = `[表格|style=${tableStyles}|class=${tableClass}]\n${rows.join(
              "\n"
            )}`;
            table.replaceWith(document.createTextNode(tablePlaceholder));
          });

          // 处理文本样式
          const styledSpans = tempDiv.getElementsByTagName("span");
          Array.from(styledSpans).forEach((span) => {
            const style = span.getAttribute("style") || "";
            const className = span.getAttribute("class") || "";
            if (style || className) {
              const content = span.textContent;
              span.replaceWith(
                document.createTextNode(
                  `[文本:${content}|style=${style}|class=${className}]`
                )
              );
            }
          });

          return tempDiv.textContent || tempDiv.innerText; */
        };

        const submitData = {
          ...this.contentForm,
          content: this.contentForm.content, //processContent(this.contentForm.content),
        };
        await projectUpdate(submitData);
        this.$message.success("内容更新成功");
        this.contentDialogVisible = false;
        this.fetchGsprData();
      } catch (error) {
        this.$message.error("内容更新失败");
      }
    },

    // 修改现有的 handleEditRemark 方法
    handleEditRemark(row) {
      // 只复制需要的字段
      this.remarkForm = {
        id: row.id,
        remarks: row.remarks || "",
        sequence: row.sequence,
        project: row.project,
        content: row.content,
        status: row.status,
        // 保留其他必要字段，但不包含 score
        name: row.name,
        tech_report_location: row.tech_report_location,
        department: row.department,
        content: row.content,
      };
      this.remarkDialogVisible = true;
    },

    // 修改备注提交方法
    async handleRemarkSubmit() {
      try {
        // 只更新必要的字段
        const updateData = {
          ...this.remarkForm,
          remarks: this.remarkForm.remarks,
        };

        await projectUpdate(updateData);
        this.$message.success("备注更新成功");
        this.remarkDialogVisible = false;
        this.fetchGsprData();
      } catch (error) {
        this.$message.error("备注更新失败");
      }
    },
    /* 修改评分 */
    async rateScope(value, row) {
      try {
        const response = await rateScope({
          id: row.id,
          score: value,
        });

        if (response.status === 200) {
          this.$message.success("评分更新成功");
          // 更新本地数据
          const index = this.gsprTableData.findIndex(
            (item) => item.id === row.id
          );
          if (index !== -1) {
            this.gsprTableData[index].score = value;
          }
        } else {
          throw new Error(response.message || "评分更新失败");
        }
      } catch (error) {
        this.$message.error(error.message || "评分更新失败");
        // 恢复原始评分
        row.score = row.score || 0;
      }
    },
    /* 修改序号 */
    handleEditSequence(row) {
      this.sequenceForm.sequence = row.sequence;
      this.sequenceForm.id = row.id;
      this.dialogVisible = true;
    },
    // 提交序号修改
    async submitSequence() {
      try {
        await sequence({
          id: this.sequenceForm.id,
          new_sequence: this.sequenceForm.sequence,
        });
        this.$message.success("修改序号成功");
        this.dialogVisible = false;
        // 重新加载数据
        this.fetchGsprData();
      } catch (error) {
        this.$message.error("修改序号失败：" + error.message);
      }
    },

    /* 项目导出 */
    async handleExport() {
      const loading = this.$loading({
        lock: true,
        text: "导出中...",
      });

      try {
        const response = await axios({
          url: `${process.env.VUE_APP_BASE_API}/project-input/export`,
          method: "post",
          data: { project_id: this.selectedProjectId },
          headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + localStorage.getItem("token"), // 根据实际token获取方式调整
          },
        });
        // 检查响应数据
        if (
          !response.data ||
          !response.data.data ||
          !response.data.data.data.file_content
        ) {
          throw new Error("导出失败：返回数据格式错误");
        }

        // 获取文件内容和文件名
        const { file_content, file_name } = response.data.data.data;

        // 将base64转换为blob
        const byteCharacters = atob(file_content);
        const byteNumbers = new Array(byteCharacters.length);
        for (let i = 0; i < byteCharacters.length; i++) {
          byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        const blob = new Blob([byteArray], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });

        // 下载文件
        const link = document.createElement("a");
        link.href = window.URL.createObjectURL(blob);
        link.download = file_name;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(link.href);

        this.$message.success(response.data.message || "导出成功");
      } catch (error) {
        console.error("导出错误:", error);
        let errorMessage = "导出失败，请稍后重试";

        if (error.response) {
          switch (error.response.status) {
            case 401:
              errorMessage = "导出失败：未授权，请重新登录";
              break;
            case 403:
              errorMessage = "导出失败：没有导出权限";
              break;
            case 404:
              errorMessage = "导出失败：导出接口不存在";
              break;
            case 500:
              errorMessage = "导出失败：服务器内部错误";
              break;
            default:
              errorMessage = `导出失败：${error.response.status}`;
          }
        }

        this.$message.error(errorMessage);
      } finally {
        loading.close();
      }
    },
    /* 删除 */
    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 handleDocViewGspr(row) {
      try {
        const loading = this.$loading({
          lock: true,
          text: "加载文档预览...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        searchTemplateList({ ids: this.documentIds.join(",") || 0 }).then(
          (res) => {
            if (res.status !== 200) return;
            this.boundTemplateList = res.data;
            loading.close();
            this.docPreviewDialogVisible = true;
          }
        );
      } catch (error) {
        loading.close();
        this.$message.error(
          "获取文档预览失败：" + (error.message || "未知错误")
        );
      }
    },

    /* 查看 */
    handleViewGspr(row) {
      this.viewForm = {
        name: row.name,
        tech_report_location: row.tech_report_location,
        department: row.department,
        score: row.score || 0,
        remarks: row.remarks,
        content: row.content,
      };

      this.viewDialogVisible = true;
    },
    /* 编辑 */
    handleEditGspr(row) {
      this.gsprDialogTitle = "编辑文献项目";
      this.gsprForm = { ...row };
      this.gsprDialogVisible = true;
    },
    /*  // 修改编辑内容显示方法
    handleEditContent(row) {
      const selectedProject = this.projectOptions.find(
        (p) => p.id === this.selectedProjectId
      );

      // 处理content内容，将文本格式转换为HTML并清理空样式
      const processedContent = this.cleanEmptyStyles(
        this.convertTextToHtml(row.content)
      );

      this.contentForm = {
        sequence: row.sequence,
        project: selectedProject.id,
        project_name: selectedProject.name,
        id: row.id,
        tech_report_location: row.tech_report_location,
        content: processedContent,
        name: row.name,
        department: row.department,
      };
      this.contentDialogVisible = true;
    }, */

    // 修改回显方法，解析样式
    convertTextToHtml(text) {
      if (!text) return "";

      let html = text;

      // 处理表格标记（包含边框样式）
      html = html.replace(
        /\[表格\|style=(.*?)\|class=(.*?)\]([\s\S]*?)(?=\[|$)/g,
        (match, tableStyle, tableClass, tableContent) => {
          const rows = tableContent.trim().split("\n");
          let tableHtml = `<table style="${tableStyle}" class="${tableClass}">`;

          rows.forEach((row) => {
            tableHtml += "<tr>";
            const cells = row.split("|").map((cell) => {
              const cellMatch = cell.match(
                /(.*?)(?:\[style=(.*?)\|class=(.*?)\])?$/
              );
              if (cellMatch) {
                const [_, content, style = "", className = ""] = cellMatch;
                return `<td style="${style}" class="${className}">${content.trim()}</td>`;
              }
              return `<td>${cell.trim()}</td>`;
            });
            tableHtml += cells.join("") + "</tr>";
          });

          tableHtml += "</table>";
          return tableHtml;
        }
      );

      // 2. 处理图片标记（保持不变）
      html = html.replace(
        /\[图片:(.*?)\|style=(.*?)\|class=(.*?)\]/g,
        (match, src, style, className) => {
          return `<img src="${src}" alt="图片" style="${style}" class="${className}">`;
        }
      );

      // 3. 处理文本样式（保持不变）
      html = html.replace(
        /\[文本:(.*?)\|style=(.*?)\|class=(.*?)\]/g,
        (match, content, style, className) => {
          return `<span style="${style}" class="${className}">${content}</span>`;
        }
      );

      // 4. 处理换行
      html = html.replace(/\n/g, "<br>");

      return html;
    },

    // 添加辅助方法：清理空样式属性
    cleanEmptyStyles(html) {
      return html
        .replace(/style=""/g, "")
        .replace(/class=""/g, "")
        .replace(/\s+>/g, ">");
    },
    /*  */
    /*   async handleContentSubmit() {
      try {
        // 创建一个函数来处理富文本内容，保留样式
        const processContent = (htmlContent) => {
          const tempDiv = document.createElement("div");
          tempDiv.innerHTML = htmlContent;

          // 处理图片：保留样式属性
          const images = tempDiv.getElementsByTagName("img");
          Array.from(images).forEach((img) => {
            const style = img.getAttribute("style") || "";
            const className = img.getAttribute("class") || "";
            const imgPlaceholder = `[图片:${img.src}|style=${style}|class=${className}]`;
            img.replaceWith(document.createTextNode(imgPlaceholder));
          });

          // 处理表格：保留完整的样式属性，包括边框
          const tables = tempDiv.getElementsByTagName("table");
          Array.from(tables).forEach((table) => {
            const tableStyle = table.getAttribute("style") || "";
            const tableClass = table.getAttribute("class") || "";
            const tableBorder = table.getAttribute("border") || "";

            const rows = Array.from(table.rows).map((row) => {
              return Array.from(row.cells)
                .map((cell) => {
                  const cellStyle = cell.getAttribute("style") || "";
                  const cellClass = cell.getAttribute("class") || "";
                  const cellBorder = cell.getAttribute("border") || "";
                  const content = cell.textContent.trim();

                  // 合并所有样式属性
                  const cellStyles = [
                    cellStyle,
                    cellBorder ? `border: ${cellBorder}px solid #000;` : "",
                  ]
                    .filter(Boolean)
                    .join(" ");

                  return `${content}${
                    cellStyles || cellClass
                      ? `[style=${cellStyles}|class=${cellClass}]`
                      : ""
                  }`;
                })
                .join("|");
            });

            // 合并表格的样式属性
            const tableStyles = [
              tableStyle,
              tableBorder ? `border: ${tableBorder}px solid #000;` : "",
            ]
              .filter(Boolean)
              .join(" ");

            const tablePlaceholder = `[表格|style=${tableStyles}|class=${tableClass}]\n${rows.join(
              "\n"
            )}`;
            table.replaceWith(document.createTextNode(tablePlaceholder));
          });

          // 处理文本样式
          const styledSpans = tempDiv.getElementsByTagName("span");
          Array.from(styledSpans).forEach((span) => {
            const style = span.getAttribute("style") || "";
            const className = span.getAttribute("class") || "";
            if (style || className) {
              const content = span.textContent;
              span.replaceWith(
                document.createTextNode(
                  `[文本:${content}|style=${style}|class=${className}]`
                )
              );
            }
          });

          return tempDiv.textContent || tempDiv.innerText;
        };

        const submitData = {
          ...this.contentForm,
          content: processContent(this.contentForm.content),
        };

        await projectUpdate(submitData);
        this.$message.success("内容更新成功");
        this.contentDialogVisible = false;
        this.fetchGsprData();
      } catch (error) {
        this.$message.error("内容更新失败");
      }
    }, */

    // 同样修改handleGsprSubmit方法
    async handleGsprSubmit() {
      try {
        await this.$refs.gsprForm.validate();

        // 处理富文本内容
        const processContent = (htmlContent) => {
          const tempDiv = document.createElement("div");
          tempDiv.innerHTML = htmlContent;

          // 处理图片
          const images = tempDiv.getElementsByTagName("img");
          Array.from(images).forEach((img) => {
            const imgPlaceholder = `[图片:${img.src}]`;
            img.replaceWith(document.createTextNode(imgPlaceholder));
          });

          // 处理表格
          const tables = tempDiv.getElementsByTagName("table");
          Array.from(tables).forEach((table) => {
            const rows = Array.from(table.rows).map((row) =>
              Array.from(row.cells)
                .map((cell) => cell.textContent.trim())
                .join(" | ")
            );
            const tablePlaceholder = "[表格]\n" + rows.join("\n");
            table.replaceWith(document.createTextNode(tablePlaceholder));
          });

          return tempDiv.textContent || tempDiv.innerText;
        };

        // 创建新对象避免修改原始数据
        const submitData = {
          ...this.gsprForm,
          content: processContent(this.gsprForm.content),
        };

        if (this.gsprForm.id) {
          await projectUpdate(submitData);
        } else {
          await projectAdd(submitData);
        }

        this.$message.success(this.gsprForm.id ? "更新成功" : "创建成功");
        this.gsprDialogVisible = false;
        this.fetchGsprData();
      } catch (error) {
        if (error !== false) {
          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("保存失败");
        }
      }
    },
    /* 初始化项目列表 */
    async fetchProjects() {
      try {
        const response = await searchProject({ page: 1, pageSize: 999 });
        if (response.status === 200) {
          this.projectOptions = response.data.dataList;

          // 如果有当前项目ID但没有选中项目，自动选中
          // 如果有当前项目ID但没有选中项目，自动选中
          if (!this.selectedProjectId && this.$route.query.id) {
            this.selectedProjectId = parseInt(this.$route.query.id);
            this.handleProjectConfirm();
          }
        }
      } catch (error) {
        this.$message.error("获取项目列表失败");
      }
    },
    async 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.setItem(
        "currentProject",
        JSON.stringify({
          id: selectedProject.id,
          name: selectedProject.name,
        })
      );

      this.gsprSearchForm.project_id = this.selectedProjectId;
      this.fetchGsprData();
    },
    // 创建项目
    async handleAddGspr() {
      if (!this.selectedProjectId) {
        this.$message.warning("请先选择一个项目");
        return;
      }

      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: this.selectedProjectId,
          project_name: this.projectOptions.find(
            (p) => p.id === this.selectedProjectId
          ).name,
        });

        if (res.status === 200) {
          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.selectedProjectId) {
        this.$message.warning("请先选择一个项目");
        return;
      }
      const selectedProject = this.projectOptions.find(
        (p) => p.id === this.selectedProjectId
      );

      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 || "未知错误"));
        }
      }
    },

    // 删除项目
    async handleDeleteItems() {
      if (!this.selectedProjectId) {
        this.$message.warning("请先选择一个项目");
        return;
      }

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

      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.selectedProjectId,
          });

          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 fetchGsprData() {
      if (!this.selectedProjectId) {
        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.selectedProjectId,
          ...this.gsprPageForm,
          ...this.gsprSearchForm,
          start_date: this.gsprSearchForm.dateRange?.[0] || null,
          end_date: this.gsprSearchForm.dateRange?.[1] || null,
        };
        delete params.dateRange;

        const response = await projectList(params);

        if (response.status === 200) {
          // 只保留匹配的数据
          this.gsprTableData = response.data.list
            .filter((item) => {
              // 移除括号以进行匹配
              const cleanLocation = item.tech_report_location;
              return this.matchedContents[cleanLocation];
            })
            .map((item) => {
              const cleanLocation = item.tech_report_location;
              const matchedContent = this.matchedContents[cleanLocation];
              return {
                ...item,
                score: typeof item.score === "number" ? item.score : 0,
                matched_content: matchedContent?.content || null,
                raw_content: matchedContent?.raw_content || null,
                input_items: matchedContent?.input_items || [],
              };
            });
          // 更新总数为过滤后的数量
          this.gsprTotal = this.gsprTableData.length;
          this.hasExistingData = this.gsprTotal > 0;

          // 如果当前页没有数据但总数大于0，回到第一页
          if (this.gsprTableData.length === 0 && this.gsprTotal > 0) {
            this.gsprPageForm.page = 1;
            this.fetchGsprData();
          }
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("获取数据失败");
      } finally {
        loading.close();
      }
    },

    // 添加一个辅助方法来检查位置是否匹配
    isLocationMatched(location) {
      if (!location) return false;
      const cleanLocation = location.replace(/[\[\]【】]/g, "");
      return !!this.matchedContents[cleanLocation];
    },

    handleGsprSizeChange(val) {
      this.gsprPageForm.page_size = val;
      this.fetchGsprData();
    },

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

    // 搜索相关
    handleGsprSearch() {
      this.gsprPageForm.page = 1;
      this.fetchGsprData();
    },

    handleGsprReset() {
      this.gsprSearchForm = {
        keyword: "",
        department: "",
        project_id: this.selectedProjectId,
        dateRange: [], // 重置时间范围
        content_empty: null, // 重置内容状态
      };
      this.handleGsprSearch();
    },

    // 排序处理
    handleSortChange({ prop, order }) {
      this.sort_field = prop;
      this.sort_order = order === "ascending" ? "asc" : "desc";
      if (!order) {
        this.sort_field = "name";
        this.sort_order = "desc";
      }
      this.fetchGsprData();
    },
    /* 获取字段 */
    init() {
      departments().then((res) => {
        if (res.status !== 200) return;
        this.departList = res.data.departments;
      });
      /* 获取当前项目绑定的文档 */
      getProjectInfo({ id: this.$route.query.id }).then((res) => {
        this.documentIds = res.data.documentIds;
      });
    },
  },
};
</script>
<style lang="scss" >
.project-input-container {
  padding: 20px;
}
.pagination-container {
  display: flex;
  justify-content: flex-end;
}
.editor-area {
  ::v-deep .cke_top {
    display: block; // Hide the original toolbar
  }
}
.project-input-container {
  padding: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

/* 添加编辑器工具栏样式 */
.editor-area {
  .cke_top {
    display: flex !important;
    justify-content: space-between;
    align-items: center;
    padding: 6px 8px !important;

    /* 工具栏组样式 */
    .cke_toolgroup {
      margin: 0 2px;
      display: flex;
      align-items: center;
    }

    /* 工具栏按钮样式 */
    .cke_toolbar {
      float: none !important;
      display: inline-flex;
      align-items: center;
    }
  }
}

/* 如果需要调整编辑器容器宽度 */
.cke_chrome {
  width: 100% !important;
}
/* 内容部分样式 */
.content-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .content-text {
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 430px; // 可以根据需要调整最大宽度
  }
}

/* 自定义 Tooltip 样式 */
.custom-tooltip {
  min-width: 200px !important; // 设置最大宽度
  /* background-color: rgba(232, 232, 232, 0.9) !important; */
  line-height: 1.5; // 设置行高
  word-break: break-all; // 允许在任意字符间断行
  white-space: pre-wrap; // 保留空格和换行

  .el-tooltip__popper {
    padding: 10px !important; // 增加内边距
    font-size: 12px; // 设置字体大小
  }
}
::v-deep .el-dialog {
  margin-top: 0 !important;
}
</style>