<template>
  <div>
    <GlobalLayout title="靶标保障方案">
      <!-- 主页面内容 -->
      <template #header-controls>
        <div class="header-actions">
          <el-button type="primary" @click="saveSolution">保存方案</el-button>
          <el-button class="blue-btn" @click="exportAsWord">导出为Word</el-button>
          <el-button class="blue-btn">查看试验任务详情</el-button>
          <!-- 查看子方案下拉菜单 -->
          <el-dropdown trigger="click" @command="handleCommand">
            <el-button class="blue-btn" icon="el-icon-folder-opened">
              查看子方案<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="interference" icon="el-icon-warning-outline">干扰方案</el-dropdown-item>
              <el-dropdown-item command="measurement" icon="el-icon-odometer">测量方案</el-dropdown-item>
              <el-dropdown-item command="target" icon="el-icon-aim">靶标方案</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </template>

      <el-container class="main-container dark-theme">
        <!-- 左侧树形结构 - 深色背景 -->
        <el-aside width="280px" class="tree-container dark-tree-bg">
          <el-card shadow="never" class="tree-card dark-card">
            <div slot="header" class="tree-header dark-header">
              <span>方案目录</span>
              <div>
                <el-button icon="el-icon-plus" size="mini" @click="openAddChapterDialog"></el-button>
                <el-button icon="el-icon-delete" size="mini" @click="deleteSection"></el-button>
              </div>
            </div>
            <!-- 横向滚动容器 -->
            <div class="tree-wrapper" >
              <el-tree
                  ref="solutionTree"
                  :data="treeList"
                  node-key="id"
                  :props="treeProps"
                  :expand-on-click-node="false"
                  :highlight-current="true"
                  @node-click="handleNodeClick"
                  class="dark-tree"
              >
                <span slot-scope="{ node, data }" class="custom-tree-node">
                  <i :class="data.icon || 'el-icon-folder'" class="tree-icon"></i>
                  <span>{{ node.label }}</span>
                </span>
              </el-tree>
            </div>
          </el-card>
        </el-aside>

        <!-- 右侧方案编辑器 -->
        <el-main class="editor-container">
          <el-card shadow shadow="never" class="editor-card-card dark-card">
            <div slot="header" class="editor-header dark-header">
              <span>{{ currentSection ? currentSection.chapterName : '方案编辑器' }}</span>
              <div v-if="currentSection">
                <el-button
                    icon="el-icon-edit"
                    size="mini"
                    @click="editSectionTitle"
                ></el-button>
              </div>
            </div>

            <!-- 文档式表单区域 -->
            <div class="document-form" v-if="currentSection">
              <!-- 根据章节类型显示不同编辑器 tabel === 0 -->
              <template v-if="currentSection.chapterType === '0'">
                <!-- 表格工具栏 -->
                <div class="table-toolbar" style="margin-bottom: 10px; display: flex; gap: 10px;">
                  <el-button
                      type="primary"
                      size="small"
                      @click="addTableRow"
                  >
                    <i class="el-icon-plus"></i> 添加行
                  </el-button>
                  <el-button
                      type="warning"
                      size="small"
                      @click="addTableColumn"
                  >
                    <i class="el-icon-plus"></i> 添加列
                  </el-button>
                  <el-button
                      type="info"
                      size="small"
                      @click="openEditHeadersModal"
                  >
                    <i class="el-icon-edit"></i> 编辑表头
                  </el-button>
                </div>

                <el-table
                    :data="currentSection.data"
                    border
                    style="width: 100%; margin-bottom: 15px;"
                    class="dark-table"
                    :key="tableKey"
                >
                  <el-table-column
                      v-for="(col, index) in currentSection.columns"
                      :key="col.prop"
                      :prop="col.prop"
                      :label="col.label"
                  >
                    <!-- 单元格内容 -->
                    <template slot-scope="scope">
                      <el-input
                          v-model="scope.row[col.prop]"
                          class="dark-input"
                          size="small"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作">
                    <template slot-scope="scope">
                      <el-button
                          icon="el-icon-delete"
                          size="mini"
                          type="danger"
                          @click="deleteTableRow(scope.$index)"
                      ></el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
              <!-- 文件上传类型章节 -->
              <template v-else-if="currentSection.chapterType === '2'">
                <div class="upload-section">
                  <el-upload
                      class="upload-demo"
                      action="#"
                      list-type="picture-card"
                      :on-preview="handleFilePreview"
                      :on-remove="handleFileRemove"
                      :before-remove="beforeFileRemove"
                      :on-change="handleFileChange"
                      multiple
                      :limit="5"
                      :on-exceed="handleFileExceed"
                      :file-list="currentSection.files || []"
                      :auto-upload="false"
                      accept="image/jpeg,image/png,image/gif"
                  >
                    <i class="el-icon-plus"></i>
                    <div slot="tip" class="el-upload__tip">
                      支持上传jpg、png、gif格式图片，单张不超过500kb，最多上传5张
                    </div>
                  </el-upload>
                </div>
              </template>

              <template v-else>
                <!-- 富文本编辑器 -->
                <WangEditor
                    v-model="currentSection.chapterValue"
                    :height="600"
                    :disabled="false"
                    @change="handleContentChange"
                    @upload-image="handleImageUpload"
                />
              </template>
            </div>

            <div v-else class="empty-editor">
              <el-empty description="请从左侧选择方案节点进行编辑" class="dark-empty"></el-empty>
            </div>
          </el-card>
        </el-main>
      </el-container>
    </GlobalLayout>

    <!-- 图片预览弹窗 -->
    <el-dialog
        title="图片预览"
        :visible.sync="previewDialogVisible"
        width="80%"
        :modal="true"
        :close-on-click-modal="true"
    >
      <div class="preview-dialog-content">
        <img
            :src="previewImageUrl"
            :alt="previewImageName"
            class="full-preview-image"
            v-if="previewImageUrl"
        >
        <div v-else>图片加载失败</div>
      </div>
    </el-dialog>

    <!-- 编辑章节标题弹窗 -->
    <el-dialog
        title="编辑章节标题"
        :visible.sync="editTitleDialogVisible"
        width="30%"
    >
      <el-input v-model="tempTitle"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editTitleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEditTitle" style="margin-right: 20px">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加列弹窗 -->
    <el-dialog
        title="添加新列"
        :visible.sync="addColumnDialogVisible"
        width="30%"
    >
      <el-form :model="newColumnForm" ref="newColumnForm">
        <el-form-item label="列标题" prop="label" :rules="[{ required: true, message: '请输入列标题', trigger: 'blur' }]">
          <el-input v-model="newColumnForm.label"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addColumnDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddColumn">确定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑表头弹窗 -->
    <el-dialog
        title="编辑表头"
        :visible.sync="editHeadersModalVisible"
        width="50%"
        :before-close="cancelEditHeaders"
    >
      <el-table
          :data="tempHeaders"
          border
          class="dark-table"
      >
        <el-table-column label="序号" type="index" width="60"></el-table-column>
        <el-table-column label="列标题">
          <template slot-scope="scope">
            <el-input
                v-model="tempHeaders[scope.$index].label"
                class="dark-input"
                placeholder="请输入列标题"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
                icon="el-icon-delete"
                size="mini"
                type="danger"
                @click="removeTempHeader(scope.$index)"
                :disabled="tempHeaders.length <= 1"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 10px; text-align: right;">
        <el-button size="small" @click="addTempHeader">
          <i class="el-icon-plus"></i> 添加列
        </el-button>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelEditHeaders">取消</el-button>
        <el-button type="primary" @click="confirmEditHeaders">保存修改</el-button>
      </span>
    </el-dialog>

    <!-- 添加章节弹窗 -->
    <el-dialog
        title="添加新章节"
        :visible.sync="addChapterDialogVisible"
        width="30%"
    >
      <el-form :model="chapterForm" ref="chapterForm" :rules="chapterFormRules">
        <el-form-item label="章节名称" prop="chapterName">
          <el-input v-model="chapterForm.chapterName" placeholder="请输入章节名称"></el-input>
        </el-form-item>
        <el-form-item label="章节类型" prop="chapterType">
          <el-select v-model="chapterForm.chapterType" placeholder="请选择章节类型">
            <el-option label="富文本" value="1"></el-option>
            <el-option label="表格" value="0"></el-option>
            <el-option label="图片上传" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addChapterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddChapter">确定</el-button>
      </span>
    </el-dialog>

    <!-- 删除列确认弹窗 -->
    <el-dialog
        title="确认删除"
        :visible.sync="deleteColumnDialogVisible"
        width="30%"
    >
      <p>确定要删除这 {{ columnsToDeleteCount }} 列吗？此操作不可撤销。</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteColumnDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDeleteColumns">确定删除</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import GlobalLayout from '@/components/Components/GlobalLayout.vue'
import WangEditor from "@/components/Components/WangEditor.vue";
import { saveAs } from 'file-saver';
import JSZip from 'jszip';
import Docxtemplater from 'docxtemplater';
import PizZipUtils from 'pizzip/utils/index.js';
import {
  addParentId,
  flattenTree,
  restructureForest,
  schemeChapterInsert,
  schemeChapterTree, schemeChapterUpdateList
} from "@/api/planningScheme";
import { MessageBox, Message, Loading } from 'element-ui';
import {doUpload} from "@/api/tool/ossTool";
import {exportSolutionToWord} from "@/views/planningSchem/comprehensive/wordExporter";

function loadFile(url, callback) {
  PizZipUtils.getBinaryContent(url, callback);
}

export default {
  components: {
    WangEditor,
    GlobalLayout
  },
  data() {
    return {
      editTitleDialogVisible: false,
      tempTitle: '',
      currentSection: null,  // 初始化为null而不是空对象
      // 图片预览相关
      previewDialogVisible: false,
      previewImageUrl: '',
      previewImageName: '',
      // 编辑表头弹窗
      editHeadersModalVisible: false,
      // 临时表头数据，用于弹窗编辑
      tempHeaders: [],
      // 原始表头数据，用于取消编辑时恢复
      originalHeaders: [],
      // 添加列弹窗
      addColumnDialogVisible: false,
      // 添加章节弹窗
      addChapterDialogVisible: false,
      // 删除列弹窗
      deleteColumnDialogVisible: false,
      // 要删除的列数量
      columnsToDeleteCount: 0,
      // 要删除的列索引
      columnsToDelete: [],
      // 新列表单数据
      newColumnForm: {
        chapterName: '',
        prop: ''
      },
      // 章节表单数据
      chapterForm: {
        chapterName: '',
        chapterType: '1' // 默认富文本类型
      },
      // 章节表单验证规则
      chapterFormRules: {
        chapterName: [
          { required: true, message: '请输入章节名称', trigger: 'blur' },
          { min: 1, max: 50, message: '章节名称长度在1到50个字符', trigger: 'blur' }
        ],
        chapterType: [
          { required: true, message: '请选择章节类型', trigger: 'change' }
        ]
      },
      batchId: null,
      treeList: [],
      // 树形结构数据 - 保留原有完整目录结构
      treeData: [
        {
          id: 'part1',
          chapterName: '标题',
          icon: 'el-icon-collection',
          chapterValue: '<h1 style="text-align: center">关于下发XXXX任务XXXX试验供靶实施方案的通知</h1>' +
              '<p><i>[本次编辑方式为半自动式编辑方式，需用户根据实际需求手动编辑！]</i> </p>',
        }
        // 其他树节点数据...
      ],
      treeProps: {
        children: 'children',
        label: 'chapterName'
      },
      // 方案表单数据
      solutionForm: {
        title: '靶标保障方案',
        version: 'V1.0',
        createDate: new Date().toLocaleDateString(),
        sections: []
      },
      // 用于强制刷新表格的key
      tableKey: 0
    }
  },
  mounted() {
    if (this.$route.query.batchId) {
      this.batchId = this.$route.query.batchId;
    } else {
      return;
    }
    this.getTree()
  },
  methods: {
    // 打开添加章节弹窗
    openAddChapterDialog() {
      // 重置表单
      this.chapterForm = {
        chapterName: '',
        chapterType: '1'
      };
      // 清空表单验证
      if (this.$refs.chapterForm) {
        this.$refs.chapterForm.resetFields();
      }
      // 显示弹窗
      this.addChapterDialogVisible = true;
    },

    // 确认添加章节
    confirmAddChapter() {
      this.$refs.chapterForm.validate(async (valid) => {
        if (valid) {
          // 生成唯一ID
          const newId = this.generateUUID();

          // 根据选择的类型初始化不同内容
          let newSection = {
            id: newId,
            chapterName: this.chapterForm.chapterName,
            chapterType: this.chapterForm.chapterType,
            parentId: '0' // 默认根节点
          };

          // 根据章节类型初始化内容
          switch(this.chapterForm.chapterType) {
            case '0': // 表格类型
              newSection.columns = [
                { prop: 'col1', label: '列1' }
              ];
              newSection.data = [
                { col1: '' }
              ];
              newSection.chapterValue = JSON.stringify({
                data: newSection.data,
                columns: newSection.columns
              });
              break;
            case '1': // 富文本类型
              newSection.chapterValue = '<p>请输入内容...</p>';
              break;
            case '2': // 图片上传类型 - 每个章节独立存储文件
              newSection.chapterValue = '';
              newSection.files = []; // 初始化空文件数组
              break;
          }

          // 如果有选中节点，作为子节点添加
          if (this.currentSection) {
            newSection.parentId = this.currentSection.id;
            if (!this.currentSection.children) {
              this.$set(this.currentSection, 'children', []);
            }
            this.currentSection.children.push(newSection);
          } else {
            // 否则添加到根节点
            this.treeList.push(newSection);
          }

          // 关闭弹窗
          this.addChapterDialogVisible = false;

          // 刷新树并选中新节点
          this.$nextTick(() => {
            this.$refs.solutionTree.setCurrentKey(newId);
            this.handleNodeClick(newSection);
          });

          Message.success('章节添加成功');
        }
      });
    },

    // 生成UUID
    generateUUID() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0;
        const v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    },

    // 处理富文本内容变化
    handleContentChange(html) {
      if (this.currentSection) {
        this.currentSection.chapterValue = html;
      }
    },

    async getTree() {
      try {
        const res = await schemeChapterTree({ batchId: this.batchId })
        this.treeList = res.data || [];

        function setTable(item) {
          // 确保每个文件上传类型章节都有独立的files数组
          if (item.chapterType === '2' && item.fileJson) {
            const fileList =  JSON.parse(item.fileJson).map(item => {
              return {
                uid: item.uid,
                name: item.fileName,
                type: item.fileType,
                url: item.fileHttp
              }
            })
            this.$set(item, 'files', fileList);
          }

          if (item.chapterType === '0') { // 表格类型
            try {
              const data = item.chapterValue ? JSON.parse(item.chapterValue) : {};
              // 初始化 columns：用 $set 确保每个属性响应式
              const columns = (data.columns && data.columns.length)
                  ? data.columns.map(col => {
                    const newCol = {};
                    this.$set(newCol, 'prop', col.prop || `col${Date.now()}`); // 唯一prop
                    this.$set(newCol, 'label', col.label || `列${data.columns.indexOf(col) + 1}`); // 初始label
                    return newCol;
                  })
                  : [{ prop: 'col1', label: '列1' }]; // 默认列
              this.$set(item, 'columns', columns); // 响应式赋值columns

              // 初始化 data：确保每行有对应列的prop
              const tableData = (data.data && data.data.length)
                  ? data.data.map(row => {
                    const newRow = {};
                    columns.forEach(col => {
                      this.$set(newRow, col.prop, row[col.prop] || ''); // 响应式赋值行数据
                    });
                    return newRow;
                  })
                  : [{ [columns[0].prop]: '' }]; // 默认行
              this.$set(item, 'data', tableData); // 响应式赋值data

              // 同步 chapterValue（避免数据不一致）
              this.$set(item, 'chapterValue', JSON.stringify({
                data: tableData,
                columns: columns.map(({ prop, label }) => ({ prop, label }))
              }));
            } catch (e) {
              // 解析失败时初始化默认结构
              const defaultColumns = [{ prop: 'col1', label: '列1' }];
              const defaultData = [{ col1: '' }];
              this.$set(item, 'columns', defaultColumns);
              this.$set(item, 'data', defaultData);
              this.$set(item, 'chapterValue', JSON.stringify({ data: defaultData, columns: defaultColumns }));
              console.warn('表格数据解析失败，已初始化默认结构', e);
            }
          }
        }

        function traverseTree(node) {
          if (node && node.length > 0) {
            node.forEach(item => {
              setTable.call(this, item); // 绑定this，确保$set生效
              if (item.children) traverseTree.call(this, item.children);
            });
          }
        }

        traverseTree.call(this, this.treeList);
      } catch (error) {
        console.error('获取树形结构失败', error);
      }
    },

    // 处理图片上传
    handleImageUpload(file, insertFn) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const imgUrl = e.target.result;
        insertFn(imgUrl);
      };
      reader.readAsDataURL(file);
    },

    // 树节点点击事件 - 确保文件数据隔离
    handleNodeClick(data) {
      // 重置表格编辑状态和选中列
      this.editHeadersModalVisible = false;
      this.tableKey = 0; // 重置表格key
      this.previewDialogVisible = false; // 关闭图片预览

      // 确保文件上传类型章节有files属性
      if (data.chapterType === '2' && !data.files) {
        this.$set(data, 'files', []);
      }

      // 使用this.$set来设置currentSection，确保响应式
      this.$set(this, 'currentSection', data);

      // 如果是新节点，初始化内容
      if (!this.currentSection.chapterValue &&
          !['0', '2'].includes(this.currentSection.chapterType)) {
        this.currentSection.chapterValue = '<p>请输入内容...</p>';
      }
    },

    // 文件上传相关方法
    handleFileChange(file, fileList) {
      // 为每个文件创建临时URL用于预览
      if (file.raw) {
        file.objectUrl = URL.createObjectURL(file.raw);
      }
      // 更新当前章节的文件列表
      this.$set(this.currentSection, 'files', fileList);
    },

    handleFilePreview(file) {
      // 显示图片预览弹窗
      this.previewImageUrl = file.url || file.objectUrl;
      this.previewImageName = file.name;
      this.previewDialogVisible = true;
    },

    handleFileRemove(file, fileList) {
      // 释放文件的object URL，避免内存泄漏
      if (file.objectUrl) {
        URL.revokeObjectURL(file.objectUrl);
      }
      // 更新当前章节的文件列表
      this.$set(this.currentSection, 'files', fileList);
    },

    beforeFileRemove(file) {
      return MessageBox.confirm(`确定要删除图片 "${file.name}" 吗？`);
    },

    handleFileExceed(files, fileList) {
      Message.warning(`当前限制选择 5 张图片，本次选择了 ${files.length} 张，共选择了 ${files.length + fileList.length} 张`);
    },

    // 截断长文件名
    truncateFileName(name, maxLength = 15) {
      if (name.length <= maxLength) return name;
      return name.substring(0, maxLength) + '...';
    },

    // 编辑章节标题
    editSectionTitle() {
      if (this.currentSection) {
        this.tempTitle = this.currentSection.chapterName;
        this.editTitleDialogVisible = true;
      }
    },

    // 确认编辑标题
    confirmEditTitle() {
      if (this.tempTitle && this.currentSection) {
        this.currentSection.chapterName = this.tempTitle;
        this.editTitleDialogVisible = false;
        Message.success('标题修改成功');
      }
    },

    // 删除章节
    deleteSection() {
      if (!this.currentSection) {
        Message.warning('请先选择要删除的节点');
        return;
      }

      // 如果是文件上传章节，删除前释放所有object URL
      if (this.currentSection.chapterType === '2' && this.currentSection.files) {
        this.currentSection.files.forEach(file => {
          if (file.objectUrl) {
            URL.revokeObjectURL(file.objectUrl);
          }
        });
      }

      MessageBox.confirm(
          `确定删除 "${this.currentSection.chapterName}" 节点吗?`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        this.removeNode(this.treeList, this.currentSection.id);
        this.currentSection = null;
        Message.success('删除成功');
      }).catch(() => {});
    },

    // 递归删除节点
    removeNode(nodes, id) {
      for (let i = 0; i < nodes.length; i++) {
        if (nodes[i].id === id) {
          // 释放该节点的所有图片URL
          if (nodes[i].chapterType === '2' && nodes[i].files) {
            nodes[i].files.forEach(file => {
              if (file.objectUrl) {
                URL.revokeObjectURL(file.objectUrl);
              }
            });
          }
          nodes.splice(i, 1);
          return true;
        }
        if (nodes[i].children && nodes[i].children.length) {
          if (this.removeNode(nodes[i].children, id)) {
            return true;
          }
        }
      }
      return false;
    },

    // 添加表格行
    addTableRow() {
      if (this.currentSection && this.currentSection.chapterType === '0') {
        const newRow = {};
        this.currentSection.columns.forEach(col => {
          newRow[col.prop] = '';
        });
        this.currentSection.data.push(newRow);
      }
    },

    // 删除表格行
    deleteTableRow(index) {
      if (this.currentSection && this.currentSection.chapterType === '0') {
        this.currentSection.data.splice(index, 1);
        // 确保至少保留一行
        if (this.currentSection.data.length === 0) {
          this.addTableRow();
        }
      }
    },

    // 打开添加列弹窗
    addTableColumn() {
      if (this.currentSection && this.currentSection.chapterType === '0') {
        this.newColumnForm = {
          label: '',
          prop: ''
        };
        this.addColumnDialogVisible = true;
      }
    },

    grert() {
      const timestamp = Date.now();
      const randomNum = Math.floor(Math.random() * 1000);
      return `column_${timestamp}_${randomNum}`;
    },

    // 确认添加列
    confirmAddColumn() {
      this.$refs.newColumnForm.validate((valid) => {
        if (valid) {
          // 检查字段名是否已存在
          const propExists = this.currentSection.columns.some(col => col.label === this.newColumnForm.label);
          if (propExists) {
            Message.error('标题已存在，请更换');
            return;
          }
          this.newColumnForm.prop = this.grert();
          // 添加新列定义
          this.currentSection.columns.push({
            label: this.newColumnForm.label,
            prop: this.newColumnForm.prop
          });

          // 为现有行添加新字段
          this.currentSection.data.forEach(row => {
            this.$set(row, this.newColumnForm.prop, '');
          });

          this.addColumnDialogVisible = false;
          this.tableKey++; // 刷新表格
          Message.success('列添加成功');
        }
      });
    },

    // 打开编辑表头弹窗
    openEditHeadersModal() {
      if (!this.currentSection || this.currentSection.chapterType !== '0') return;

      // 深拷贝当前表头数据到临时数组，避免直接修改原数据
      this.tempHeaders = JSON.parse(JSON.stringify(this.currentSection.columns));
      // 保存原始表头用于取消编辑时恢复
      this.originalHeaders = JSON.parse(JSON.stringify(this.currentSection.columns));

      this.editHeadersModalVisible = true;
    },

    // 在弹窗中添加临时列
    addTempHeader() {
      const newProp = this.grert();
      this.tempHeaders.push({
        prop: newProp,
        label: `新列${this.tempHeaders.length + 1}`
      });
    },

    // 在弹窗中移除临时列
    removeTempHeader(index) {
      if (this.tempHeaders.length <= 1) {
        Message.warning('至少需要保留一列');
        return;
      }

      this.tempHeaders.splice(index, 1);
    },

    // 确认编辑表头
    confirmEditHeaders() {
      // 验证列标题
      const labels = this.tempHeaders.map(header => header.label.trim());

      // 检查空标题
      const emptyIndex = labels.findIndex(label => !label);
      if (emptyIndex !== -1) {
        Message.warning(`第${emptyIndex + 1}列标题不能为空`);
        return;
      }

      // 检查重复标题
      const duplicates = [];
      labels.forEach((label, index) => {
        if (labels.indexOf(label) !== index && !duplicates.includes(label)) {
          duplicates.push(label);
        }
      });

      if (duplicates.length > 0) {
        Message.warning(`存在重复的列标题: ${duplicates.join(', ')}`);
        return;
      }

      // 找出被删除的列的prop
      const deletedProps = this.originalHeaders
          .map(header => header.prop)
          .filter(prop => !this.tempHeaders.some(h => h.prop === prop));

      // 更新列定义
      this.currentSection.columns = JSON.parse(JSON.stringify(this.tempHeaders));

      // 处理行数据：删除被移除列的数据，添加新列的数据
      this.currentSection.data.forEach(row => {
        // 删除被移除列的数据
        deletedProps.forEach(prop => {
          this.$delete(row, prop);
        });

        // 为新列添加空数据
        this.currentSection.columns.forEach(col => {
          if (row[col.prop] === undefined) {
            this.$set(row, col.prop, '');
          }
        });
      });

      // 刷新表格
      this.tableKey++;

      // 关闭弹窗
      this.editHeadersModalVisible = false;
      Message.success('表头编辑成功');
    },

    // 取消编辑表头
    cancelEditHeaders() {
      this.editHeadersModalVisible = false;
    },

    // 执行删除列操作
    confirmDeleteColumns() {
      if (!this.columnsToDelete.length) return;

      // 从后往前删除，避免索引混乱
      this.columnsToDelete.forEach(index => {
        // 获取要删除的字段名
        const propToRemove = this.currentSection.columns[index].prop;

        // 从列定义中删除
        this.currentSection.columns.splice(index, 1);

        // 从每行数据中删除对应的字段
        this.currentSection.data.forEach(row => {
          this.$delete(row, propToRemove);
        });
      });

      // 关闭弹窗并重置状态
      this.deleteColumnDialogVisible = false;
      this.columnsToDelete = [];
      this.tableKey++; // 刷新表格

      Message.success(`成功删除 ${this.columnsToDeleteCount} 列`);
    },

    // 保存方案 - 修复节点选中问题
    async saveSolution() {
      // 显示全局加载
      const loading = Loading.service({
        lock: true,
        text: '正在保存方案...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      try {

        // 收集所有章节数据
        const allSections = await this.collectAllSections(this.treeList);

        this.solutionForm.sections = flattenTree(allSections);

        const res = await schemeChapterUpdateList({
          data: this.solutionForm.sections,
          batchId: this.batchId
        });

        if (res.data) {
          Message.success('方案保存成功');
          // 重新获取树形结构
          await this.getTree();

          // 清空选中节点
          this.$set(this, 'currentSection', null);
        }
      } catch (error) {
        console.error('保存方案失败', error);
        Message.error('保存方案失败');
      } finally {
        // 关闭加载
        loading.close();
      }
    },

    // 展开节点的所有父节点
    expandNodeParents(nodeId) {
      if (!this.$refs.solutionTree) return;

      // 获取节点的所有父节点ID
      const parentIds = this.findNodeParentIds(this.treeList, nodeId);

      // 展开所有父节点
      parentIds.forEach(parentId => {
        this.$refs.solutionTree.expand(parentId);
      });
    },

    // 查找节点的所有父节点ID
    findNodeParentIds(nodes, targetId, parentIds = []) {
      for (const node of nodes) {
        if (node.id === targetId) {
          return parentIds;
        }

        if (node.children && node.children.length) {
          const found = this.findNodeParentIds(node.children, targetId, [...parentIds, node.id]);
          if (found) return found;
        }
      }
      return null;
    },

    // 根据ID查找节点
    findNodeById(nodes, id) {
      for (const node of nodes) {
        if (node.id === id) {
          return node;
        }
        if (node.children && node.children.length) {
          const found = this.findNodeById(node.children, id);
          if (found) return found;
        }
      }
      return null;
    },

    // 收集所有章节数据
    async collectAllSections(nodes, result = []) {
      for (const node of nodes) { // 使用for循环支持异步操作
        const sectionData = {
          id: node.id,
          parentId: node.parentId,
          chapterName: node.chapterName,
          chapterType: node.chapterType || '0',
          chapterValue: node.chapterValue || '',
          children: []
        };

        // 处理表格数据（保持不变）
        if (node.chapterType === '0') {
          sectionData.tableData = node.data;
          sectionData.columns = node.columns;
          sectionData.chapterValue = JSON.stringify({
            data: node.data,
            columns: node.columns
          })
        }

        // 处理文件数据 - 先上传再保存
        if (node.chapterType === '2' && node.files && node.files.length) {
          try {
            // 只处理状态为 'ready' 的文件（需要上传的）
            const filesToUpload = node.files.filter(file => file.status === 'ready');
            let uploadResults = [];

            // 如果有需要上传的文件
            if (filesToUpload.length > 0) {
              const uploadPromises = filesToUpload.map(async (file) => {
                const formData = new FormData();
                formData.append('file', file.raw); // 添加文件

                try {
                  const response = await doUpload(formData);

                  if (response.code === 0) {
                    // 使用原始 file.uid，保持关联
                    return {
                      uid: file.uid,
                      fileName: file.name,
                      fileType: response.data.suffix,
                      fileHttp: response.data.fileStoragePath,
                    };
                  } else {
                    // 上传失败，抛出错误
                    throw new Error(`文件 ${file.name} 上传失败: ${response.msg || '未知错误'}`);
                  }
                } catch (error) {
                  console.error(`上传文件 ${file.name} 时发生错误:`, error);
                  throw error;
                }
              });

              // 等待所有上传完成
              uploadResults = await Promise.all(uploadPromises);
            }

            // 处理已上传的文件
            const existingFiles = node.files
                .filter(file => file.status === 'success')
                .map(file => ({
                  uid: file.uid,
                  fileName: file.name,
                  fileType: file.type,
                  fileHttp: file.url
                }));

            // 合并新旧文件信息
            const allFileInfos = [...existingFiles, ...uploadResults];

            // 保存合并后的所有文件信息
            sectionData.fileJson = JSON.stringify(allFileInfos);

          } catch (error) {
            console.error('文件上传失败', error);
            Message.error(error.message || '文件上传失败，请重试');
          }
        }

        // 保留原有字段信息
        if (node.fields) {
          sectionData.fields = node.fields;
        }

        result.push(sectionData);

        // 递归处理子节点
        if (node.children && node.children.length) {
          await this.collectAllSections(node.children, sectionData.children);
        }
      }
      return result;
    },


    // 导出为Word
    async exportAsWord() {
      try {
        await exportSolutionToWord(this.batchId);
        this.$message.success('导出Word成功');
      } catch (error) {
        this.$message.error(error.message || '导出Word失败');
      }
      // // 收集数据
      // this.collectAllSections(this.treeList);
      //
      // // 生成HTML内容用于导出Word
      // const htmlContent = this.generateExportHtml();
      //
      // const blob = new Blob(['\ufeff', htmlContent], {
      //   type: 'application/msword'
      // });
      //
      // saveAs(blob, `${this.solutionForm.title}.doc`);
    },

    // 生成导出的HTML内容
    generateExportHtml() {
      let html = `
        <html>
          <head>
            <meta charset="UTF-8">
            <title>${this.solutionForm.title}</title>
            <style>
              body { font-family: SimSun; }
              .title { text-align: center; font-size: 24px; margin: 20px 0; }
              .subtitle { text-align: center; margin: 10px 0; }
              h1 { font-size: 20px; margin: 15px 0; }
              h2 { font-size: 18px; margin: 12px 0; }
              h3 { font-size: 16px; margin: 10px 0; }
              p { margin: 8px 0; line-height: 1.5; }
              table { border-collapse: collapse; width: 100%; margin: 10px 0; }
              table, th, td { border: 1px solid #000; padding: 5px; }
              th { background-color: #f0f0f0; }
              .section { margin: 15px 0; }
              .file-item { margin: 5px 0; }
              .image-preview { max-width: 200px; margin: 10px 0; }
              .gantt-task { margin: 5px 0; padding: 5px; background-color: #f5f5f5; }
            </style>
          </head>
          <body>
            <div class="title">${this.solutionForm.title}</div>
            <div class="subtitle">版本：${this.solutionForm.version}</div>
            <div class="subtitle">日期：${this.solutionForm.createDate}</div>
      `;

      // 添加所有章节内容
      html += this.generateSectionsHtml(this.treeList, 1);

      html += `
          </body>
        </html>
      `;

      return html;
    },

    // 生成章节HTML
    generateSectionsHtml(nodes, level) {
      let html = '';
      nodes.forEach(node => {
        const tag = `h${level}`;
        html += `<div class="section">`;
        html += `<${tag}>${node.chapterName}</${tag}>`;

        // 根据类型添加内容
        if (node.chapterType === '1' && node.chapterValue) {
          html += `<div class="content">${node.chapterValue}</div>`;
        }

        // 表格内容
        if (node.chapterType === '0' && node.data && node.columns) {
          html += '<table>';
          // 表头
          html += '<tr>';
          node.columns.forEach(col => {
            html += `<th>${col.label}</th>`;
          });
          html += '</tr>';
          // 表体
          node.data.forEach(row => {
            html += '<tr>';
            node.columns.forEach(col => {
              html += `<td>${row[col.prop] || ''}</td>`;
            });
            html += '</tr>';
          });
          html += '</table>';
        }

        // 图片内容
        if (node.chapterType === '2' && node.fileJson) {
          html += '<div class="images">';
          html += '<p>图片列表：</p>';
          JSON.parse(node.fileJson).forEach(file => {
            // 只在有URL的情况下才添加图片标签
            if (file.fileHttp || file.objectUrl) {
              html += `<p><img src="${file.fileHttp || file.objectUrl}" class="image-preview" alt="${file.fileName}"></p>`;
            }
            html += `<p>${file.fileName}</p>`;
          });
          html += '</div>';
        }

        // 递归处理子节点
        if (node.children && node.children.length) {
          html += this.generateSectionsHtml(node.children, level + 1);
        }

        html += `</div>`;
      });
      return html;
    },

    // 格式化文件大小显示
    formatFileSize(bytes) {
      if (bytes < 1024) return bytes + ' B';
      else if (bytes < 1048576) return (bytes / 1024).toFixed(2) + ' KB';
      else return (bytes / 1048576).toFixed(2) + ' MB';
    },

    // 处理下拉菜单命令
    handleCommand(command) {
      switch(command) {
        case 'interference':
          Message.info('查看干扰方案');
          break;
        case 'measurement':
          Message.info('查看测量方案');
          break;
        case 'target':
          Message.info('查看靶标方案');
          break;
      }
    }
  },
  // 组件销毁时清理所有临时URL
  beforeDestroy() {
    // 递归清理所有图片的临时URL
    function cleanObjectUrls(nodes) {
      nodes.forEach(node => {
        if (node.chapterType === '2' && node.files) {
          node.files.forEach(file => {
            if (file.objectUrl) {
              URL.revokeObjectURL(file.objectUrl);
            }
          });
        }
        if (node.children && node.children.length) {
          cleanObjectUrls(node.children);
        }
      });
    }

    cleanObjectUrls(this.treeList);
  }
}
</script>
<style scoped>
/* 深色主题基础样式 */
.dark-theme {
  background-color: #1f2a38;
  color: #e0e6ed;
}

/* 左侧树结构背景色 */
.dark-tree-bg {
  background-color: #1f2a38;
}

/* 卡片样式 */
.dark-card {
  background-color: #2d3a4b;
  border: 1px solid #425163;
  color: #e0e6ed;
}

.dark-card ::v-deep .el-card__header {
  background-color: #1f2a38;
  border-bottom: 1px solid #425163;
  color: #ffffff;
}

/* 头部样式 */
.dark-header {
  color: #ffffff;
  border-bottom: 1px solid #425163;
}

/* 树形结构样式 - 深色背景 */
.dark-tree ::v-deep .el-tree {
  background-color: #2d3a4b;
  color: #e0e6ed;
}

.dark-tree ::v-deep .el-tree-node__content {
  height: 36px;
  transition: all 0.3s;
  background-color: #2d3a4b;
}

.dark-tree ::v-deep .el-tree-node__content:hover {
  background-color: rgba(64, 158, 255, 0.1);
}

.dark-tree ::v-deep .el-tree-node:focus > .el-tree-node__content {
  background-color: rgba(64, 158, 255, 0.2);
}

.tree-icon {
  margin-right: 5px;
  color: #409EFF;
}

/* 表单样式 */
.dark-input ::v-deep .el-input__inner {
  background-color: #1f2a38;
  border: 1px solid #425163;
  color: #e0e6ed;
}

.dark-table ::v-deep .el-table {
  background-color: #2d3a4b;
  color: #e0e6ed;
}

.dark-table ::v-deep .el-table th {
  background-color: #1f2a38;
  border-bottom: 1px solid #425163;
}

.dark-table ::v-deep .el-table tr {
  background-color: #2d3a4b;
}

.dark-table ::v-deep .el-table tr:nth-child(2n) {
  background-color: #283544;
}

.dark-table ::v-deep .el-table td {
  border-bottom: 1px solid #425163;
}

/* 布局样式 */
.main-container {
  height: calc(100vh - 60px);
}

.tree-container {
  border-right: 1px solid #425163;
  height: 100%;
}

.tree-card {
  height: 100%;
  border-radius: 0;
  border: none;
  .el-card__body {
    padding: 0;
  }
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 8px;
}

.editor-container {
  padding: 0;
  height: 100%;
  background-color: #1f2a38;
}

.editor-card {
  height: 100%;
  border-radius: 0;
  border: none;
  overflow: auto;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.document-form {
  padding: 20px;
}

.empty-editor {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: auto;
}

.dark-empty ::v-deep .el-empty__description {
  color: #8796ad;
}

::v-deep .el-upload--picture-card{
  background-color: #fdfdfd1c;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background-color: #425163;
  border-radius: 3px;
}

::-webkit-scrollbar-track {
  background-color: #1f2a38;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 滚动容器：限制高度，允许横向滚动 */
.tree-wrapper {
  width: 254px;
  max-height: calc(100vh - 140px);
  overflow-x: auto;
  overflow-y: auto;
}

.tree-wrapper::-webkit-scrollbar {
  height: 6px;
}

.tree-wrapper::-webkit-scrollbar-thumb {
  background-color: #888;
  border-radius: 3px;
}

.tree-wrapper::-webkit-scrollbar-thumb:hover {
  background-color: #555;
}

.custom-tree .el-tree-node__content {
  white-space: nowrap;
  min-width: 100%;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  flex-nowrap: nowrap;
  min-width: max-content;
}

/* 图片上传和预览样式 */
.upload-section {
  margin-top: 10px;
}

.image-preview-container {
  margin-top: 20px;
  padding-top: 10px;
  border-top: 1px dashed #425163;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
  margin-top: 10px;
}

.image-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.preview-image {
  width: 100%;
  height: 120px;
  cursor: pointer;
  border: 1px solid #425163;
  border-radius: 4px;
  background-color: #1f2a38;
}

.image-info {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 5px;
  font-size: 12px;
}

.image-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 110px;
}

.delete-image {
  color: #f56c6c;
  padding: 0;
}

.image-error {
  width: 100%;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #8796ad;
  background-color: #1f2a38;
  border: 1px solid #425163;
  border-radius: 4px;
}

/* 图片预览弹窗样式 */
.preview-dialog-content {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
}

.full-preview-image {
  max-width: 100%;
  max-height: 80vh;
  object-fit: contain;
}

</style>
