<template>
  <div class="information-container">
    <!-- 添加搜索栏 -->
    <div class="search-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="名称">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="技术文档位置">
          <el-input
            v-model="queryParams.tech_report_location"
            placeholder="请输入技术文档位置"
            clearable
          />
        </el-form-item>
        <el-form-item label="部门">
          <el-select
            v-model="queryParams.department"
            placeholder="请选择部门"
            clearable
          >
            <el-option
              v-for="(item, index) in departList"
              :key="index"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery" type="danger">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="batch-operation">
      <el-button type="primary" :disabled="selectedRows.length== 0" @click="handleBatchDepartment">批量修改部门</el-button>
    </div>
    <el-table :data="projectList" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="sequence" label="序号" width="80">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-right: 10px">{{ scope.row.sequence }}</span>
            <i
              class="el-icon-edit"
              @click="handleEdit(scope.row)"
              style="cursor: pointer; margin-left: 5px"
            ></i>
          </div>
        </template>
      </el-table-column>
      <!--       <el-table-column prop="project_name" label="项目名称" /> -->
      <el-table-column prop="name" label="文件名称" />
      <el-table-column prop="tech_report_location" label="技术文档位置" />
      <el-table-column prop="department" label="部门" />
      <el-table-column prop="content" label="内容" width="450">
        <template slot-scope="scope">
          <div class="content-cell">
            <span class="content-text">{{
              getPlainText(scope.row.content)
            }}</span>
            <i
              class="el-icon-edit"
              @click="handleEditContent(scope.row)"
              style="cursor: pointer; margin-left: 5px"
            ></i>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" sortable />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleEditInfo(scope.row)"
            >编辑信息</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.page_size"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      title="修改序号"
      width="30%"
      append-to-body
      v-el-drag-dialog
    >
      <el-form :model="sequenceForm" label-width="80px">
        <el-form-item label="序号">
          <el-input-number
            v-model="sequenceForm.sequence"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSequence">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 添加内容编辑弹窗 -->
    <el-dialog
      title="编辑内容"
      :visible.sync="contentDialogVisible"
      :close-on-click-modal="false"
      width="80%"
    >
      <div style="overflow: auto">
        <CanvasEditor
          ref="wordEditor"
          :edit-mode="Modetype"
          :html-data="htmlData"
          :doc-json="docJson"
          :editor-options="editorOptions"
          :key="keys"
          @save="save"
          @is-save="getSave"
        ></CanvasEditor>
      </div>
      <!--   </el-form-item>
        </el-form> -->
      <div slot="footer">
        <el-button @click="contentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleContentSubmit">确定</el-button>
      </div>
    </el-dialog>
    <!-- 添加新的编辑信息对话框 -->
    <el-dialog
      title="编辑信息"
      :visible.sync="infoDialogVisible"
      width="30%"
      append-to-body
    >
      <el-form :model="infoForm" label-width="80px">
        <el-form-item label="文件名称">
          <el-input v-model="infoForm.name" placeholder="请输入文件名称" />
        </el-form-item>
        <el-form-item label="部门">
          <el-select v-model="infoForm.department" placeholder="请选择部门">
            <el-option
              v-for="(item, index) in departList"
              :key="index"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="infoDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitInfo">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 添加批量修改部门的对话框 -->
    <el-dialog
      title="批量修改部门"
      :visible.sync="batchDepartDialogVisible"
      width="30%"
    >
      <el-form :model="batchDepartForm" label-width="80px">
        <el-form-item label="部门">
          <el-select v-model="batchDepartForm.department" placeholder="请选择部门">
            <el-option
              v-for="(item, index) in departList"
              :key="index"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDepartDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchDepartment">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script>
import {
  projectList,
  sequence,
  Templatelist,
  TemplateUpdate,
  departments,
  projectTemUpdate,
  updateInfo,
  batchUpdateInfo
} from "@/api/knowledge";
import elDragDialog from "@/directive/el-drag-dialog";
import CanvasEditor from "@/components/CanvasEditor/index"; // 确保路径正确
export default {
  components: {
    CanvasEditor, // 使用驼峰式注册
  },
  directives: { elDragDialog },
  name: "Information",
  data() {
    return {
      projectList: [],
      total: 0,
      queryParams: {
        sort_field: "sequence",
        sort_order: "asc",
        page: 1,
        page_size: 10,
        name: "", // 添加名称搜索参数
        tech_report_location: "", // 添加技术文档位置搜索参数
        department: "", // 部门搜索参数
      },
      dialogVisible: false,
      sequenceForm: {
        sequence: 1,
        id: null,
      },
      departList: [],
      /* 编辑内容 */
      contentDialogVisible: false,
      Modetype: "edit",
      htmlData: "", // 编辑器html数据
      docJson: null, // 编辑器getValue数据
      keys: new Date().getTime(), // 给编辑器赋值不刷新的时候，改变key
      contentForm: {
        id: "",
        content: "",
        name: "",
        department: "",
      },
      infoDialogVisible: false,
      infoForm: {
        name: "",
        department: "",
      },
      selectedRows: [], // 存储选中的行
      batchDepartDialogVisible: false,
      batchDepartForm: {
        department: '',
        ids: []
      },
      editorOptions: {},
    };
  },
  methods: {
    // 添加 CanvasEditor 相关的方法
    save(data) {
      // 处理保存逻辑
      console.log("保存数据:", data);
      // 这里可以添加具体的保存实现
    },

    getSave(isSaved) {
      // 处理保存状态
      console.log("是否已保存:", isSaved);
      // 这里可以添加保存状态的处理逻辑
    },
    // 处理内容中的a标签，移除a标签但保持表头样式
    processContentForSave(htmlContent) {
      try {
        if (!htmlContent) return htmlContent;
        
        console.log('开始处理内容，移除a标签但保持表头样式:', htmlContent);
        
        // 创建临时DOM元素来解析HTML
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = htmlContent;
        
        // 处理所有表格
        const tables = tempDiv.querySelectorAll('table');
        tables.forEach(table => {
          // 处理表头行
          const headerRows = table.querySelectorAll('thead tr, tr:first-child');
          headerRows.forEach(headerRow => {
            // 确保表头有背景色
            if (!headerRow.style.backgroundColor) {
              headerRow.style.backgroundColor = '#f5f5f5';
            }
            
            // 获取表头单元格
            const headerCells = headerRow.querySelectorAll('th, td');
            
            // 找到第一个没有a标签的表头单元格作为样式参考
            let referenceCell = null;
            let referenceStyle = null;
            
            for (let cell of headerCells) {
              if (!cell.querySelector('a')) {
                referenceCell = cell;
                referenceStyle = window.getComputedStyle(cell);
                break;
              }
            }
            
            // 如果没找到参考单元格，使用默认样式
            if (!referenceStyle) {
              referenceStyle = {
                getPropertyValue: (prop) => {
                  const defaults = {
                    'font-weight': 'bold',
                    'font-size': '14px',
                    'font-family': 'Arial, sans-serif',
                    'color': '#000000',
                    'background-color': '#f5f5f5',
                    'text-align': 'left'
                  };
                  return defaults[prop] || '';
                }
              };
            }
            
            console.log('参考样式:', {
              fontWeight: referenceStyle.getPropertyValue('font-weight'),
              fontSize: referenceStyle.getPropertyValue('font-size'),
              fontFamily: referenceStyle.getPropertyValue('font-family'),
              color: referenceStyle.getPropertyValue('color'),
              backgroundColor: referenceStyle.getPropertyValue('background-color')
            });
            
            // 处理所有表头单元格
            headerCells.forEach(cell => {
              // 确保表头单元格有背景色
              if (!cell.style.backgroundColor) {
                cell.style.backgroundColor = '#f5f5f5';
              }

              // 获取单元格的原始对齐方式
              const cellComputedStyle = window.getComputedStyle(cell);
              const originalTextAlign = cellComputedStyle.getPropertyValue('text-align') || 
                                       cell.style.textAlign || 
                                       referenceStyle.getPropertyValue('text-align') || 'left';

              // 处理单元格内的超链接
              const cellLinks = cell.querySelectorAll('a');
              cellLinks.forEach(cellLink => {
                const span = document.createElement('span');
                
                // 获取链接的文本内容，并彻底清理中间的换行符
                let linkText = cellLink.textContent;
                
                // 彻底清理文本中间的换行符和多余空白，但保持单词间的单个空格
                // 使用更严格的正则表达式来确保清理所有类型的空白字符
                linkText = linkText.replace(/[\s\n\r\t\f\v]+/g, ' ').trim();
                
                span.textContent = linkText;

                // 应用参考样式
                span.style.fontWeight = referenceStyle.getPropertyValue('font-weight') || 'bold';
                span.style.fontSize = referenceStyle.getPropertyValue('font-size') || '14px';
                span.style.fontFamily = referenceStyle.getPropertyValue('font-family') || 'Arial, sans-serif';
                span.style.color = referenceStyle.getPropertyValue('color') || '#000000';
                
                // 保持原始的对齐方式
                span.style.textAlign = originalTextAlign;

                // 移除链接样式
                span.style.textDecoration = 'none';
                span.style.cursor = 'default';

                console.log('替换a标签，应用样式:', {
                  fontWeight: span.style.fontWeight,
                  fontSize: span.style.fontSize,
                  fontFamily: span.style.fontFamily,
                  color: span.style.color,
                  textAlign: span.style.textAlign,
                  originalTextAlign: originalTextAlign
                });

                cellLink.parentNode.replaceChild(span, cellLink);
              });

              // 确保单元格本身保持正确的对齐方式
              if (!cell.style.textAlign && originalTextAlign !== 'left') {
                cell.style.textAlign = originalTextAlign;
              }
            });
          });
          
          // 处理表格单元格中的超链接（非表头）
          const cellLinks = table.querySelectorAll('td a, tbody a');
          cellLinks.forEach(cellLink => {
            const span = document.createElement('span');
            span.textContent = cellLink.textContent;
            
            // 保持单元格的默认样式
            span.style.color = 'inherit';
            span.style.textDecoration = 'none';
            span.style.cursor = 'default';
            
            cellLink.parentNode.replaceChild(span, cellLink);
          });
        });
        
        // 处理表格外的超链接
        const links = tempDiv.querySelectorAll('a:not(table a)');
        links.forEach(link => {
          const span = document.createElement('span');
          span.textContent = link.textContent;
          
          // 获取父元素的样式
          const parentElement = link.parentElement;
          if (parentElement) {
            const parentStyles = window.getComputedStyle(parentElement);
            
            // 复制重要的样式属性
            const stylesToCopy = [
              'background-color', 'background', 'font-family', 'font-size', 
              'font-weight', 'font-style', 'text-align', 'padding', 'margin',
              'border', 'border-color', 'border-width', 'border-style',
              'color', 'text-decoration'
            ];
            
            stylesToCopy.forEach(styleProp => {
              const value = parentStyles.getPropertyValue(styleProp);
              if (value && value !== 'initial' && value !== 'inherit' && value !== 'transparent') {
                span.style.setProperty(styleProp, value);
              }
            });
          }
          
          // 设置文本样式为普通文本，移除链接样式
          span.style.textDecoration = 'none';
          span.style.cursor = 'default';
          
          // 替换超链接元素
          link.parentNode.replaceChild(span, link);
        });
        
        // 过滤末尾的空格和换行
        let result = this.filterTrailingWhitespace(tempDiv.innerHTML);
        
        // 额外安全措施：对所有表头进行最终的换行符清理
        result = this.finalHeaderCleanup(result);
        
        // 专门清理包含br标签的span元素
        result = this.cleanSpanWithBrTags(result);
        
        console.log('处理完成后的HTML:', result);
        return result;
      } catch (error) {
        console.error('处理内容时出错:', error);
        return htmlContent; // 如果处理失败，返回原始内容
      }
    },

    // 专门清理包含br标签的span元素
    cleanSpanWithBrTags(htmlContent) {
      try {
        if (!htmlContent) return htmlContent;

        // 使用正则表达式直接清理HTML字符串中的问题标签
        let cleanedHtml = htmlContent;
        
        // 清理各种形式的包含br的span标签
        const patterns = [
          // 匹配 <span style="font-family: Arial; font-size: 14;"><br></span> 等具体样式
          /<span[^>]*style="[^"]*font-family:\s*Arial[^"]*"[^>]*>\s*<br\s*\/?>\s*<\/span>/gi,
          // 匹配 <span style="font-family: Arial; font-size: 14;"><br /></span>
          /<span[^>]*style="[^"]*font-family:\s*Arial[^"]*"[^>]*>\s*<br\s+\/>\s*<\/span>/gi,
          // 匹配任何只包含br的span标签（通用模式）
          /<span[^>]*>\s*<br\s*\/?>\s*<\/span>/gi,
          // 匹配任何只包含br/的span标签
          /<span[^>]*>\s*<br\s+\/>\s*<\/span>/gi,
          // 匹配包含多个br的span标签
          /<span[^>]*>\s*(<br\s*\/?>)+\s*<\/span>/gi,
          // 匹配包含空白和br的span标签
          /<span[^>]*>\s*[\s\n\r\t]*(<br\s*\/?>)+[\s\n\r\t]*<\/span>/gi
        ];

        patterns.forEach(pattern => {
          const matches = cleanedHtml.match(pattern);
          if (matches) {
            console.log('发现需要清理的span br标签:', matches);
            cleanedHtml = cleanedHtml.replace(pattern, '');
          }
        });

        if (cleanedHtml !== htmlContent) {
          console.log('清理span br标签完成');
        }

        return cleanedHtml;
      } catch (error) {
        console.error('清理span br标签时出错:', error);
        return htmlContent;
      }
    },

    // 最终的表头清理方法，确保所有表头文本都没有中间的换行符
    finalHeaderCleanup(htmlContent) {
      try {
        if (!htmlContent) return htmlContent;

        // 创建临时DOM元素来解析HTML
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = htmlContent;

        // 处理所有表格的表头
        const tables = tempDiv.querySelectorAll('table');
        tables.forEach(table => {
          // 处理所有表头单元格
          const headerCells = table.querySelectorAll('th, thead td, tr:first-child td');
          
          headerCells.forEach(cell => {
            // 获取所有文本节点
            const textNodes = [];
            const walker = document.createTreeWalker(
              cell,
              NodeFilter.SHOW_TEXT,
              null,
              false
            );
            
            let textNode;
            while (textNode = walker.nextNode()) {
              textNodes.push(textNode);
            }
            
            // 清理所有文本节点
            textNodes.forEach(node => {
              const originalText = node.textContent;
              // 使用最严格的正则表达式清理所有空白字符
              const cleanedText = originalText.replace(/[\s\n\r\t\f\v]+/g, ' ').trim();
              
              if (originalText !== cleanedText) {
                node.textContent = cleanedText;
                console.log('最终清理表头文本:', `"${originalText}" -> "${cleanedText}"`);
              }
            });
            
            // 清理可能存在的空元素和包含br的span
            const emptyElements = cell.querySelectorAll('span, div, p');
            emptyElements.forEach(element => {
              const textContent = element.textContent.trim();
              const hasOnlyBr = element.innerHTML.trim() === '<br>' || 
                               element.innerHTML.trim() === '<br/>' || 
                               element.innerHTML.trim() === '<br />';
              const isEmpty = textContent === '';
              
              if ((isEmpty || hasOnlyBr) && !element.querySelector('img')) {
                element.remove();
                console.log('最终清理：移除空的表头元素:', element, 'innerHTML:', element.innerHTML);
              }
            });
            
            // 特别处理：清理所有包含br标签的span元素
            const spansWithBr = cell.querySelectorAll('span');
            spansWithBr.forEach(span => {
              const innerHTML = span.innerHTML.trim();
              if (innerHTML === '<br>' || innerHTML === '<br/>' || innerHTML === '<br />') {
                span.remove();
                console.log('最终清理：移除只包含br的span元素:', span);
              }
            });
          });
        });

        return tempDiv.innerHTML;
      } catch (error) {
        console.error('最终表头清理时出错:', error);
        return htmlContent;
      }
    },

    // 专门处理表头内容，防止在表头中间添加换行符（适用于所有对齐方式）
    processHeaderContent(headerCell) {
      try {
        // 获取单元格的原始对齐方式
        const cellComputedStyle = window.getComputedStyle(headerCell);
        const textAlign = cellComputedStyle.getPropertyValue('text-align') || 'left';
        
        console.log('处理表头单元格对齐方式:', textAlign, headerCell);
        
        // 获取所有文本节点
        const textNodes = [];
        const walker = document.createTreeWalker(
          headerCell,
          NodeFilter.SHOW_TEXT,
          null,
          false
        );
        
        let textNode;
        while (textNode = walker.nextNode()) {
          textNodes.push(textNode);
        }
        
        // 清理所有文本节点中的换行符和多余空白
        textNodes.forEach(node => {
          const originalText = node.textContent;
          
          // 清理文本中间的换行符和多余空白，但保持单词间的单个空格
          // 这个正则表达式会：
          // 1. 将多个连续的空白字符（包括换行符、制表符、空格）替换为单个空格
          // 2. 清理开头和结尾的空白
          const cleanedText = originalText.replace(/\s+/g, ' ').trim();
          
          if (originalText !== cleanedText) {
            node.textContent = cleanedText;
            console.log('清理表头文本:', `"${originalText}" -> "${cleanedText}"`);
          }
        });
        
        // 确保单元格保持原始的对齐方式
        if (!headerCell.style.textAlign && textAlign !== 'left') {
          headerCell.style.textAlign = textAlign;
        }
        
        // 额外处理：清理单元格内可能存在的空元素和包含br的span
        const emptyElements = headerCell.querySelectorAll('span, div, p');
        emptyElements.forEach(element => {
          // 检查是否为空元素或只包含br标签的span
          const textContent = element.textContent.trim();
          const hasOnlyBr = element.innerHTML.trim() === '<br>' || element.innerHTML.trim() === '<br/>';
          const isEmpty = textContent === '';
          
          if ((isEmpty || hasOnlyBr) && !element.querySelector('img')) {
            element.remove();
            console.log('移除空的表头元素:', element, 'innerHTML:', element.innerHTML);
          }
        });
        
        // 特别处理：清理包含br标签的span元素
        const spansWithBr = headerCell.querySelectorAll('span');
        spansWithBr.forEach(span => {
          // 检查span是否只包含br标签
          const innerHTML = span.innerHTML.trim();
          if (innerHTML === '<br>' || innerHTML === '<br/>' || innerHTML === '<br />') {
            span.remove();
            console.log('移除只包含br的span元素:', span);
          }
        });
        
        return headerCell;
      } catch (error) {
        console.error('处理表头内容时出错:', error);
        return headerCell;
      }
    },

 // 过滤末尾空格和换行的方法 - 只处理文本末尾，不影响格式
 filterTrailingWhitespace(htmlContent) {
      try {
        if (!htmlContent) return htmlContent;

        // 创建临时DOM元素来解析HTML
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = htmlContent;

        // 专门处理表格单元格内容的函数 - 只处理非表头单元格
        const processTableCellContent = (cell) => {
          console.log('处理非表头单元格:', cell, '内容:', cell.innerHTML);

          // 递归处理所有文本节点的末尾空白
          const processTextNodes = (node) => {
            if (node.nodeType === Node.TEXT_NODE) {
              // 清理文本节点末尾的空白字符（包括换行符和空格）
              const original = node.textContent;
              node.textContent = node.textContent.replace(/[\s\n\r\t]+$/, '');
              if (original !== node.textContent) {
                console.log('清理文本节点:', `"${original}" -> "${node.textContent}"`);
              }
            } else if (node.nodeType === Node.ELEMENT_NODE) {
              // 递归处理所有子节点
              Array.from(node.childNodes).forEach(processTextNodes);
            }
          };

          // 处理单元格内的所有文本节点
          Array.from(cell.childNodes).forEach(processTextNodes);

          // 特别处理：清理单元格内嵌套元素末尾的br标签和空白
          const nestedElements = cell.querySelectorAll('span, div, p, strong, em, b, i, a');
          nestedElements.forEach(element => {
            // 递归处理嵌套元素的文本节点
            Array.from(element.childNodes).forEach(processTextNodes);

            // 清理元素末尾的br标签
            let innerHTML = element.innerHTML;
            const originalInnerHTML = innerHTML;

            // 移除末尾的br标签
            innerHTML = innerHTML.replace(/(<br\s*\/?>)+$/gi, '');
            // 移除末尾的空白字符
            innerHTML = innerHTML.replace(/[\s\n\r\t]+$/, '');

            if (innerHTML !== originalInnerHTML) {
              element.innerHTML = innerHTML;
              console.log('清理嵌套元素:', element.tagName, `"${originalInnerHTML}" -> "${innerHTML}"`);
            }
          });

          // 最终清理：直接处理单元格的innerHTML来移除末尾的br和空白
          let cellHTML = cell.innerHTML;
          const originalCellHTML = cellHTML;

          // 多次处理确保彻底清理
          let previousHTML;
          do {
            previousHTML = cellHTML;
            // 移除末尾的br标签
            cellHTML = cellHTML.replace(/(<br\s*\/?>)+$/gi, '');
            // 移除末尾的空白字符（包括换行、空格等）
            cellHTML = cellHTML.replace(/[\s\n\r\t]+$/, '');
            // 移除末尾的空span、div等标签
            cellHTML = cellHTML.replace(/<(span|div|p)[^>]*>\s*<\/\1>$/gi, '');
          } while (cellHTML !== previousHTML);

          if (cellHTML !== originalCellHTML) {
            cell.innerHTML = cellHTML;
            console.log('最终清理非表头单元格:', `"${originalCellHTML}" -> "${cellHTML}"`);
          }

          // 清理单元格内可能存在的空文本节点
          const walker = document.createTreeWalker(
            cell,
            NodeFilter.SHOW_TEXT,
            null,
            false
          );

          let textNode;
          const nodesToRemove = [];
          while (textNode = walker.nextNode()) {
            if (textNode.textContent.trim() === '') {
              nodesToRemove.push(textNode);
            }
          }

          nodesToRemove.forEach(node => node.remove());
        };

        // 处理所有表格，但只处理非表头内容
        const allTables = tempDiv.querySelectorAll('table');
        allTables.forEach(table => {
          console.log('处理表格，但保护表头:', table);

          // 1. 明确保护表头内容：不处理thead中的任何单元格，但需要处理居中对齐的换行符问题
          const theadCells = table.querySelectorAll('thead th, thead td');
          console.log('保护表头单元格数量:', theadCells.length);
          theadCells.forEach(cell => {
            console.log('跳过表头单元格:', cell, '内容:', cell.innerHTML);
            // 使用专门的方法处理表头内容，防止居中表头中间出现换行符
            this.processHeaderContent(cell);
          });

          // 2. 明确保护表格标题行（通常是第一行包含th的行）
          const allRows = table.querySelectorAll('tr');
          const headerRows = [];

          // 识别可能的表头行（包含th的行或第一行）
          allRows.forEach((row, index) => {
            const hasTh = row.querySelector('th');
            const isFirstRow = index === 0;
            if (hasTh || isFirstRow) {
              headerRows.push(row);
              console.log('识别为表头行:', row);
            }
          });

          // 保护表头行中的所有单元格，但需要处理居中对齐的换行符问题
          headerRows.forEach(row => {
            const headerCells = row.querySelectorAll('th, td');
            headerCells.forEach(cell => {
              console.log('保护表头行中的单元格:', cell, '内容:', cell.innerHTML);
              // 使用专门的方法处理表头内容，防止居中表头中间出现换行符
              this.processHeaderContent(cell);
            });
          });

          // 3. 只处理tbody中的非表头td单元格
          const tbodyTds = table.querySelectorAll('tbody td');
          tbodyTds.forEach(td => {
            // 双重检查：确保这个td不在任何表头行中
            const parentRow = td.closest('tr');
            const isInHeaderRow = headerRows.includes(parentRow);

            if (!isInHeaderRow) {
              processTableCellContent(td);
            } else {
              console.log('跳过表头行中的td:', td);
            }
          });

          // 4. 处理没有tbody的表格：只处理非表头行的td
          const hasTbody = table.querySelector('tbody');
          if (!hasTbody) {
            console.log('表格没有tbody，处理非表头行');

            allRows.forEach((row, index) => {
              const isHeaderRow = headerRows.includes(row);

              if (!isHeaderRow) {
                console.log('处理非表头行:', row);
                const cells = row.querySelectorAll('td');
                cells.forEach(cell => {
                  processTableCellContent(cell);
                });
              } else {
                console.log('跳过表头行:', row);
              }
            });
          }

          // 5. 额外安全措施：明确不处理任何th元素，但需要处理居中对齐的换行符问题
          const allThs = table.querySelectorAll('th');
          allThs.forEach(th => {
            console.log('保护所有th元素:', th, '内容:', th.innerHTML);
            // 使用专门的方法处理表头内容，防止居中表头中间出现换行符
            this.processHeaderContent(th);
          });

          // 6. 额外检查：确保没有遗漏需要保护的单元格
          const allCells = table.querySelectorAll('td, th');
          allCells.forEach(cell => {
            const parentRow = cell.closest('tr');
            const isTh = cell.tagName.toLowerCase() === 'th';
            const isInHeaderRow = headerRows.includes(parentRow);
            const isInThead = cell.closest('thead');

            if (isTh || isInHeaderRow || isInThead) {
              console.log('确认保护单元格:', cell.tagName, '在表头中:', cell);
            }
          });
        });

        // 处理非表格内容的文本节点（保持原有逻辑）
        const processGeneralTextNodes = (node) => {
          if (node.nodeType === Node.TEXT_NODE) {
            const original = node.textContent;
            node.textContent = node.textContent.replace(/\s+$/, '');
            if (original !== node.textContent) {
              console.log('清理一般文本节点:', `"${original}" -> "${node.textContent}"`);
            }
          } else if (node.nodeType === Node.ELEMENT_NODE && !node.closest('table')) {
            // 递归处理非表格元素的子节点
            Array.from(node.childNodes).forEach(processGeneralTextNodes);
          }
        };

        // 处理所有子节点的文本末尾空白（跳过表格内容）
        Array.from(tempDiv.childNodes).forEach(processGeneralTextNodes);

        // 获取处理后的HTML并进行最终清理
        let result = tempDiv.innerHTML;

        console.log('初步处理结果:', result);

        // 最终清理步骤（不影响表头，因为表头已经在DOM中保护）
        let previousResult;
        do {
          previousResult = result;

          // 清理整个内容末尾的空白字符
          result = result.replace(/[\s\n\r\t]+$/, '');

          // 清理整个内容末尾的br标签
          result = result.replace(/(<br\s*\/?>)+$/gi, '');

          // 清理末尾的空标签
          result = result.replace(/<(span|div|p)[^>]*>\s*<\/\1>$/gi, '');
          result = result.replace(/<(\w+)[^>]*>(<br\s*\/?>)+<\/\1>$/gi, '');

        } while (result !== previousResult);

        // 清理开头的空白
        result = result.replace(/^[\s\n\r\t]+/, '');

        console.log('最终结果:', result);

        return result;
      } catch (error) {
        console.error('过滤末尾空白时出错:', error);
        return htmlContent; // 如果处理失败，返回原始内容
      }
    },
    // 修改 handleContentSubmit 方法
    async handleContentSubmit() {
      try {
        // 获取编辑器的最新内容
        const editorContent = this.$refs.wordEditor.editorRef.command.getHTML();

        // 处理内容，移除a标签但保持表头样式
        const processedContent = this.processContentForSave(editorContent.main);

        // 更新 contentForm
        this.contentForm.content = processedContent;
        const submitData = {
          ...this.contentForm,
          content: this.contentForm.content,
        };
        await projectTemUpdate(submitData);
        this.$message.success("内容更新成功");
        this.contentDialogVisible = false;
        this.getProjectList();
      } catch (error) {
        this.$message.error("内容更新失败");
      }
    },
    // 修改 handleEditContent 方法，添加编辑器数据的处理
    handleEditContent(row) {
      /*  const selectedProject = this.projectOptions.find(
        (p) => p.id === this.selectedProjectId
      ); */

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

      this.contentForm = {
        id: row.id,
        content: row.content, //processedContent,
      };
      if (row.font_style) {
        this.editorOptions = row.font_style;
      } else {
        this.editorOptions = {
          font: "Arial",
          size: 14,
          bold: false,
          align: "left",
        };
      }
      // 设置编辑器数据
      this.htmlData = processedContent;
      this.Modetype = "edit";
      this.keys = new Date().getTime(); // 强制刷新编辑器

      this.contentDialogVisible = true;
    },

    /* 处理文字 */
    getPlainText(html) {
      if (!html) return "";

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

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

      // 截断文本
      return plainText.length > 50
        ? plainText.substring(0, 50) + "..."
        : plainText;
    },
    // 添加辅助方法：清理空样式属性
    cleanEmptyStyles(html) {
      return html
        .replace(/style=""/g, "")
        .replace(/class=""/g, "")
        .replace(/\s+>/g, ">");
    },
    // 修改回显方法，解析样式
    convertTextToHtml(text) {
      if (!text) return "";

      let html = text;

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

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

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

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

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

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

      return html;
    },
    async getProjectList() {
      try {
        // 修改请求，添加分页参数
        const response = await Templatelist(this.queryParams);
        this.projectList = response.data.list;
        this.total = response.data.total; // 假设后端返回总数
      } catch (error) {
        console.error("获取项目列表失败：", error);
      }
    },
    // 添加分页处理方法
    handleSizeChange(val) {
      this.queryParams.page_size = val;
      this.getProjectList();
    },
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.getProjectList();
    },
    // 获取状态标签类型
    getStatusType(status) {
      const statusMap = {
        5: "success",
        // 可以根据实际状态码添加更多映射
      };
      return statusMap[status] || "info";
    },
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        5: "正常",
        // 可以根据实际状态码添加更多映射
      };
      return statusMap[status] || "未知状态";
    },
    // 添加搜索相关方法
    handleQuery() {
      this.queryParams.page = 1;
      this.getProjectList();
    },
    resetQuery() {
      this.queryParams.name = "";
      this.queryParams.tech_report_location = "";
      this.queryParams.department = "";
      this.handleQuery();
    },
    // 打开编辑序号对话框
    handleEdit(row) {
      this.sequenceForm.sequence = row.sequence;
      this.sequenceForm.id = row.id;
      this.dialogVisible = true;
    },

    // 提交序号修改
    async submitSequence() {
      try {
        await TemplateUpdate({
          id: this.sequenceForm.id,
          new_sequence: this.sequenceForm.sequence,
        });
        this.$message.success("修改序号成功");
        this.dialogVisible = false;
        this.getProjectList(); // 刷新列表
      } catch (error) {
        this.$message.error("修改序号失败：" + error.message);
      }
    },
    init() {
      departments().then((res) => {
        if (res.status !== 200) return;
        this.departList = res.data.departments;
      });
    },
    handleEditInfo(row) {
      this.infoForm = {
        id: row.id,
        name: row.name,
        department: row.department,
      };
      this.infoDialogVisible = true;
    },
    async submitInfo() {
      try {
        await updateInfo(this.infoForm);
        this.$message.success("信息更新成功");
        this.infoDialogVisible = false;
        this.getProjectList(); // 刷新列表
      } catch (error) {
        this.$message.error("信息更新失败：" + error.message);
      }
    },
    // 处理表格多选
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },

    // 打开批量修改部门对话框
    handleBatchDepartment() {
      this.batchDepartForm.department = '';
      this.batchDepartForm.ids = this.selectedRows.map(row => row.id);
      this.batchDepartDialogVisible = true;
    },

    // 提交批量修改部门
    async submitBatchDepartment() {
      try {
        await batchUpdateInfo({
          ids:JSON.stringify(this.batchDepartForm.ids),
          department: this.batchDepartForm.department
        });
        this.$message.success('批量修改部门成功');
        this.batchDepartDialogVisible = false;
        this.getProjectList(); // 刷新列表
      } catch (error) {
        this.$message.error('批量修改部门失败：' + error.message);
      }
    }
  },
  created() {
    this.getProjectList();
    this.init();
  },
};
</script>
  
  <style lang="scss" scoped>
.information-container {
  padding: 20px;
}
.pagination-container {
  display: flex;
  justify-content: flex-end;
}
/* 内容部分样式 */
.content-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .content-text {
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 430px; // 可以根据需要调整最大宽度
  }
}
/* 添加以下样式 */
::v-deep .el-dialog {
  margin-top: 0 !important;
}
.batch-operation {
  margin: 10px 0;
}
</style>