<template>
  <div class="data-list">
    <el-table
      :data="dataList"
      style="width: 100%"
      header-row-class-name="headerBg"
      empty-text="没有项目信息"
    >
      <el-table-column prop="id" label="项目编号" align="center" width="80" />
      <el-table-column prop="customer_id" label="客户名称" align="left">
        <template #default="scope">
          <span>{{ getCusomName(scope.row.customer_id) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="项目名称" align="left" />

      <el-table-column prop="categoryId" label="产品类别" align="left">
        <template #default="scope">
          <span>{{ getCategoryTypeName(scope.row.product_id) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="productName" label="产品名称" align="left">
        <template #default="scope">
          <span>{{ getCategoryName(scope.row.product_id) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="service_content" label="服务内容" align="left" />

      <el-table-column prop="start_date" label="项目开始日期" align="center" />
      <el-table-column prop="updateTime" label="最后更新日期" align="center" />
      <el-table-column prop="calculate" label="完成度" align="center">
        <template #default="scope">
          <span :class="getCompletionClass(scope.row.calculate)">
            {{ formatCompletion(scope.row.calculate) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="current_phase" label="当前阶段" align="left">
        <template #default="scope">
          <el-tag :type="getPhaseType(scope.row.current_phase)" effect="plain">
            {{ getPhaseName(scope.row.current_phase) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="project_status" label="目前状态" align="center">
        <template #default="scope">
          <el-tag
            :type="getStatusType(scope.row.project_status)"
            effect="plain"
          >
            {{ getStatusName(scope.row.project_status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" fixed="right">
        <template #default="scope">
          <el-dropdown @command="handleCommand" :data="scope.row">
            <span class="el-dropdown-link">
              <el-button
                type="text"
                size="small"
                circle
                class="operation-button"
                style="font-size: 15px; margin-left: 10px"
                icon="el-icon-more"
              ></el-button>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  :command="{ type: 'template', row: scope.row }"
                  >选择模版</el-dropdown-item
                >
                <el-dropdown-item :command="{ type: 'enter', row: scope.row }"
                  >输入项目</el-dropdown-item
                >
                <el-dropdown-item
                  :command="{ type: 'viewTemplates', row: scope.row }"
                  v-if="
                    scope.row.documentIds && scope.row.documentIds.length > 0
                  "
                >
                  已绑定模版
                </el-dropdown-item>
                <el-dropdown-item :command="{ type: 'edit', row: scope.row }">
                  <svg-icon icon-class="edit" />编辑
                </el-dropdown-item>
                <el-dropdown-item :command="{ type: 'delete', row: scope.row }">
                  <svg-icon icon-class="delete" />删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
        <!-- <template #default="scope">
          <div class="btns">
            <el-button type="primary" size="small" @click="selTemplate(scope.row)"
              >选择模版</el-button
            >
            <el-button type="primary" size="small" @click="enterPro(scope.row)"
              >输入项目</el-button
            >
            <el-button type="primary" size="small" @click="btnEdit(scope.row)"
              ><svg-icon icon-class="edit" />编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="btnDelete(scope.row.id)"
              ><svg-icon icon-class="delete" />删除</el-button
            >
          </div>
        </template> -->
      </el-table-column>
    </el-table>

    <div class="page-info">
      <el-pagination
        :currentPage="queryForm.page"
        :page-size="queryForm.pageSize"
        :total="recordCount"
        :page-count="pageTotal"
        background
        layout="prev, pager, next"
        @current-change="ChangePage"
      >
      </el-pagination>
    </div>

    <el-dialog
      :visible.sync="dialogVisible"
      append-to-body
      v-el-drag-dialog
      custom-class="prod-verify"
      title="创建项目信息"
    >
      <dataInfo :id="currentDataId" @onClose="onClose"></dataInfo>
    </el-dialog>
    <!-- 选择模版 -->
    <el-dialog
      title="选择模版"
      :visible.sync="templateDialogVisible"
      width="50%"
      append-to-body
    >
      <el-table
        :data="templateList"
        style="width: 100%"
        @selection-change="handleTemplateSelect"
        @select-all="handleSelectAll"
        ref="templateTable"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="title" label="模版名称" align="left" />
        <el-table-column prop="create_time" label="创建时间" align="center" />
      </el-table>
      <div class="pagination-container">
        <el-pagination
          :current-page="templateQueryForm.page"
          :page-size="templateQueryForm.pageSize"
          :total="templateTotal"
          background
          layout="prev, pager, next"
          @current-change="handleTemplatePageChange"
        >
        </el-pagination>
      </div>
      <div class="dialog-footer" slot="footer">
        <el-button @click="templateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmTemplateSelection"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="已绑定模版"
      :visible.sync="boundTemplatesDialogVisible"
      v-el-drag-dialog
      width="50%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-table
        :data="boundTemplateList"
        style="width: 100%"
        @selection-change="handleBoundTemplateSelect"
        ref="boundTemplateTable"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="title" label="模版名称" align="left" />
        <el-table-column prop="createTime" label="绑定时间" align="center" />
        <el-table-column label="操作" align="center" width="320">
          <template #default="scope">
            <el-button type="primary" @click="previewTemplate(scope.row)"
              >预览</el-button
            >
            <el-button type="primary" @click="replaceTemplate(scope.row)"
              >替换</el-button
            >
            <el-dropdown
              style="margin-left: 10px"
              trigger="click"
              @command="(command) => handleExport(command, scope.row)"
            >
              <el-button type="success">
                导出文档<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="word">Word格式</el-dropdown-item
                  ><!-- word -->
                  <el-dropdown-item command="pdf">PDF格式</el-dropdown-item>
                  <!-- <el-dropdown-item command="pdf-to-word"
                    >Word</el-dropdown-item
                  > -->
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="dialog-footer" style="margin-top: 20px; text-align: right">
        <el-button
          type="primary"
          @click="batchReplace"
          :loading="batchReplaceLoading"
          :disabled="selectedBoundTemplates.length === 0"
        >
          批量替换
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      title=""
      :visible.sync="replaceVisible"
      width="50%"
      append-to-body
    >
      <!-- 显示匹配 -->
      <div v-if="matchResults.length" class="match-results">
        <div
          v-for="(item, index) in matchResults"
          :key="index"
          class="match-item"
        >
          <div class="match-content">
            <span>原始值: {{ item }}</span>
            <!-- <span>替换后: {{ item  }}</span> -->
          </div>
          <div class="actions">
            <el-button size="small" @click="replaceItem(item)">替换</el-button>
          </div>
        </div>
        <div style="display: flex; justify-content: flex-end; margin-top: 20px">
          <el-button type="primary" @click="replaceAll">批量替换</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  searchProject,
  deleteProject,
  searchCategory,
  relate,
  searchTemplateList,
  getstatus,
  calculate,
  getphases,
} from "@/api/project";
import {
  searchList,
  updateDocument,
  exportDocument,
  exportToPDF,
  htmlWordNew,
  htmlPDFWord,
} from "@/api/document";
import { searchCustomer } from "@/api/customer";
import { searchProduct } from "@/api/product";
/* import {searchTemplate} from "@/api/template" */
import dataInfo from "./dataInfo.vue";
import elDragDialog from "@/directive/el-drag-dialog";
import axios from "axios";
import jsPDF from "jspdf";
import html2canvas from "html2canvas";
import htmlDocx from "html-docx-js/dist/html-docx"; // 需要先安装: npm install html-docx-js
import { saveAs } from "file-saver"; // 需要先安装: npm install file-saver

export default {
  components: {
    dataInfo,
  },
  directives: { elDragDialog },
  props: {
    queryForm: {
      type: Object,
      default: () => {
        return {
          page: 1,
          pageSize: 10,
          name: "",
          category_id: "",
          status: "",
        };
      },
    },
  },
  watch: {
    queryForm: {
      handler: function (val) {
        this.search();
      },
      // immediate: true,//立即执行
      deep: true,
    },
  },
  data() {
    return {
      templateQueryForm: {
        page: 1,
        pageSize: 10,
      },
      templateTotal: 0, // 模版总数
      dialogVisible: false, //控制产品审核
      currentDataId: 0,
      recordCount: 0,
      pageTotal: 1,
      dataList: [],
      currentData: {},
      categoryList: [],
      templateDialogVisible: false,
      templateList: [],
      selectedTemplates: [], // 改为数组以支持多选
      boundTemplatesDialogVisible: false,
      previewDialogVisible: false,
      boundTemplateList: [],
      templatePreviewContent: "",
      currentTemplateId: null,
      replaceVisible: false,
      loading: false, // 增加 loading 状态
      searchResult: {},
      matchResults: [], // 存储匹配到的结果
      TemList: [],
      docAttr: {},
      templateLoading: false, // 添加模版加载状态
      boundTemplateLoading: false, // 添加已绑定模版加载状态
      selectedBoundTemplates: [], // 新增：已选择的绑定模版
      batchReplaceLoading: false, // 新增：批量替换loading状态
      getstatusList: [], //状态列表
      customList: [], //客户列��
      productList: [], //产品列表
      currentPhaseList: [], //阶段列表
      selectedTemplateIds: new Set(), // 新增: 用于存储所有已选择的模版ID
      isAllSelected: false, // 新增: 标记是否全选所有页
      selectedPageIds: new Map(), // 新增: 存储每页选中的ID
    };
  },
  mounted() {
    this.search();
    this.init();
  },
  methods: {
    /* 使用html-docx-js方法替换 */
    // 预处理内容，处理分页符和表格
    preprocessContent(content) {
      const tempDiv = document.createElement("div");
      tempDiv.innerHTML = content;

      // 处理分页符
      tempDiv
        .querySelectorAll('div[style*="page-break-after"]')
        .forEach((pageBreak) => {
          // 使用Word支持的分页符格式
          const newPageBreak = document.createElement("br");
          newPageBreak.style.pageBreakBefore = "always";
          newPageBreak.style.clear = "both";
          // 添加特殊的Word分页符
          newPageBreak.className = "WordSection";

          // 替换原有分页符
          pageBreak.parentNode.replaceChild(newPageBreak, pageBreak);
        });

      return tempDiv.innerHTML;
    },

    // 更新导出方法
    async exportDocumentWithHtmlDocx(template) {
      try {
        const templateData = JSON.parse(template.data || "[]");
        const contentContainer = document.createElement("div");
        contentContainer.className = "content";

        // 处理每个模版段落
        templateData.forEach((item) => {
          const templateSection = document.createElement("div");
          templateSection.className = "template-textarea";
          // 使用预处理方法处理内容，包括图片处理
          templateSection.innerHTML = this.htmlProcessImages(
            this.preprocessContent(item.content)
          );
          contentContainer.appendChild(templateSection);
        });

        let contentData = `
          <!DOCTYPE html>
          <html xmlns:v="urn:schemas-microsoft-com:vml" 
              xmlns:o="urn:schemas-microsoft-com:office:office" 
              xmlns:w="urn:schemas-microsoft-com:office:word">
          <head>
            <meta charset="UTF-8">
            <xml>
              <w:WordDocument>
                <w:View>Print</w:View>
                <w:Zoom>100</w:Zoom>
                <w:DoNotOptimizeForBrowser/>
              </w:WordDocument>
            </xml>
              <style>
                /* 基础表格样式 */
                table {
                  width: 100%;
                  margin: 8px 0;
                  table-layout: fixed;
                }
                
                /* 有边框表格样式 */
                table[data-border="true"],
                .table-with-border {
                  border-collapse: collapse !important;
                  border: 1px solid black !important;
                  margin-bottom: 1em;
                }
                
                /* 确保表格行不会在页面边界断开 */
                table[data-border="true"] tr,
                .table-with-border tr {
                  page-break-inside: avoid !important;
                }
                
                /* 表格单元格样式 */
                table[data-border="true"] td,
                table[data-border="true"] th,
                .table-with-border td,
                .table-with-border th {
                  border: 1px solid black !important;
                  padding: 6px;
                  word-wrap: break-word;
                  overflow: hidden;
                }
                
                /* 表格头部样式 */
                table[data-border="true"] thead,
                .table-with-border thead {
                  display: table-header-group;
                }
                
                /* 表格主体样式 */
                table[data-border="true"] tbody,
                .table-with-border tbody {
                  display: table-row-group;
                }
                
                /* 确保跨页时边框正确显示 */
                @media print {
                  table[data-border="true"],
                  .table-with-border {
                    -webkit-print-color-adjust: exact;
                    color-adjust: exact;
                    border-collapse: collapse !important;
                  }
                  
                  table[data-border="true"] tr,
                  .table-with-border tr {
                    border-top: 1px solid black !important;
                    border-bottom: 1px solid black !important;
                  }
                  
                  /* 确保打印时表格边框显示完整 */
                  table[data-border="true"] td,
                  table[data-border="true"] th,
                  .table-with-border td,
                  .table-with-border th {
                    border: 1px solid black !important;
                    -webkit-print-color-adjust: exact;
                    color-adjust: exact;
                  }
                }
                
                /* 无边框表格样式 */
                table[data-border="false"],
                .table-no-border {
                  border: none !important;
                }
                
                table[data-border="false"] td,
                table[data-border="false"] th,
                .table-no-border td,
                .table-no-border th {
                  border: none !important;
                  padding: 6px;
                }
                 /* 图片相关样式 */
                .WordImage {
                  margin: 10pt 0;
                  page-break-inside: avoid;
                  clear: both;
                }
                
                img {
                  max-width: 100%;
                  display: block;
                  page-break-inside: avoid;
                  -ms-interpolation-mode: bicubic;
                }
                
                /* Word特定的图片容器样式 */
                v\\:shape, v\\:imagedata {
                  behavior: url(#default#VML);
                }
                
                /* 确保图片容器继承父元素的对齐方式 */
                p[style*="text-align"] .WordImage {
                  margin-left: auto;
                  margin-right: auto;
                }
              </style>
            </head>
            <body>
              ${this.processTableHeaders(
                this.processContentForWord(contentContainer.innerHTML)
              )}
            </body>
          </html>
        `;

        // 添加Word特定的分页处理
        contentData = contentData.replace(
          /<br class="WordSection"[^>]*>/g,
          '<br clear="all" style="page-break-before:always; mso-break-type:section-break">'
        );

        const converted = htmlDocx.asBlob(contentData, {
          orientation: "portrait",
          margins: {
            top: "2.54cm",
            right: "2.54cm",
            bottom: "2.54cm",
            left: "2.54cm",
          },
          // 添加Word特定的文档属性
          docProperties: {
            "w:sectPr": {
              "w:type": { _attr: { "w:val": "nextPage" } },
            },
          },
        });

        saveAs(converted, `${template.title}.docx`);
      } catch (error) {
        console.error("导出Word文档失败:", error);
        this.$message.error("导出文档时发生错误，请稍后重试");
      }
    },
    /* 处理图片 */
    htmlProcessImages(content) {
      const tempDiv = document.createElement("div");
      tempDiv.innerHTML = content;
      // 处理所有图片
      tempDiv.querySelectorAll("img").forEach((img) => {
        // 创建图片容器
        const container = document.createElement("div");
        container.className = "image-container";
        // 获取所有可能的尺寸来源
        let width =
          img.getAttribute("width") || img.style.width || img.width || null;
        let height =
          img.getAttribute("height") || img.style.height || img.height || null;
        // 移除单位并转换为数字
        if (typeof width === "string") {
          width = parseInt(width.replace(/[^0-9]/g, ""));
        }
        if (typeof height === "string") {
          height = parseInt(height.replace(/[^0-9]/g, ""));
        }
        // 如果没有尺寸，创建一个临时图片来获取实际尺寸
        if (!width || !height) {
          const tempImg = new Image();
          tempImg.src = img.src;
          width = tempImg.width || 595; // 默认宽度
          height = tempImg.height || Math.round(width * 0.75); // 默认高度比例
        }
        // 确保数值有效
        width = Math.max(1, parseInt(width));
        height = Math.max(1, parseInt(height));
        // 处理尺寸
        const maxWidth = 595; // A4纸宽度（像素，减去边距）
        if (width > maxWidth) {
          // 等比例缩放
          const aspectRatio = width / height;
          const newHeight = Math.round(maxWidth / aspectRatio);
          width = maxWidth;
          height = newHeight;
        }
        // 同时设置style和属性
        img.style.width = `${width}px`;
        img.style.height = `${height}px`;
        img.setAttribute("width", width);
        img.setAttribute("height", height);
        // 将图片包装在容器中
        img.parentNode.insertBefore(container, img);
        container.appendChild(img);
      });
      return tempDiv.innerHTML;
    },

  
    // 预处理表格
    preprocessTables(content) {
      const tempDiv = document.createElement("div");
      tempDiv.innerHTML = content;

      // 处理所有表格
      tempDiv.querySelectorAll("table").forEach((table, index) => {
        if (this.isTableWithBorder(table)) {
          // 处理有边框表格
          this.processTableWithBorder(table, index);
        } else {
          // 处理无边框表格
          this.processTableNoBorder(table, index);
        }
      });

      return tempDiv.innerHTML;
    },

    // 处理有边框表格
    processTableWithBorder(table, index) {
      // 创建表格容器
      const container = document.createElement("div");
      container.className = "table-container";

      // 获取表头行
      const headerRow = table.querySelector("tr");
      const hasHeader = headerRow && headerRow.querySelector("th");

      // 复制原始表格并添加必要的类和属性
      const clonedTable = table.cloneNode(true);
      clonedTable.className = "table-with-border continuous-table";
      clonedTable.setAttribute("data-table-id", `table-${index}`);

      if (hasHeader) {
        // 保存表头信息
        const headerHTML = headerRow.outerHTML;
        clonedTable.setAttribute("data-header", headerHTML);
        clonedTable.setAttribute("data-repeat-header", "true");
      }

      // 处理表格的每一行
      clonedTable.querySelectorAll("tr").forEach((row, rowIndex) => {
        row.setAttribute("data-row-index", rowIndex);
        row.style.pageBreakInside = "avoid";
      });

      // 将处理后的表格放入容器
      container.appendChild(clonedTable);
      table.parentNode.replaceChild(container, table);
    },

    // 处理无边框表格
    processTableNoBorder(table, index) {
      // 创建表格容器
      const container = document.createElement("div");
      container.className = "table-container-no-border";

      // 复制原始表格并添加必要的类和属性
      const clonedTable = table.cloneNode(true);
      clonedTable.className = "table-no-border";
      clonedTable.setAttribute("data-table-id", `table-no-border-${index}`);

      // 处理表格的每一行，保持原有样式
      clonedTable.querySelectorAll("tr").forEach((row) => {
        const originalRowStyles = row.getAttribute("style") || "";
        row.style.cssText = `
          page-break-inside: avoid;
          ${originalRowStyles}
        `;

        // 处理单元格，保持原有样式
        row.querySelectorAll("td, th").forEach((cell) => {
          const originalStyles = cell.getAttribute("style") || "";
          cell.style.cssText = `
            border: none !important;
            padding: 6px;
            word-wrap: break-word;
            overflow: hidden;
            ${originalStyles}
          `;
        });
      });

      // 将处理后的表格放入容器
      container.appendChild(clonedTable);
      table.parentNode.replaceChild(container, table);
    },

    // 处理表格内容
    processContentForWord(content) {
      const tempDiv = document.createElement("div");
      tempDiv.innerHTML = content;

      // 处理所有表格
      tempDiv.querySelectorAll("table").forEach((table) => {
        // 检查表格是否有边框
        const hasBorder = this.detectTableBorder(table);

        if (hasBorder) {
          // 为有边框的表格添加必要的类和属性
          table.classList.add("table-with-border");
          table.setAttribute("data-border", "true");

          // 确保表格基本样式
          table.style.borderCollapse = "collapse";
          table.style.width = "100%";
          table.style.pageBreakInside = "auto";

          // 处理所有行
          table.querySelectorAll("tr").forEach((row, rowIndex) => {
            row.setAttribute("data-row-index", rowIndex);
            row.style.pageBreakInside = "avoid";

            // 处理所有单元格
            row.querySelectorAll("td, th").forEach((cell) => {
              // 保存原有样式
              const originalStyles = cell.getAttribute("style") || "";

              // 合并新样式和原有样式
              cell.style.cssText = `
                border: 1px solid black !important;
                border-collapse: collapse !important;
                padding: 6px;
                word-wrap: break-word;
                overflow: hidden;
                ${originalStyles}
              `;
            });
          });
        } else {
          // 处理无边框表格
          table.classList.add("table-no-border");
          table.setAttribute("data-border", "false");
        }
      });

      return tempDiv.innerHTML;
    },

    // 添加检测表格边框的方法
    detectTableBorder(table) {
      // 1. 检查表格本身是否有边框属性
      if (
        table.getAttribute("border") ||
        table.style.border ||
        table.classList.contains("bordered")
      ) {
        return true;
      }

      // 2. 检查表格样式是否包含边框相关属性
      const tableStyle = window.getComputedStyle(table);
      if (tableStyle.border || tableStyle.borderCollapse === "collapse") {
        return true;
      }

      // 3. 检查单元格是否有边框
      const cells = table.querySelectorAll("td, th");
      const hasCellBorder = Array.from(cells).some((cell) => {
        const style = window.getComputedStyle(cell);
        return (
          style.border ||
          style.borderTop ||
          style.borderBottom ||
          style.borderLeft ||
          style.borderRight
        );
      });

      // 4. 检查是否有特定的无边框标记
      const hasNoBorderMark =
        table.classList.contains("no-border") ||
        table.getAttribute("data-no-border") === "true";

      return hasCellBorder && !hasNoBorderMark;
    },

    // 添加处理分页的辅助方法
    addPageBreaks(content) {
      // 查找需要分页的位置（可以根据实际需求调整）
      const pageBreakMarkers = ["<h1", "<h2", "<!-- pagebreak -->"];

      pageBreakMarkers.forEach((marker) => {
        content = content.replace(
          new RegExp(marker, "g"),
          `<div class="page-break"></div>${marker}`
        );
      });

      return content;
    },

    // 处理表格边框的辅助方法
    processTableBorders(table) {
      const isInfoTable = this.isInformationTable(table);

      if (isInfoTable) {
        table.classList.add("info-table");
      } else {
        // 检查表格是否需要边框
        const needsBorder = this.checkTableNeedsBorder(table);
        if (needsBorder) {
          table.style.border = "1px solid black";
          table.querySelectorAll("td, th").forEach((cell) => {
            cell.style.border = "1px solid black";
          });
        }
      }
    },

    // 检查表格是否需要边框
    checkTableNeedsBorder(table) {
      // 检查表格第一行是否包含特定标记或样式
      const firstRow = table.querySelector("tr");
      if (!firstRow) return false;

      // 可以根据实际需求添加更多的判断条件
      return (
        firstRow.querySelector('td[style*="border"]') !== null ||
        table.getAttribute("border") === "1" ||
        table.classList.contains("bordered")
      );
    },

    // 添加内容处理方法
    processContentForWord(content) {
      const tempDiv = document.createElement("div");
      tempDiv.innerHTML = content;

      // 添加表格分页标识
      let tableCounter = 0;

      // 处理表格
      tempDiv.querySelectorAll("table").forEach((table) => {
        tableCounter++;
        const tableId = `table_${tableCounter}`;
        table.setAttribute("data-table-id", tableId);

        // 判断表格类型
        const isInfoTable = this.isInformationTable(table);
        const isContinuousTable = this.isContinuousTable(table);

        // 基本表格样式
        table.style.width = "100%";
        table.style.borderCollapse = "collapse";
        table.style.tableLayout = "fixed";

        if (isInfoTable) {
          // 信息表格处理逻辑保持不变
          table.classList.add("info-table");
          this.processInfoTable(table);
        } else if (isContinuousTable) {
          // 处理跨页连续表格
          table.classList.add("continuous-table");
          this.processContinuousTable(table, tableCounter);
        } else {
          // 普通表格处理逻辑保持不变
          this.processNormalTable(table);
        }
      });

      // 添加表格连续性样式
      const styleElement = document.createElement("style");
      styleElement.textContent = this.generateTableStyles(tableCounter);
      tempDiv.insertBefore(styleElement, tempDiv.firstChild);

      return tempDiv.innerHTML;
    },

    // 判断是否为连续表格
    isContinuousTable(table) {
      // 检查表格是否有分页标记
      const prevElement = table.previousElementSibling;
      return prevElement && prevElement.classList.contains("page-break");
    },

    // 处理连续表格
    processContinuousTable(table, tableCounter) {
      // 设置表格基本样式
      table.style.borderCollapse = "collapse";
      table.style.border = "1px solid black";

      // 处理所有单元格
      table.querySelectorAll("tr").forEach((row, rowIndex) => {
        row.style.borderTop = "1px solid black";
        row.style.borderBottom = "1px solid black";

        row.querySelectorAll("td, th").forEach((cell) => {
          const originalStyles = cell.getAttribute("style") || "";
          cell.style.cssText = `
            border: 1px solid black !important;
            padding: 6px;
            word-wrap: break-word;
            overflow: hidden;
            ${originalStyles}
          `;
        });
      });
    },

    // 生成表格样式
    generateTableStyles() {
      return `
        /* 原有表格样式保持不变 */
        .table-with-border {
          /* ... */
        }
        
        .table-no-border {
          /* ... */
        }
        
        /* 确保表格不会被分页符影响 */
        table {
          -webkit-column-break-inside: avoid;
          page-break-inside: avoid;
          break-inside: avoid;
        }
      `;
    },

    // 添加判断表格类型的方法
    isInformationTable(table) {
      // 获取表格第一行第一个单元格的文本
      const firstCell = table.querySelector("td");
      if (!firstCell) return false;

      // 定义信息表格的特征文本数组
      const infoTableHeaders = [
        "Drafted by",
        "Reviewed by",
        "Approved by",
        "File number",
        "Revision",
        "Effective",
      ];

      // 检查第一个单元格的文本是否匹配特征文本
      return infoTableHeaders.some(
        (header) =>
          firstCell.textContent.trim().toLowerCase() === header.toLowerCase()
      );
    },
    // 添加处理普通表格的方法
    processNormalTable(table) {
      // 处理行和单元格
      table.querySelectorAll("tr").forEach((row, rowIndex) => {
        // 保持原始行高
        const height = row.style.height || row.getAttribute("height");
        if (height) {
          row.style.height = height;
        }

        // 处理单元格
        row.querySelectorAll("td, th").forEach((cell, cellIndex) => {
          // 获取原始样式
          const originalStyles = cell.getAttribute("style") || "";

          // 设置单元格样式
          cell.style.cssText = `
            padding: 6px;
            word-wrap: break-word;
            overflow: hidden;
            ${originalStyles}
          `;

          // 保持原始宽度
          if (rowIndex === 0) {
            const width = cell.style.width || cell.getAttribute("width");
            if (width) {
              cell.style.width = width;
              // 为该列的所有单元格设置相同的宽度
              table
                .querySelectorAll(
                  `tr td:nth-child(${cellIndex + 1}), tr th:nth-child(${
                    cellIndex + 1
                  })`
                )
                .forEach((td) => {
                  td.style.width = width;
                });
            }
          }

          // 处理合并单元格
          if (cell.hasAttribute("rowspan")) {
            cell.style.verticalAlign = "middle";
          }
        });
      });
    },

    // 添加处理信息表格的方法
    processInfoTable(table) {
      table.querySelectorAll("tr").forEach((row) => {
        row.querySelectorAll("td").forEach((cell, index) => {
          // 第一列（标签列）样式
          if (index === 0) {
            cell.style.cssText = `
              border: 1px solid black;
              padding: 6px;
              width: 150px;
              font-weight: normal;
              text-align: left;
              background-color: white;
            `;
          }
          // 第二列（内容列）样式
          else {
            cell.style.cssText = `
              border: 1px solid black;
              padding: 6px;
              text-align: left;
            `;
          }

          // 保持原始对齐方式
          const originalAlign = cell.getAttribute("align");
          if (originalAlign) {
            cell.style.textAlign = originalAlign;
          }
        });
      });
    },

    // 判断表格类型的方法
    isTableWithBorder(table) {
      // 检查表格是否有边框属性
      if (table.getAttribute("border") === "1") return true;

      // 检查表格是否有边框样式
      if (table.style.border || table.classList.contains("bordered"))
        return true;

      // 检查第一个单元格是否有边框
      const firstCell = table.querySelector("td, th");
      if (firstCell && firstCell.style.border) return true;

      // 检查是否为信息类表格
      const firstCellText = firstCell?.textContent?.trim().toLowerCase() || "";
      const infoHeaders = [
        "drafted by",
        "reviewed by",
        "approved by",
        "file number",
        "revision",
        "effective",
      ];
      return infoHeaders.some((header) =>
        firstCellText.includes(header.toLowerCase())
      );
    },

    // 处理表格的主方法
    processContentForWord(content) {
      const tempDiv = document.createElement("div");
      tempDiv.innerHTML = content;

      // 添加表格分页标识
      let tableCounter = 0;

      // 处理表格
      tempDiv.querySelectorAll("table").forEach((table) => {
        tableCounter++;
        const tableId = `table_${tableCounter}`;
        table.setAttribute("data-table-id", tableId);

        // 判断表格类型
        const isInfoTable = this.isInformationTable(table);
        const isContinuousTable = this.isContinuousTable(table);
        const hasTableBorder = this.isTableWithBorder(table);

        // 基本表格样式
        table.style.width = "100%";
        table.style.borderCollapse = "collapse";
        table.style.tableLayout = "fixed";

        if (isInfoTable) {
          // 信息表格处理逻辑
          table.classList.add("info-table");
          this.processInfoTable(table);
        } else if (isContinuousTable && hasTableBorder) {
          // 处理有边框的跨页连续表格
          table.classList.add("continuous-table-with-border");
          this.processContinuousTableWithBorder(table, tableCounter);
        } else if (isContinuousTable) {
          // 处理无边框的跨页连续表格
          table.classList.add("continuous-table-no-border");
          this.processContinuousTableNoBorder(table, tableCounter);
        } else if (hasTableBorder) {
          // 处理有边框的普通表格
          table.classList.add("normal-table-with-border");
          this.processNormalTableWithBorder(table);
        } else {
          // 处理无边框的普通表格
          table.classList.add("normal-table-no-border");
          this.processNormalTableNoBorder(table);
        }
      });

      // 添加表格样式
      const styleElement = document.createElement("style");
      styleElement.textContent = this.generateTableStyles(tableCounter);
      tempDiv.insertBefore(styleElement, tempDiv.firstChild);

      return tempDiv.innerHTML;
    },

    // 处理有边框的普通表格
    processNormalTableWithBorder(table) {
      table.style.border = "1px solid black";

      table.querySelectorAll("tr").forEach((row, rowIndex) => {
        // 保持原始行高
        const height = row.style.height || row.getAttribute("height");
        if (height) {
          row.style.height = height;
        }

        row.querySelectorAll("td, th").forEach((cell, cellIndex) => {
          const originalStyles = cell.getAttribute("style") || "";
          cell.style.cssText = `
            border: 1px solid black;
            padding: 6px;
            word-wrap: break-word;
            overflow: hidden;
            ${originalStyles}
          `;

          // 保持原始宽度
          if (rowIndex === 0) {
            const width = cell.style.width || cell.getAttribute("width");
            if (width) {
              this.setColumnWidth(table, cellIndex, width);
            }
          }
        });
      });
    },

    // 处理无边框的普通表格
    processNormalTableNoBorder(table) {
      table.querySelectorAll("tr").forEach((row, rowIndex) => {
        // 保持原始行高
        const height = row.style.height || row.getAttribute("height");
        if (height) {
          row.style.height = height;
        }

        row.querySelectorAll("td, th").forEach((cell, cellIndex) => {
          const originalStyles = cell.getAttribute("style") || "";
          cell.style.cssText = `
            padding: 6px;
            word-wrap: break-word;
            overflow: hidden;
            ${originalStyles}
          `;

          // 保持原始宽度
          if (rowIndex === 0) {
            const width = cell.style.width || cell.getAttribute("width");
            if (width) {
              this.setColumnWidth(table, cellIndex, width);
            }
          }
        });
      });
    },

    // 处理有边框的连续表格
    processContinuousTableWithBorder(table, tableCounter) {
      // 设置表格基本样式
      table.style.borderCollapse = "collapse";
      table.style.border = "1px solid black";

      // 为表格添加唯一标识
      const tableId = `bordered-table-${tableCounter}`;
      table.id = tableId;

      // 处理所有行和单元格
      table.querySelectorAll("tr").forEach((row, rowIndex) => {
        // 设置行样式
        row.style.borderTop = "1px solid black";
        row.style.borderBottom = "1px solid black";
        row.style.pageBreakInside = "avoid"; // 防止行内分页

        // 处理单元格
        row.querySelectorAll("td, th").forEach((cell, cellIndex) => {
          const originalStyles = cell.getAttribute("style") || "";
          cell.style.cssText = `
            border: 1px solid black !important;
            padding: 6px;
            word-wrap: break-word;
            overflow: hidden;
            ${originalStyles}
          `;
        });
      });

      // 添加特定样式以处理分页情况
      const styleSheet = document.createElement("style");
      styleSheet.textContent = `
        #${tableId} {
          border-collapse: collapse !important;
          border: 1px solid black !important;
        }
        
        #${tableId} tr {
          border-top: 1px solid black !important;
          border-bottom: 1px solid black !important;
        }
        
        #${tableId} td,
        #${tableId} th {
          border: 1px solid black !important;
        }
        
        /* 处理分页后的表格边框 */
        @media print {
          #${tableId} {
            border: 1px solid black !important;
          }
          
          #${tableId}[data-table-continued="true"] {
            border-top: 1px solid black !important;
          }
          
          #${tableId}[data-table-start="true"] {
            border-bottom: 1px solid black !important;
          }
        }
      `;
      document.head.appendChild(styleSheet);
    },

    // 处理无边框的连续表格
    processContinuousTableNoBorder(table, tableCounter) {
      table.querySelectorAll("tr").forEach((row) => {
        row.querySelectorAll("td, th").forEach((cell) => {
          const originalStyles = cell.getAttribute("style") || "";
          cell.style.cssText = `
            padding: 6px;
            word-wrap: break-word;
            overflow: hidden;
            ${originalStyles}
          `;
        });
      });
    },

    // 设置列宽的辅助方法
    setColumnWidth(table, columnIndex, width) {
      table
        .querySelectorAll(
          `tr td:nth-child(${columnIndex + 1}), tr th:nth-child(${
            columnIndex + 1
          })`
        )
        .forEach((td) => {
          td.style.width = width;
        });
    },

    // 生成表格样式
    generateTableStyles(tableCount) {
      return `
        /* 基础表格样式 */
        table {
          width: 100%;
          border-collapse: collapse;
          table-layout: fixed;
          page-break-inside: auto;
        }
        
        /* 有边框表格的通用样式 */
        table[data-has-border="true"] {
          border-collapse: collapse !important;
        }
        
        /* 处理分页情况 */
        @media print {
          /* 确保分页后的表格边框显示 */
          table[data-has-border="true"] {
            border: 1px solid black !important;
          }
          
          /* 处理跨页表格的边框 */
          table[data-has-border="true"][data-table-continued="true"] {
            border-top: 1px solid black !important;
            margin-top: 0 !important;
          }
          
          table[data-has-border="true"][data-table-start="true"] {
            border-bottom: 1px solid black !important;
          }
          
          /* 确保所有单元格边框显示 */
          table[data-has-border="true"] td,
          table[data-has-border="true"] th {
            border: 1px solid black !important;
          }
        }
      `;
    },

    // 判断表格是否是连续的
    isTableContinued(previousTable, currentTable) {
      // 检查两个表格是否紧邻
      const nextElement = previousTable.nextElementSibling;
      if (!nextElement) return false;

      // 检查是否有分页标记
      if (nextElement.classList.contains("page-break")) {
        return true;
      }

      // 检查表格结构是否相似
      const prevCols = previousTable.querySelectorAll(
        "tr:first-child td, tr:first-child th"
      ).length;
      const currCols = currentTable.querySelectorAll(
        "tr:first-child td, tr:first-child th"
      ).length;

      return prevCols === currCols;
    },

    // 处理表格表头
    processTableHeaders(content) {
      const tempDiv = document.createElement("div");
      tempDiv.innerHTML = content;

      // 处理所有需要重复表头的表格
      tempDiv
        .querySelectorAll('table[data-repeat-header="true"]')
        .forEach((table) => {
          const headerHTML = table.getAttribute("data-header");
          if (!headerHTML) return;

          // 创建thead元素
          const thead = document.createElement("thead");
          thead.innerHTML = headerHTML;

          // 将原有的表头移动到thead中
          const firstRow = table.querySelector("tr");
          if (firstRow) {
            table.insertBefore(thead, firstRow);
          }

          // 确保tbody存在
          if (!table.querySelector("tbody")) {
            const tbody = document.createElement("tbody");
            while (table.querySelector("tr")) {
              tbody.appendChild(table.querySelector("tr"));
            }
            table.appendChild(tbody);
          }
        });

      return tempDiv.innerHTML;
    },
    /*  */
    // 添加 PDF 转 Word 的方法
    async convertPDFToWord(pdfPath) {
      try {
        // 创建FormData对象
        const formData = new FormData();
        formData.append("oss_url", pdfPath);

        // 调用后端转换接口
        const res = await axios.post(
          `${process.env.VUE_APP_BASE_API}/convert/pdftoword`,
          formData,
          {
            headers: {
              "Content-Type": "multipart/form-data", // 设置请求头为form-data
            },
          }
        );

        if (res.status === 200) {
          // 将base64转换为Blob
          const byteCharacters = atob(res.data.data.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.wordprocessingml.document",
          });

          // 创建下载链接
          const link = document.createElement("a");
          link.href = URL.createObjectURL(blob);
          link.download = "converted.docx"; // 或使用服务器返回的文件名
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);

          // 清理URL对象
          URL.revokeObjectURL(link.href);

          this.$message.success("转换成功");
        } else {
          throw new Error(res.data.message || "转换失败");
        }
      } catch (error) {
        console.error("PDF转Word失败:", error);
        this.$message.error("PDF转Word失败，请稍后重试");
      }
    },
    // 2. 替换原有的 exportDocument 方法
    async exportDocument(template) {
      try {
        const templateData = JSON.parse(template.data || "[]");
        const contentContainer = document.createElement("div");
        contentContainer.className = "content";

        // 处理每个模版段落
        templateData.forEach((item) => {
          const templateSection = document.createElement("div");
          templateSection.className = "template-textarea";

          // 创��临时div用于处理HTML内容
          const tempDiv = document.createElement("div");
          tempDiv.innerHTML = item.content;

          // 合并嵌套的样式标签
          const mergeStyleTags = (element) => {
            const spans = element.getElementsByTagName("span");
            for (let i = spans.length - 1; i >= 0; i--) {
              const span = spans[i];
              if (
                span.firstElementChild &&
                span.firstElementChild.tagName === "SPAN"
              ) {
                const childSpan = span.firstElementChild;

                // 保存span中的所有内容
                const spanContent = span.innerHTML;

                // 合并样式
                const parentStyle = span.getAttribute("style") || "";
                const childStyle = childSpan.getAttribute("style") || "";

                // 解析样式
                const styleMap = {};
                [...parentStyle.split(";"), ...childStyle.split(";")]
                  .filter((s) => s.trim())
                  .forEach((s) => {
                    const [key, value] = s.split(":").map((s) => s.trim());
                    if (key && value) {
                      styleMap[key] = value;
                    }
                  });

                // 创建新的样式字符串
                const mergedStyle = Object.entries(styleMap)
                  .map(([key, value]) => `${key}: ${value}`)
                  .join("; ");

                // 创建新的span元素并保留所有内容
                const newSpan = document.createElement("span");
                newSpan.setAttribute("style", mergedStyle);

                // 使用原始的innerHTML内容
                newSpan.innerHTML = spanContent;

                // 处理strong标签和其他特殊标签
                const strongTags = newSpan.getElementsByTagName("strong");
                for (const strongTag of strongTags) {
                  strongTag.style.fontWeight = "bold";
                }

                // 替换原始标签
                span.parentNode.replaceChild(newSpan, span);
              }
            }

            // 清理可能的空span标签
            const allSpans = element.getElementsByTagName("span");
            for (let i = allSpans.length - 1; i >= 0; i--) {
              const span = allSpans[i];
              if (!span.textContent.trim() && !span.querySelector("img")) {
                span.parentNode.removeChild(span);
              }
            }
          };

          // 处理所有表格
          tempDiv.querySelectorAll("table").forEach((table) => {
            // 检查表格及其单元格是否有任何边框
            const tableStyle = table.getAttribute("style");

            // 如果表格没有style属性，直接判定为无边框
            if (!tableStyle) {
              table.setAttribute("data-code", "noactive");
              return;
            }

            // 检查所有单元格
            const cells = Array.from(table.querySelectorAll("td, th"));
            const hasBorder = cells.some((cell) => {
              const cellStyle = cell.getAttribute("style");
              // 如果单元格没有style属性，视为无边框
              if (!cellStyle) {
                return false;
              }
              // 检查是否存在任何边框相关的样式
              return /border(?:-(top|right|bottom|left))?:\s*[^;]*[1-9]/.test(
                cellStyle
              );
            });

            if (hasBorder) {
              table.setAttribute("data-code", "active");
              // 保持原有样式
            } else {
              table.setAttribute("data-code", "noactive");
            }
          });

          // 对整个内容进行样式合并
          mergeStyleTags(tempDiv);

          templateSection.innerHTML = tempDiv.innerHTML;
          contentContainer.appendChild(templateSection);
        });

        let contentData = `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <style>
          body {
            font-family: SimSun, serif;
            font-size: 12pt;
            line-height: 12pt !important; /* 设置固定行距为12磅 */
          }
          
          /* 确保所有段落和文本容器都使用相同的行距 */
          p, div, span, td, th {
            line-height: 12pt !important;
          }
          
          /* 有边框的表格样式 */
          table[data-code="active"] {
            border-collapse: collapse;
            width: 100%;
          }
          table[data-code="active"] td,
          table[data-code="active"] th {
            border: 1px solid black;
            padding: 8px;
            line-height: 12pt !important;
          }
          
          /* 无边框的表格样式 */
          table[data-code="noactive"] {
            border: none;
            border-collapse: collapse;
            width: 100%;
          }
          table[data-code="noactive"] td,
          table[data-code="noactive"] th {
            border: none;
            padding: 8px;
            line-height: 12pt !important;
          }
          
          .template-textarea {
            page-break-after: always;
            line-height: 12pt !important;
          }
        </style>
      </head>
      <body>
        ${this.processImages(contentContainer.innerHTML)}
      </body>
    </html>`;

        // 调用导出接口
        const res = await htmlWordNew({
          content: contentData,
          title: template.title,
          options: {
            format: "docx",
            encoding: "utf-8",
            preserveStyles: true,
          },
        });

        if (res.status !== 200) {
          this.$alert(res.errMsg);
          return;
        }

        // 处理文件下载
        const link = document.createElement("a");
        link.href = res.data.file_path;
        link.download = `${template.title}.docx`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        this.$message.success("导出成功");
      } catch (error) {
        console.error("导出Word文档失败:", error);
        this.$alert("导出文档时发生错误，请稍后重试。");
      }
    },
    /* 客户名称 */
    getCusomName(phaseId) {
      const product = this.customList.find((item) => item.id === phaseId);
      return product ? product.name : "未知客户";
    },
    /* 当前阶段 */
    getPhaseName(phaseId) {
      const product = this.currentPhaseList.find(
        (item) => item.value === phaseId
      );
      return product ? product.label : "未知阶段";
    },

    getPhaseType(phaseId) {
      const product = this.currentPhaseList.find(
        (item) => item.value === phaseId
      );
      if (!product) return "info";

      // 根据不同阶段返回同的类型
      // 这里的判断逻辑需要根据实际的产品阶来调整
      switch (product.status) {
        case 1:
          return "success"; // 已完成
        case 2:
          return "warning"; // 进行中
        case 3:
          return "danger"; // 待处理
        default:
          return "info"; // 其他状态
      }
    },
    /*目前状态  */
    getStatusName(statusId) {
      const status = this.getstatusList.find((item) => item.value === statusId);
      return status ? status.label : "未状态";
    },

    getStatusType(statusId) {
      // 这里可以根据不同状态返回不同的类型
      // 可用的类型：success/warning/danger/info
      const status = this.getstatusList.find((item) => item.value === statusId);
      if (!status) return "info";

      // 根据状值返回对应的类型
      switch (status.value) {
        case 5:
          return "success";
        case 4:
          return "warning";
        case 3:
          return "danger";
        default:
          return "info";
      }
    },
    // 格式化完成度显示
    formatCompletion(rate) {
      if (rate === undefined || rate === null) {
        return "0%";
      }
      return `${rate}%`;
    },

    // 根据完成度返回对应CSS类名
    getCompletionClass(rate) {
      if (!rate) return "completion-low";
      if (rate >= 100) return "completion-high";
      if (rate >= 50) return "completion-medium";
      return "completion-low";
    },
    handleCommand(command) {
      switch (command.type) {
        case "template":
          this.selTemplate(command.row);
          break;
        case "enter":
          this.enterPro(command.row);
          break;
        case "edit":
          this.btnEdit(command.row);
          break;
        case "delete":
          this.btnDelete(command.row.id);
          break;
        case "viewTemplates":
          this.viewBoundTemplates(command.row);
          break;
      }
    },
    // Add new methods
    // 查看已绑定模版
    viewBoundTemplates(row) {
      this.currentData = row;
      this.boundTemplateLoading = true;
      searchTemplateList({ ids: row.documentIds.join(",") || 0 })
        .then((res) => {
          if (res.status === 200) {
            this.boundTemplateList = res.data;
            this.boundTemplatesDialogVisible = true;
          }
        })
        .finally(() => {
          this.boundTemplateLoading = false;
        });
    },

    previewTemplate(template) {
      /*  this.currentTemplateId = template.id; */
      let _this = this;
      let a = document.createElement("a");
      a.href = "#/document/viewCreate?articleId=" + template.id;
      a.target = "_blank";
      a.click();
      /* getTemplateContent(template.id).then((res) => {
        if (res.status === 200) {
          this.templatePreviewContent = res.data.content;
          this.previewDialogVisible = true;
        }
      }); */
    },

    replaceTemplate(template) {
      this.docAttr = template;
      const TemList = JSON.parse(template.data);
      /* this.$confirm("确定要替换此模吗？", "提示", {
        confirmButtonText: "确",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => { */
      this.replaceVisible = true;
      this.searchEx(TemList);
      /* this.closeTemplateDialog();
        this.selTemplate(this.currentData); */
      /* }); */
    },
    // 新增：处理已绑定模版的选择
    handleBoundTemplateSelect(selection) {
      this.selectedBoundTemplates = selection;
    },

    // 新增：批量替换方法
    async batchReplace() {
      if (this.selectedBoundTemplates.length === 0) {
        this.$message.warning("请选择需要替换的模版");
        return;
      }

      this.batchReplaceLoading = true;
      try {
        // 依次处理个选中的模版
        for (const template of this.selectedBoundTemplates) {
          this.docAttr = template;
          const TemList = JSON.parse(template.data);
          await this.searchEx(TemList);

          if (this.matchResults.length > 0) {
            await this.replaceAll();
          }
        }

        this.$message.success("批量替换完成");
        /*  this.boundTemplatesDialogVisible = false; */
      } catch (error) {
        console.error("批量替换失败:", error);
        this.$message.error("批量替换过程中发生错误");
      } finally {
        this.batchReplaceLoading = false;
      }
    },

    searchEx(val) {
      return new Promise((resolve) => {
        let allMatches = [];
        this.TemList = val;
        this.TemList.forEach((el) => {
          // 创建临时 div 来解析 HTML 内容
          const tempDiv = document.createElement("div");
          tempDiv.innerHTML = el.content;
          const plainText = tempDiv.textContent || tempDiv.innerText;

          // 分别匹配中文括号和英文括号
          const patterns = [
            /【([A-Z]{1,4}[0-9]{0,2})-([A-Z]{1,4}[0-9]{0,2})-([0-9]{2})-([0-9]{2,3})】/g,
            /\[([A-Z]{1,4}[0-9]{0,2})-([A-Z]{1,4}[0-9]{0,2})-([0-9]{2})-([0-9]{2,3})\]/g,
          ];

          patterns.forEach((pattern) => {
            let match;
            while ((match = pattern.exec(plainText)) !== null) {
              const fullMatch = match[0];
              const segments = [match[1], match[2], match[3], match[4]];

              // 验证每个段落的格式
              const isValid = segments.every((segment) => segment.length > 0);

              if (isValid) {
                allMatches.push(fullMatch);
              }
            }
          });
        });

        this.matchResults = [...new Set(allMatches)];

        // 调试用：打印每个匹配的详细信息
        this.matchResults.forEach((match) => {
          // 据括号类型选不同的切片方式
          const content = match.startsWith("【")
            ? match.slice(1, -1)
            : match.slice(1, -1);
          const parts = content.split("-");
        });
        resolve();
      });
    },

    // 添加��的辅助方法来判断文档类型
    getDocumentType(code) {
      if (code.includes("-RP-")) return "template_location";
      if (code.includes("-IR-")) return "middle_layer_location";
      if (code.includes("-WE-")) return "tech_report_location";
      return "other_location";
    },

    // 修改式化请求参数的方法
    formatRequestParams(locations) {
      const locationArray = Array.isArray(locations) ? locations : [locations];

      // 初始化求参数对象
      const params = {
        /* project_id:'', */
        template_location: [],
        middle_layer_location: [],
        tech_report_location: [],
        other_location: [],
      };

      // 根据不同类型分类存储
      locationArray.forEach((location) => {
        const cleanLocation = location.replace(/[\[\]【】]/g, "");
        const type = this.getDocumentType(cleanLocation);
        console.log("params", type);
        // 为每种类型创建对应长度的空数组
        Object.keys(params).forEach((key) => {
          if (type === key) {
            params[key].push(cleanLocation);
          } else {
            params[key].push("");
          }
        });
      });

      return params;
    },

    // 解析内容，处理特殊标记
    parseContent(content) {
      if (!content) return "";

      let parsed = content;

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

      // 处理表格标记
      parsed = parsed.replace(
        /\[表格\|style=(.*?)\|class=(.*?)\]\n([\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 [content, ...styleInfo] = cell.split("[style=");
              if (styleInfo.length) {
                const [style, className] = styleInfo[0]
                  .slice(0, -1)
                  .split("|class=");
                return `<td style="${style}" class="${className}">${content}</td>`;
              }
              return `<td>${content}</td>`;
            });
            tableHtml += cells.join("") + "</tr>";
          });

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

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

      return parsed;
    },

    // 查内容是否包含表格或图片
    containsTableOrImage(content) {
      return content.includes("<table") || content.includes("<img");
    },

    // 获取所有文本节点
    getTextNodes(node) {
      const textNodes = [];
      const walk = document.createTreeWalker(
        node,
        NodeFilter.SHOW_TEXT,
        null,
        false
      );
      let currentNode;
      while ((currentNode = walk.nextNode())) {
        textNodes.push(currentNode);
      }
      return textNodes;
    },

    /*更新  */
    onUpload() {
      let _this = this;
      if (_this.TemList.length <= 0) {
        _this.$message.error("增加组件");
        return;
      }
      if (_this.docAttr.title == "") {
        _this.$message.error("请填写模版题");
        return;
      }
      _this.docAttr.links = JSON.stringify(_this.docAttr.linkProduct);
      _this.docAttr.projects = JSON.stringify(_this.docAttr.linkProject);
      _this.docAttr.data = JSON.stringify(_this.TemList);
      _this.docAttr.is_template = 1;
      _this.docAttr.id = _this.docAttr.id;
      _this.docAttr.user_name = _this.docAttr.name;
      _this.docAttr.user_id = _this.docAttr.id;
      updateDocument(_this.docAttr).then((res) => {
        if (res.status != 200) return; //更新文档
        _this.docAttr.id = res.data;
        _this.$message.success("模版更新成功");
      });
    },

    // 添加统一的内容处理方法
    async processAndReplaceContent(content, originalMatch) {
      try {
        const params = this.formatRequestParams(originalMatch);
        params.project_id = this.currentData.id;
        const response = await axios.post(
          `${process.env.VUE_APP_BASE_API}/project-raw-data/batch-content`,
          params,
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        );

        if (response.status === 200 && response.data) {
          const replacementContent =
            response.data.data.matched_data[0]?.content;
          if (replacementContent) {
            // 处富文本内容
            this.TemList.forEach((el, index) => {
              console.log(el, originalMatch, replacementContent);
              const processedContent = this.processTableContent(
                el.content,
                originalMatch,
                replacementContent
              );
              this.$set(this.TemList[index], "content", processedContent);
            });
            return true;
          }
        }
        return false;
      } catch (error) {
        console.error("处理内容失败:", error);
        return false;
      }
    },

    // 修改单个替换方法
    async replaceItem(item) {
      try {
        const success = await this.processAndReplaceContent(this.TemList, item);
        if (success) {
          this.matchResults = this.matchResults.filter(
            (match) => match !== item
          );
          this.onUpload();
          this.$message.success("替换成功");
        } else {
          this.$message.warning("未获取到替换内容");
        }
      } catch (error) {
        console.error("替换失败:", error);
        this.$message.error(error.response?.data?.message || "替换失败");
      }
    },

    // 修改批量替换方法
    async replaceAll() {
      this.batchReplaceLoading = true;
      try {
        // 收所有配
        const allLocations = this.matchResults.map((item) => {
          return item.replace(/[\[\]【】]/g, "");
        });

        // 格式化请求参数
        const params = {
          template_location: [],
          middle_layer_location: [],
          tech_report_location: [],
          other_location: [],
        };

        // 遍历所有位置并分类
        allLocations.forEach((location) => {
          const type = this.getDocumentType(location);
          Object.keys(params).forEach((key) => {
            if (type === key) {
              params[key].push(location);
            } else {
              params[key].push("");
            }
          });
        });
        params.project_id = this.currentData.id;

        // 发送批量请求
        const response = await axios.post(
          `${process.env.VUE_APP_BASE_API}/project-raw-data/batch-content`,
          params,
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        );

        if (response.status === 200 && response.data) {
          const replacementContents = response.data.data.matched_data;

          if (replacementContents && replacementContents.length > 0) {
            // 更新所有内容
            this.TemList.forEach((el, index) => {
              let updatedContent = el.content;

              // 遍历所有替换内容和对应匹配项
              this.matchResults.forEach((item) => {
                // 提取编号的函数只需定义一
                const getCodeFromItem = (searchItem) => {
                  const cleanItem = searchItem.replace(/[\[\]【】]/g, "");
                  const match = cleanItem.match(/([A-Z0-9]+-[A-Z]+-\d+-\d+)/);
                  return match ? match[1] : null;
                };

                // 获取当前项的编号
                const currentCode = getCodeFromItem(item);
                if (!currentCode) return; // 如果没有有效编号，跳过此项

                // 查找匹配的替换内容
                const matchedContent = replacementContents.find(
                  (content) => content.template_location === currentCode
                );

                if (matchedContent?.content) {
                  // 构建替换内容
                  const formattedReplacement = `
                    <span class="replacement-content" data-code="${currentCode}">
                      ${matchedContent.content}
                    </span>
                  `.trim();

                  // 处理表格和其他内容
                  updatedContent = this.processTableContent(
                    updatedContent,
                    item,
                    formattedReplacement
                  );

                  // 记录日志
                  if (process.env.NODE_ENV !== "production") {
                    console.log("替换信息:", {
                      原始编号: currentCode,
                      原始内容: item,
                      替换内容: formattedReplacement,
                    });
                  }
                }
              });

              // 更新内容
              this.$set(this.TemList[index], "content", updatedContent);
            });

            // 更新文档
            await this.onUpload();
            this.matchResults = [];
            this.$message.success("批量替换成功");
            this.replaceVisible = false;
          } else {
            this.$message.warning("未获取到替换内容");
          }
        }
      } catch (error) {
        console.error("批量替换失败:", error);
        this.$message.error(error.response?.data?.message || "批量替换失败");
      } finally {
        this.batchReplaceLoading = false;
      }
    },

    // 辅助方法：获取文档类型
    getDocumentType(code) {
      if (code.includes("-RP-")) return "template_location";
      if (code.includes("-IR-")) return "middle_layer_location";
      if (code.includes("-WE-")) return "tech_report_location";
      return "other_location";
    },

    // 修改处理表格内容的方法，添加对多个替换的支持
    processTableContent(content, searchItem, replacement) {
      if (!content || !searchItem) return content;

      try {
        // 提取搜索项中的编号
        const getCodeFromItem = (item) => {
          const cleanItem = item.replace(/[\[\]【】]/g, "");
          const match = cleanItem.match(/([A-Z0-9]+-[A-Z]+-\d+-\d+)/);
          return match ? match[1] : null;
        };

        const searchCode = getCodeFromItem(searchItem);
        if (!searchCode) {
          console.warn("无法从搜索项中提取编号:", searchItem);
          return content;
        }

        const tempDiv = document.createElement("div");
        tempDiv.innerHTML = content;

        // 新增：递归处理HTML节点
        const processNode = (node) => {
          if (node.nodeType === 3) {
            // 文本节点
            return node.textContent;
          }

          let html = "";
          for (const child of node.childNodes) {
            html += processNode(child);
          }
          return html;
        };

        const handleSplitContent = () => {
          // 先获取纯文本内容用于匹配
          const plainText = processNode(tempDiv);

          // 构建用于匹配分割标记的正则表达式
          const splitRegex = new RegExp(
            `(\\[|【)(.*?)(${searchCode})(.*?)(\\]|】)`,
            "g"
          );

          let currentHtml = tempDiv.innerHTML;

          // 查找所有可能的匹配
          const matches = [
            ...currentHtml.matchAll(/<[^>]+>|\[|\]|【|】|[^<\[\]【】]+/g),
          ];

          // 重建HTML，识别并替换目标编码
          let rebuiltHtml = "";
          let currentMatch = "";
          let isCollecting = false;
          let bracketCount = 0;

          for (let i = 0; i < matches.length; i++) {
            const part = matches[i][0];

            if (part === "[" || part === "【") {
              isCollecting = true;
              bracketCount++;
              currentMatch = part;
              continue;
            }

            if (isCollecting) {
              currentMatch += part;

              if (part === "]" || part === "】") {
                bracketCount--;
                if (bracketCount === 0) {
                  // 检查收集到的内容是否包含目标编码
                  const cleanText = currentMatch.replace(/<[^>]+>/g, "");
                  if (cleanText.includes(searchCode)) {
                    rebuiltHtml += replacement;
                    isCollecting = false;
                    currentMatch = "";
                  } else {
                    rebuiltHtml += currentMatch;
                    isCollecting = false;
                    currentMatch = "";
                  }
                }
              }
            } else {
              rebuiltHtml += part;
            }
          }

          // 处理未闭合的标记
          if (currentMatch) {
            rebuiltHtml += currentMatch;
          }

          // 清理可能的残留标签
          rebuiltHtml = rebuiltHtml
            .replace(/(<span[^>]*>)\s*(<\/span>)/g, "")
            .replace(/(<\/span>)(<span[^>]*>)/g, "")
            .replace(/<a[^>]*><\/a>/g, "")
            .replace(/\s+/g, " ");

          tempDiv.innerHTML = rebuiltHtml;
        };

        handleSplitContent();
        return tempDiv.innerHTML;
      } catch (error) {
        console.error("替换内容时出错:", error);
        console.error("错误详情:", {
          原始内容: content.substring(0, 100) + "...",
          搜索项: searchItem,
          替换内容: replacement,
          错误信息: error.message,
        });
        return content;
      }
    },

    // 添加样式到 convertTextToHtml 方法
    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}; border-collapse: collapse;" class="${tableClass}">`;

          rows.forEach((row, index) => {
            const [label, value] = row.split("|").map((item) => item.trim());
            if (label) {
              tableHtml += "<tr>";
              if (value) {
                // 如果有值，创建两列的行
                tableHtml += `
              <td style="border: 1px solid #000; padding: 8px;">${label}</td>
              <td style="border: 1px solid #000; padding: 8px;">${value}</td>
            `;
              } else {
                // 如果只有标签，创建单列的行（可能是表头）
                tableHtml += `
              <td style="border: 1px solid #000; padding: 8px; font-weight: ${
                index === 0 ? "bold" : "normal"
              }">${label}</td>
            `;
              }
              tableHtml += "</tr>";
            }
          });

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

      // 保持原有的图片和文本处理逻辑不变
      html = html.replace(
        /\[图片:(.*?)\|style=(.*?)\|class=(.*?)\]/g,
        (match, src, style, className) => {
          return `<img src="${src}" alt="图片" style="${style}" class="${className}">`;
        }
      );

      html = html.replace(
        /\[文本:(.*?)\|style=(.*?)\|class=(.*?)\]/g,
        (match, content, style, className) => {
          return `<span style="${style}" class="${className}">${content}</span>`;
        }
      );

      return html;
    },

    /* 选择模版 */
    selTemplate(row) {
      this.currentData = row;
      this.selectedTemplates = []; // 重置选择
      this.selectedTemplateIds = new Set(row.documentIds || []); // 初始化已绑定的模版ID
      this.templateQueryForm.page = 1; // 重置码
      this.loadTemplateList();
    },
    // 处理模版分页变化
    handleTemplatePageChange(page) {
      // 保存当前页的选择状态
      const currentSelection = this.$refs.templateTable.selection;
      if (currentSelection.length > 0) {
        this.selectedPageIds.set(
          this.templateQueryForm.page,
          new Set(currentSelection.map((item) => item.id))
        );
      }

      this.templateQueryForm.page = page;
      this.loadTemplateList();
    },
    // 加载模版表
    loadTemplateList() {
      this.templateLoading = true;
      searchList(this.templateQueryForm)
        .then((res) => {
          if (res.status === 200) {
            this.templateList = res.data.dataList;
            this.templateTotal = res.data.totalRecord;
            this.templateDialogVisible = true;

            // 恢复选中状态
            this.$nextTick(() => {
              const currentPage = this.templateQueryForm.page;
              const currentPageSelected = this.selectedPageIds.get(currentPage);

              this.templateList.forEach((row) => {
                const shouldSelect =
                  this.isAllSelected ||
                  (currentPageSelected && currentPageSelected.has(row.id)) ||
                  this.selectedTemplateIds.has(row.id) ||
                  (this.currentData.documentIds &&
                    this.currentData.documentIds.includes(row.id));

                if (shouldSelect) {
                  this.$refs.templateTable.toggleRowSelection(row, true);
                }
              });
            });
          }
        })
        .finally(() => {
          this.templateLoading = false;
        });
    },

    handleTemplateSelect(selection) {
      const currentPage = this.templateQueryForm.page;
      const currentPageIds = selection.map((item) => item.id);

      // 更新当前页的选择状态
      if (currentPageIds.length > 0) {
        this.selectedPageIds.set(currentPage, new Set(currentPageIds));
      } else {
        this.selectedPageIds.delete(currentPage);
      }

      // 如果之前是全选状态，现在取消了某些选择
      if (this.isAllSelected && selection.length < this.templateList.length) {
        this.isAllSelected = false;
        // 保留其页面的选择和已绑定的模版
        const allSelectedIds = new Set(this.currentData.documentIds || []);
        this.selectedPageIds.forEach((pageIds, page) => {
          if (page !== currentPage) {
            pageIds.forEach((id) => allSelectedIds.add(id));
          }
        });
        // 添加当前页选中的ID
        currentPageIds.forEach((id) => allSelectedIds.add(id));
        this.selectedTemplateIds = allSelectedIds;
      } else {
        // 正常选择模式，保留已绑定的模版
        const existingIds = new Set(this.currentData.documentIds || []);
        this.templateList.forEach((item) => {
          if (currentPageIds.includes(item.id)) {
            this.selectedTemplateIds.add(item.id);
          } else if (!existingIds.has(item.id)) {
            // 只删除非已绑定的模版
            this.selectedTemplateIds.delete(item.id);
          }
        });
      }
    },

    // 处理全选按点击
    handleSelectAll(selection) {
      const currentPage = this.templateQueryForm.page;

      if (selection.length > 0) {
        this.$confirm("是否选择所有页的模版?", "提示", {
          confirmButtonText: "全部选择",
          cancelButtonText: "仅选择当前页",
          type: "info",
        })
          .then(() => {
            // 选择所有页
            this.selectAllPages();
          })
          .catch(() => {
            // 仅选择当前页
            this.selectCurrentPage(selection);
            // 更当前页的选择记录
            this.selectedPageIds.set(
              currentPage,
              new Set(selection.map((item) => item.id))
            );
          });
      } else {
        // 取消全选
        this.isAllSelected = false;
        this.selectedTemplateIds.clear();
        this.selectedPageIds.clear();
        this.$refs.templateTable.clearSelection();
      }
    },

    // 选择所有页
    async selectAllPages() {
      this.isAllSelected = true;
      this.selectedTemplateIds.clear();

      // 获取所有模版ID
      try {
        const allTemplates = await this.getAllTemplates();
        allTemplates.forEach((template) => {
          this.selectedTemplateIds.add(template.id);
        });

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

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

    // 仅选择当前页
    selectCurrentPage(selection) {
      this.isAllSelected = false;
      // 清除前的选择
      this.selectedTemplateIds.clear();
      // 加当前页选中项
      selection.forEach((item) => {
        this.selectedTemplateIds.add(item.id);
      });
    },

    // 获取有模版数据
    async getAllTemplates() {
      const pageSize = 999; // 使用较大的页码一次性获取
      const params = {
        ...this.templateQueryForm,
        page: 1,
        pageSize,
      };

      try {
        const res = await searchList(params);
        if (res.status === 200) {
          return res.data.dataList;
        }
        return [];
      } catch (error) {
        console.error("获取所有模版失败:", error);
        return [];
      }
    },

    // 确认选择
    confirmTemplateSelection() {
      if (this.selectedTemplateIds.size === 0) {
        this.$message.warning("请至少选择一个模版");
        return;
      }
      // 合并已有的文档ID和新选择的ID
      const allDocIds = new Set([
        ...(this.currentData.documentIds || []),
        ...this.selectedTemplateIds,
      ]);
      relate({
        project_id: this.currentData.id,
        doc_ids: JSON.stringify([...allDocIds]),
      }).then((res) => {
        if (res.status !== 200) return;
        this.$message.success("模版关联成功");
        this.closeTemplateDialog();
        this.search();
      });
    },

    // 关对话框
    closeTemplateDialog() {
      this.templateDialogVisible = false;
      this.selectedTemplateIds.clear();
      this.selectedPageIds.clear();
      this.isAllSelected = false;
      this.$refs.templateTable.clearSelection();
    },

    // 输入项目
    enterPro(row) {
      if (row.documentIds.length == 0) {
        this.$message.warning("请先绑定模版!");
        return;
      }

      // 获取绑定模版替换位置信息
      searchTemplateList({ ids: row.documentIds.join(",") || 0 })
        .then(async (res) => {
          if (res.status === 200) {
            const templates = res.data;
            const locations = [];

            // 遍历所有模版，提取替换位置
            templates.forEach((template) => {
              if (template.data) {
                const templateData = JSON.parse(template.data);
                templateData.forEach((item) => {
                  const tempDiv = document.createElement("div");
                  tempDiv.innerHTML = item.content;
                  const plainText = tempDiv.textContent || tempDiv.innerText;

                  const patterns = [
                    /【([A-Z]{1,4}[0-9]{0,2})-([A-Z]{1,4}[0-9]{0,2})-([0-9]{2})-([0-9]{2,3})】/g,
                    /\[([A-Z]{1,4}[0-9]{0,2})-([A-Z]{1,4}[0-9]{0,2})-([0-9]{2})-([0-9]{2,3})\]/g,
                  ];

                  patterns.forEach((pattern) => {
                    let match;
                    while ((match = pattern.exec(plainText)) !== null) {
                      locations.push({
                        template_id: template.id,
                        template_title: template.title,
                        location: match[0],
                        type: this.getDocumentType(match[0]),
                      });
                    }
                  });
                });
              }
            });

            try {
              // 按类型分组位置信息
              const params = {
                template_location: [],
                middle_layer_location: [],
                tech_report_location: [],
                other_location: [],
              };

              // 遍历所有位置并分类
              locations.forEach((loc) => {
                Object.keys(params).forEach((key) => {
                  if (loc.type === key) {
                    params[key].push(loc.location.replace(/[\[\]【】]/g, "")); // 清除括号
                  } else {
                    params[key].push("");
                  }
                });
              });
              params.project_id = row.id;
              // 获取替换内容
              const response = await axios.post(
                `${process.env.VUE_APP_BASE_API}/project-raw-data/batch-content`,
                params,
                {
                  headers: {
                    "Content-Type": "application/json",
                  },
                }
              );

              if (response.status === 200 && response.data) {
                const replacementContents = response.data.data.matched_data;

                // 将位置信息和对应的替换内容组合
                const enrichedLocations = locations.map((loc, index) => ({
                  ...loc,
                  content: replacementContents[index]?.content || null,
                  template_location:
                    replacementContents[index]?.template_location || null,
                  tech_report_location:
                    replacementContents[index]?.tech_report_location || [],
                }));

                // 对整个 enrichedLocations 进行去重
                const uniqueEnrichedLocations = enrichedLocations.reduce(
                  (acc, current) => {
                    const isDuplicate = acc.find(
                      (item) =>
                        item.template_id === current.template_id &&
                        item.location === current.location
                    );

                    if (!isDuplicate) {
                      // 如果不是重复项，添加到结果数组中
                      return [...acc, current];
                    }
                    return acc;
                  },
                  []
                );
                // 使用去重后的数据
                this.$router.push({
                  path: "/project/ProjectInput",
                  query: {
                    id: row.id,
                    projectData: encodeURIComponent(
                      JSON.stringify({
                        locations: uniqueEnrichedLocations, // 使用去重后的数据
                        templates: templates.map((t) => ({
                          id: t.id,
                          title: t.title,
                        })),
                      })
                    ),
                  },
                });
              }
            } catch (error) {
              console.error("获取替换内容失败:", error);
              this.$message.error("获取替换内容失败");
            }
          }
        })
        .catch((error) => {
          console.error("获取模版位置信息失败:", error);
          this.$message.error("获取模版位置信失败");
        });
    },
    /* 产品类别名称 */
    getCategoryTypeName(categoryId) {
      if (!categoryId) return "未分类";
      const product = this.productList.find((item) => item.id === categoryId);
      return product && product.category ? product.category.name : "未知类";
    },

    getCategoryName(categoryId) {
      if (!categoryId) return "未知产品";
      const product = this.productList.find((item) => item.id === categoryId);
      return product ? product.name : "未知产品";
    },

    searchData() {
      let _this = this;
      _this.dialogVisible = false;
      _this.search();
    },

    btnDelete(e) {
      let _this = this;
      let par = {
        id: e,
      };
      _this
        .$confirm("您是否确认删除该记录？", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then((res) => {
          // console.log("AAA")
          deleteProject(par).then((res) => {
            _this.search();
          });
        })
        .catch(() => {});
    },

    //编辑
    btnEdit(e) {
      let _this = this;
      _this.currentDataId = e.id;
      _this.dialogVisible = true;
    },

    onClose(needRefresh) {
      console.log("onClose triggered with needRefresh:", needRefresh); // 添加调试日志
      this.currentDataId = 0;
      this.dialogVisible = false;
      if (needRefresh) {
        this.search();
      }
    },

    handleUpdate() {
      this.search(); // 添加额外的更新处理方法
    },

    //搜索
    async search() {
      try {
        const res = await searchProject(this.queryForm);
        if (!res) return;

        // 获取所有项目的完成度
        const calculatePromises = res.data.dataList.map(async (item) => {
          try {
            const calcRes = await calculate({ id: item.id });
            if (calcRes.status === 200) {
              item.calculate = calcRes.data.completionRate;
            }
          } catch (err) {
            console.error(`获取项目${item.id}完成度失败:`, err);
            item.calculate = 0;
          }
        });

        await Promise.all(calculatePromises);

        this.dataList = res.data.dataList;
        this.recordCount = res.data.totalRecord;
        this.pageTotal = res.data.totalPage;
      } catch (err) {
        console.error("搜索失败:", err);
        this.$message.error("获取项目列表失");
      }
    },
    //修改分页
    ChangePage(e) {
      let _this = this;
      _this.queryForm.page = e;
      _this.search();
    },
    init() {
      searchCategory().then((res) => {
        if (res.status !== 200) return;
        this.categoryList = res.data.dataList;
      });
      /* 获取阶段 */
      getphases().then((res) => {
        this.currentPhaseList = res.data.options;
      });
      /* 获取目前态 */
      getstatus().then((res) => {
        this.getstatusList = res.data.options;
      });
      /* 获取客户列表 */
      searchCustomer({ page: 1, pageSize: 999 }).then((res) => {
        this.customList = res.data.dataList;
      });
      /* 获取产品列表 */
      searchProduct({ page: 1, pageSize: 999 }).then((res) => {
        this.productList = res.data.dataList;
      });
    },
    // 新增：处理导出命令
    async handleExport(command, row) {
      switch (command) {
        case "word":
          await this.exportDocumentWithHtmlDocx(row); //this.exportDocument(row);
          break;
        case "pdf":
          await this.exportToPDF(row);
          break;
        case "pdf-to-word": // 添加新的命令类型
          const pdfResult = await this.exportToPDF_url(row);
          /* if (pdfResult && pdfResult.file_path) {
            await this.convertPDFToWord(pdfResult.file_path);
          } */
          break;
      }
    },
    /* 过去pdf链接 */
    async exportToPDF_url(template) {
      try {
        // 解析模版内容
        const templateData = JSON.parse(template.data || "[]");

        // 创建一个临时的容器来存放内容
        const contentContainer = document.createElement("div");
        contentContainer.className = "content";

        // 处理每个模版段落
        templateData.forEach((item) => {
          const templateSection = document.createElement("div");
          templateSection.className = "template-textarea";
          templateSection.innerHTML = item.content;
          contentContainer.appendChild(templateSection);
        });

        // 处理所有输入框
        contentContainer
          .querySelectorAll('input[type="text"]')
          .forEach((input) => {
            const span = document.createElement("span");
            span.textContent = input.value;
            input.parentNode.replaceChild(span, input);
          });

        // 构建HTML内容
        let contentData = `<!DOCTYPE html>
        <html>
          <head>
            <meta charset="UTF-8">
            <style>
              @page {
                size: A4;
                margin: 2cm;
              }
              body {
                font-family: Arial, sans-serif;
                font-size: 12pt;
                line-height: 1.5;
              }
              /* 添加图片控制样式 */
              img {
                max-width: 100%;
                max-height: 100vh;
                object-fit: contain;
                page-break-inside: avoid;
              }
              /* 图片容器样式 */
              .image-container {
                width: 100%;
                text-align: center;
                margin: 10px 0;
                page-break-inside: avoid;
              }
              table {
                width: 100%;
                border-collapse: collapse;
              }
              td, th {
                border: 1px solid black;
                padding: 5px;
              }
              .template-textarea {
                page-break-after: always;
              }
              .TOC {
                display: none !important;
              }
            </style>
          </head>
          <body>
            ${this.processImages(contentContainer.innerHTML)}
          </body>
        </html>`;

        /*    // 处理表格样式
        contentData = contentData
          .replaceAll("<table ", `<table style="border-collapse: collapse;" `)
          .replaceAll("<td>", `<td style="border: 1px solid black;">`); */
        const formData = new FormData();
        formData.append("content", contentData);
        formData.append("title", template.title);
        // 调用导出接口，指定导出类型为 PDF
        const res = await axios.post(
          `${process.env.VUE_APP_BASE_API}/document/htmlPDFWord`,
          formData,
          {
            headers: {
              "Content-Type": "multipart/form-data", // 设置请求头为form-data
            },
          }
        ); /* await htmlPDFWord({
          content: contentData,
          title: template.title,
        }); */

        if (res.status !== 200) {
          this.$alert(res.errMsg);
          return;
        }
        console.log(res);
        // 处理文件下载
        const link = document.createElement("a");
        link.href = res.data.data.file_path;
        link.download = res.data.data.file_name;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        this.$message.success("导出成功");

        // 处理文件下载
        return res.data; // 返回结果，包含 file_path
      } catch (error) {
        console.error("导出PDF失败:", error);
        this.$alert("导出PDF时发生错误，请稍后重试。");
      }
    },
    // 添加新的 exportToPDF 方法
    async exportToPDF(template) {
      try {
        // 解析模版内容
        const templateData = JSON.parse(template.data || "[]");

        // 创建一个临时的容器来存放内容
        const contentContainer = document.createElement("div");
        contentContainer.className = "content";

        // 处理每个模版段落
        templateData.forEach((item) => {
          const templateSection = document.createElement("div");
          templateSection.className = "template-textarea";
          templateSection.innerHTML = item.content;
          contentContainer.appendChild(templateSection);
        });

        // 处理所有输入框
        contentContainer
          .querySelectorAll('input[type="text"]')
          .forEach((input) => {
            const span = document.createElement("span");
            span.textContent = input.value;
            input.parentNode.replaceChild(span, input);
          });

        // 构建HTML内容
        let contentData = `<!DOCTYPE html>
        <html>
          <head>
            <meta charset="UTF-8">
            <style>
              @page {
                size: A4;
                margin: 2cm;
              }
              body {
                font-family: Arial, sans-serif;
                font-size: 12pt;
                line-height: 1.5;
              }
              /* 添加图片控制样式 */
              img {
                max-width: 100%;
                max-height: 100vh;
                object-fit: contain;
                page-break-inside: avoid;
              }
              /* 图片容器样式 */
              .image-container {
                width: 100%;
                text-align: center;
                margin: 10px 0;
                page-break-inside: avoid;
              }
              table {
                width: 100%;
                border-collapse: collapse;
              }
              td, th {
                border: 1px solid black;
                padding: 5px;
              }
              .template-textarea {
                page-break-after: always;
              }
              .TOC {
                display: none !important;
              }
            </style>
          </head>
          <body>
            ${this.processImages(contentContainer.innerHTML)}
          </body>
        </html>`;

        /*    // 处理表格样式
        contentData = contentData
          .replaceAll("<table ", `<table style="border-collapse: collapse;" `)
          .replaceAll("<td>", `<td style="border: 1px solid black;">`); */

        // 调用导出接口，指定导出类型为 PDF
        const res = await exportToPDF({
          content: contentData,
          title: template.title,
        });

        if (res.status !== 200) {
          this.$alert(res.errMsg);
          return;
        }

        // 处理文件下载
        const link = document.createElement("a");
        link.href = res.data.file_path;
        link.download = res.data.file_name;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        this.$message.success("导出成功");
        return res.data; // 返回结果，包含 file_path
      } catch (error) {
        console.error("导出PDF败:", error);
        this.$alert("导出PDF时发生错误，请稍后重试。");
      }
    },
    // 添加处理图片的辅助方法
    processImages(content) {
      const tempDiv = document.createElement("div");
      tempDiv.innerHTML = content;
      // 处理所有图片
      tempDiv.querySelectorAll("img").forEach((img) => {
        // 创建图片容器
        const container = document.createElement("div");
        container.className = "image-container";
        // 获取所有可能的尺寸来源
        let width =
          img.getAttribute("width") || img.style.width || img.width || null;
        let height =
          img.getAttribute("height") || img.style.height || img.height || null;
        // 移除单位并转换为数字
        if (typeof width === "string") {
          width = parseInt(width.replace(/[^0-9]/g, ""));
        }
        if (typeof height === "string") {
          height = parseInt(height.replace(/[^0-9]/g, ""));
        }
        // 如果没有尺寸，创建一个临时图片来获取实际尺寸
        if (!width || !height) {
          const tempImg = new Image();
          tempImg.src = img.src;
          width = tempImg.width || 595; // 默认宽度
          height = tempImg.height || Math.round(width * 0.75); // 默认高度比例
        }
        // 确保数值有效
        width = Math.max(1, parseInt(width));
        height = Math.max(1, parseInt(height));
        // 处理尺寸
        const maxWidth = 595; // A4纸宽度（像素，减去边距）
        if (width > maxWidth) {
          // 等比例缩放
          const aspectRatio = width / height;
          const newHeight = Math.round(maxWidth / aspectRatio);
          width = maxWidth;
          height = newHeight;
        }
        // 同时设置style和属性
        img.style.width = `${width}px`;
        img.style.height = `${height}px`;
        img.setAttribute("width", width);
        img.setAttribute("height", height);
        // 将图片包装在容器中
        img.parentNode.insertBefore(container, img);
        container.appendChild(img);
      });
      return tempDiv.innerHTML;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./dataList.scss";
.match-results {
  margin-top: 20px;

  .match-item {
    padding: 10px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .match-content {
      flex: 1;
      display: flex;
      gap: 20px;
    }

    .actions {
      margin-left: 10px;
    }
  }
}
// 完成度文字样式
.completion-high {
  color: #67c23a;
  font-weight: bold;
}

.completion-medium {
  color: #e6a23c;
  font-weight: bold;
}

.completion-low {
  color: #f56c6c;
  font-weight: bold;
}

// 添加PDF相关样式
.content {
  background: white;

  .template-textarea {
    page-break-after: always;

    table {
      width: 100%;
      border-collapse: collapse;

      td,
      th {
        border: 1px solid black;
        padding: 5px;
      }
    }
  }
}
</style>
