<template>
  <div class="split-screen-editor">
    <!-- 编辑器工具栏 -->
    <div class="editor-tools">
      <div class="mode-switch">
        <button 
          class="mode-btn" 
          :class="{ active: editorMode === 'edit' }"
          @click="editorMode = 'edit'"
        >
          <i class="el-icon-edit"></i>
          编辑
        </button>
        <button 
          class="mode-btn" 
          :class="{ active: editorMode === 'preview' }"
          @click="editorMode = 'preview'"
        >
          <i class="el-icon-view"></i>
          预览
        </button>
        <button 
          class="mode-btn" 
          :class="{ active: editorMode === 'split' }"
          @click="editorMode = 'split'"
        >
          <i class="el-icon-s-unfold"></i>
          分屏
        </button>
      </div>
      
      <div class="tool-actions">
        <span class="word-count">{{ wordCount }} 字</span>
        <el-button size="mini" @click="toggleUsageGuide" icon="el-icon-question">
          {{ showUsageGuide ? '隐藏指南' : '使用指南' }}
        </el-button>
        <el-button size="mini" @click="toggleFullscreen" icon="el-icon-full-screen">
          {{ isFullscreen ? '退出全屏' : '全屏' }}
        </el-button>
        <el-button 
          size="mini" 
          @click="handlePublish" 
          icon="el-icon-upload" 
          type="warning"
          :loading="publishLoading"
          :disabled="!localContent.trim()"
        >
          {{ publishLoading ? '发布中...' : '发布' }}
        </el-button>
      </div>
    </div>

    <!-- 编辑器面板容器 -->
    <div class="editor-container" :class="{ fullscreen: isFullscreen }">
      <el-row :gutter="20">
        <!-- 编辑区域 -->
        <el-col :span="editorMode === 'preview' ? 0 : (editorMode === 'split' ? 12 : 24)">
          <div class="editor-panel" v-show="editorMode !== 'preview'">
            <div class="panel-header">
              <span><i class="el-icon-edit"></i> 富文本编辑</span>
              <div class="panel-actions">
                <el-button size="mini" @click="insertBulletPoint" icon="el-icon-arrow-right">
                  插入圆点
                </el-button>
              </div>
            </div>
            <div class="editor-content">
              <!-- 富文本编辑器 -->
              <div ref="editorContainer" class="tinymce-container">
                <textarea 
                  :id="editorId" 
                  v-model="localContent"
                  @input="handleContentChange"
                ></textarea>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 预览区域 -->
        <el-col :span="editorMode === 'edit' ? 0 : (editorMode === 'split' ? 12 : 24)">
          <div class="editor-panel" v-show="editorMode !== 'edit'">
            <div class="panel-header">
              <span><i class="el-icon-view"></i> 实时预览</span>
              <div class="panel-actions">
                <el-button size="mini" @click="copyHtml" icon="el-icon-document-copy">
                  复制HTML
                </el-button>
              </div>
            </div>
            <div class="preview-content content-display" v-html="previewContent"></div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- TinyMCE 使用指南 -->
    <transition name="slide-fade">
      <div v-show="showUsageGuide" class="usage-guide-panel">
        <el-card shadow="never">
          <div slot="header">
            <span><i class="el-icon-guide"></i> TinyMCE 富文本编辑器使用指南</span>
            <el-button 
              style="float: right; padding: 3px 0; margin-left: 10px;" 
              type="text" 
              @click="toggleUsageGuide"
              icon="el-icon-close"
            >
              关闭指南
            </el-button>
            <el-button 
              style="float: right; padding: 3px 0" 
              type="text" 
              @click="checkDemoEditorStatus"
              icon="el-icon-info"
            >
              检查状态
            </el-button>
          </div>
          
          <div class="guide-content">
            <!-- 功能演示区域 -->
            <div class="guide-section">
              <h4>💡 功能演示区域</h4>
              <p class="demo-description">在下方编辑器中直接尝试各种功能：</p>
              <div class="demo-editor-container">
                <div :id="demoEditorId" class="demo-editor"></div>
              </div>
              <div class="demo-tips">
                <span class="tip-item">💡 提示：可以在此编辑器中直接尝试下方介绍的所有功能</span>
              </div>
            </div>

            <!-- 基础操作 -->
            <div class="guide-section">
              <h4>📝 基础文本编辑</h4>
              <div class="function-grid">
                <div class="function-item">
                  <div class="function-icon">
                    <i class="el-icon-refresh-left"></i>
                  </div>
                  <div class="function-detail">
                    <h5>撤销/重做</h5>
                    <p><kbd>Ctrl + Z</kbd> 撤销 | <kbd>Ctrl + Y</kbd> 重做</p>
                    <span class="tips">快速回退或恢复编辑操作</span>
                  </div>
                </div>
                
                <div class="function-item">
                  <div class="function-icon">
                    <strong>B</strong>
                  </div>
                  <div class="function-detail">
                    <h5>字体样式</h5>
                    <p><kbd>Ctrl + B</kbd> 粗体 | <kbd>Ctrl + I</kbd> 斜体 | <kbd>Ctrl + U</kbd> 下划线</p>
                    <span class="tips">选中文字后使用快捷键或点击工具栏按钮</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 格式设置 -->
            <div class="guide-section">
              <h4>🎨 格式与样式</h4>
              <div class="function-grid">
                <div class="function-item">
                  <div class="function-icon">
                    <i class="el-icon-s-grid"></i>
                  </div>
                  <div class="function-detail">
                    <h5>段落格式</h5>
                    <p>标题1-6、段落、预格式化文本</p>
                    <span class="tips">点击"格式"下拉菜单选择段落样式</span>
                  </div>
                </div>
                
                <div class="function-item">
                  <div class="function-icon">
                    <div class="color-icon"></div>
                  </div>
                  <div class="function-detail">
                    <h5>颜色设置</h5>
                    <p>字体颜色 <span class="color-demo" style="color: #ff0000;">A</span> | 背景颜色 <span class="bg-demo">A</span></p>
                    <span class="tips">选中文字后点击颜色按钮选择颜色</span>
                  </div>
                </div>
                
                <div class="function-item">
                  <div class="function-icon">
                    <i class="el-icon-sort"></i>
                  </div>
                  <div class="function-detail">
                    <h5>文本对齐</h5>
                    <p>左对齐 | 居中 | 右对齐 | 两端对齐</p>
                    <span class="tips">将光标放在段落中，点击对应对齐按钮</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 列表功能 -->
            <div class="guide-section">
              <h4>📋 列表与缩进</h4>
              <div class="function-grid">
                <div class="function-item">
                  <div class="function-icon">
                    <span style="font-size: 18px;">•</span>
                  </div>
                  <div class="function-detail">
                    <h5>无序列表（圆点）</h5>
                    <p>创建带圆点的项目列表</p>
                    <span class="tips">点击圆点按钮或使用"• 圆点"专用按钮</span>
                  </div>
                </div>
                
                <div class="function-item">
                  <div class="function-icon">
                    <span style="font-size: 16px;">1.</span>
                  </div>
                  <div class="function-detail">
                    <h5>有序列表（数字）</h5>
                    <p>创建带数字编号的项目列表</p>
                    <span class="tips">点击数字列表按钮，自动生成编号</span>
                  </div>
                </div>
                
                <div class="function-item">
                  <div class="function-icon">
                    <i class="el-icon-right"></i>
                  </div>
                  <div class="function-detail">
                    <h5>缩进控制</h5>
                    <p><kbd>Tab</kbd> 增加缩进 | <kbd>Shift + Tab</kbd> 减少缩进</p>
                    <span class="tips">用于创建多层级列表结构</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 插入功能 -->
            <div class="guide-section">
              <h4>🔗 插入与媒体</h4>
              <div class="function-grid">
                <div class="function-item">
                  <div class="function-icon">
                    <i class="el-icon-link"></i>
                  </div>
                  <div class="function-detail">
                    <h5>链接插入</h5>
                    <p><kbd>Ctrl + K</kbd> 插入链接</p>
                    <span class="tips">选中文字后按快捷键或点击链接按钮</span>
                  </div>
                </div>
                
                <div class="function-item">
                  <div class="function-icon">
                    <i class="el-icon-picture"></i>
                  </div>
                  <div class="function-detail">
                    <h5>图片插入</h5>
                    <p>支持上传图片或插入图片链接</p>
                    <span class="tips">点击图片按钮，选择本地文件或输入URL</span>
                  </div>
                </div>
                
                <div class="function-item">
                  <div class="function-icon">
                    <i class="el-icon-s-grid"></i>
                  </div>
                  <div class="function-detail">
                    <h5>表格插入</h5>
                    <p>创建和编辑表格数据</p>
                    <span class="tips">点击表格按钮选择行列数，右键编辑表格</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 特殊功能 -->
            <div class="guide-section">
              <h4>🛠️ 高级功能</h4>
              <div class="function-grid">
                <div class="function-item">
                  <div class="function-icon">
                    <i class="el-icon-search"></i>
                  </div>
                  <div class="function-detail">
                    <h5>搜索替换</h5>
                    <p><kbd>Ctrl + F</kbd> 查找 | <kbd>Ctrl + H</kbd> 替换</p>
                    <span class="tips">快速查找和批量替换文本内容</span>
                  </div>
                </div>
                
                <div class="function-item">
                  <div class="function-icon">
                    <i class="el-icon-view"></i>
                  </div>
                  <div class="function-detail">
                    <h5>源码编辑</h5>
                    <p>查看和编辑HTML源代码</p>
                    <span class="tips">点击代码按钮切换到HTML视图</span>
                  </div>
                </div>
                
                <div class="function-item">
                  <div class="function-icon">
                    <i class="el-icon-full-screen"></i>
                  </div>
                  <div class="function-detail">
                    <h5>全屏编辑</h5>
                    <p><kbd>F11</kbd> 或点击全屏按钮</p>
                    <span class="tips">沉浸式编辑体验，<kbd>ESC</kbd>退出</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 快捷键汇总 -->
            <div class="guide-section">
              <h4>⌨️ 快捷键汇总</h4>
              <div class="shortcuts-grid">
                <div class="shortcut-category">
                  <h5>基础编辑</h5>
                  <div class="shortcut-list">
                    <div class="shortcut-item">
                      <kbd>Ctrl + Z</kbd>
                      <span>撤销</span>
                    </div>
                    <div class="shortcut-item">
                      <kbd>Ctrl + Y</kbd>
                      <span>重做</span>
                    </div>
                    <div class="shortcut-item">
                      <kbd>Ctrl + A</kbd>
                      <span>全选</span>
                    </div>
                    <div class="shortcut-item">
                      <kbd>Ctrl + C</kbd>
                      <span>复制</span>
                    </div>
                  </div>
                </div>
                
                <div class="shortcut-category">
                  <h5>格式化</h5>
                  <div class="shortcut-list">
                    <div class="shortcut-item">
                      <kbd>Ctrl + B</kbd>
                      <span>粗体</span>
                    </div>
                    <div class="shortcut-item">
                      <kbd>Ctrl + I</kbd>
                      <span>斜体</span>
                    </div>
                    <div class="shortcut-item">
                      <kbd>Ctrl + U</kbd>
                      <span>下划线</span>
                    </div>
                    <div class="shortcut-item">
                      <kbd>Ctrl + K</kbd>
                      <span>插入链接</span>
                    </div>
                  </div>
                </div>
                
                <div class="shortcut-category">
                  <h5>视图控制</h5>
                  <div class="shortcut-list">
                    <div class="shortcut-item">
                      <kbd>F11</kbd>
                      <span>全屏</span>
                    </div>
                    <div class="shortcut-item">
                      <kbd>ESC</kbd>
                      <span>退出全屏</span>
                    </div>
                    <div class="shortcut-item">
                      <kbd>Ctrl + F</kbd>
                      <span>查找</span>
                    </div>
                    <div class="shortcut-item">
                      <kbd>Ctrl + H</kbd>
                      <span>替换</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 专用功能说明 -->
            <div class="guide-section special-features">
              <h4>⭐ 专用功能说明</h4>
              <div class="special-function">
                <div class="special-icon">
                  <span>•</span>
                </div>
                <div class="special-content">
                  <h5>圆点插入专用按钮</h5>
                  <p>我们为您特别添加了"• 圆点"按钮，专门用于插入黑色圆点符号。</p>
                  <div class="usage-steps">
                    <span class="step">1</span> 将光标定位到需要插入圆点的位置
                    <span class="step">2</span> 点击工具栏中的"• 圆点"按钮
                    <span class="step">3</span> 圆点自动插入，在分屏模式下立即可见
                  </div>
                </div>
              </div>
              
              <div class="special-function">
                <div class="special-icon">
                  <i class="el-icon-s-unfold"></i>
                </div>
                <div class="special-content">
                  <h5>分屏实时预览</h5>
                  <p>左边编辑，右边实时预览，完美解决圆点在预览时才显示的问题。</p>
                  <div class="usage-steps">
                    <span class="step">1</span> 点击工具栏中的"分屏"按钮
                    <span class="step">2</span> 左侧编辑器，右侧实时预览
                    <span class="step">3</span> 圆点和格式化效果立即可见
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </transition>
  </div>
</template>

<script>
import { addDocument } from '../api/documentManagement'

export default {
  name: 'SplitScreenEditor',
  props: {
    /**
     * 编辑器内容
     */
    value: {
      type: String,
      default: ''
    },
    /**
     * 编辑器配置选项
     */
    options: {
      type: Object,
      default: () => ({})
    },
    /**
     * 编辑器高度
     */
    height: {
      type: [String, Number],
      default: 500
    }
  },
  
  data() {
    return {
      localContent: '',
      editorMode: 'split', // 'edit', 'preview', 'split'
      isFullscreen: false,
      wordCount: 0,
      editorInstance: null,
      editorId: `editor_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      showUsageGuide: false, // 使用指南显示状态
      
      // 演示编辑器相关
      demoEditorInstance: null,
      demoEditorId: `demo_editor_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      
      // 文档发布相关
      publishLoading: false,
      documentInfo: {
        title: '',
        subTitle: '',
        type: 0, // 默认文档类型：其他
        lang: 'zh' // 默认中文
      },
      
      // 默认编辑器配置
      defaultOptions: {
        height: this.height,
        menubar: false,
        plugins: [
          'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
          'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
          'insertdatetime', 'media', 'table', 'help', 'wordcount'
        ],
        toolbar: [
          'undo redo | formatselect | bold italic underline strikethrough',
          'forecolor backcolor | alignleft aligncenter alignright alignjustify',
          'bullist numlist outdent indent | removeformat | help'
        ].join(' | '),
        content_style: `
          body { 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
            font-size: 14px; 
            line-height: 1.6;
            color: #2c3e50;
          }
          p { margin: 10px 0; }
          ul, ol { margin: 10px 0; padding-left: 20px; }
          li { margin: 4px 0; }
        `,
        language: 'zh_CN',
        branding: false,
        resize: false,
        statusbar: false,
        placeholder: '开始编写您的内容...',
        setup: (editor) => {
          this.editorInstance = editor;
          
          // 监听内容变化
          editor.on('input', () => {
            this.handleEditorChange();
          });
          
          editor.on('change', () => {
            this.handleEditorChange();
          });
          
          // 添加自定义按钮：插入圆点
          editor.ui.registry.addButton('bulletpoint', {
            text: '• 圆点',
            tooltip: '插入黑色圆点',
            onAction: () => {
              this.insertBulletPoint();
            }
          });
        }
      }
    }
  },
  
  computed: {
    /**
     * 合并后的编辑器配置
     */
    mergedOptions() {
      return {
        ...this.defaultOptions,
        ...this.options,
        height: this.height,
        toolbar: this.defaultOptions.toolbar + ' | bulletpoint'
      }
    },
    
    /**
     * 预览内容 - 格式化HTML
     */
    previewContent() {
      if (!this.localContent) return '<p style="color: #999; text-align: center; padding: 40px;">预览内容将在这里显示...</p>';
      
      // 简单的HTML格式化，确保列表项正确显示
      let formatted = this.localContent;
      
      // 如果内容中包含列表，确保样式正确
      formatted = formatted.replace(/<ul>/g, '<ul style="margin: 10px 0; padding-left: 20px;">');
      formatted = formatted.replace(/<ol>/g, '<ol style="margin: 10px 0; padding-left: 20px;">');
      formatted = formatted.replace(/<li>/g, '<li style="margin: 4px 0;">');
      
      return formatted;
    }
  },
  
  watch: {
    value: {
      handler(newVal) {
        if (newVal !== this.localContent) {
          this.localContent = newVal;
          if (this.editorInstance) {
            this.editorInstance.setContent(newVal);
          }
        }
      },
      immediate: true
    },
    
    localContent() {
      this.updateWordCount();
    }
  },
  
  mounted() {
    this.initEditor();
    this.updateWordCount();
    
    // 监听ESC键退出全屏
    document.addEventListener('keydown', this.handleKeydown);
    
    // 如果使用指南默认打开，延迟初始化演示编辑器
    if (this.showUsageGuide) {
      this.$nextTick(() => {
        setTimeout(() => {
          console.log('页面加载完成，初始化演示编辑器');
          this.initDemoEditor();
        }, 1000); // 给足够时间让主编辑器完全初始化
      });
    }
  },
  
  beforeDestroy() {
    this.destroyEditor();
    this.destroyDemoEditor();
    document.removeEventListener('keydown', this.handleKeydown);
  },
  
  methods: {
    /**
     * 初始化TinyMCE编辑器
     */
    async initEditor() {
      // 确保TinyMCE已加载
      if (typeof window.tinymce === 'undefined') {
        console.error('TinyMCE未加载，请确保已正确引入TinyMCE');
        return;
      }
      
      try {
        await window.tinymce.init({
          selector: `#${this.editorId}`,
          ...this.mergedOptions
        });
        
        console.log('编辑器初始化成功');
      } catch (error) {
        console.error('编辑器初始化失败:', error);
      }
    },
    
    /**
     * 销毁编辑器
     */
    destroyEditor() {
      if (this.editorInstance) {
        this.editorInstance.destroy();
        this.editorInstance = null;
      }
    },
    
    /**
     * 处理编辑器内容变化
     */
    handleEditorChange() {
      if (this.editorInstance) {
        const content = this.editorInstance.getContent();
        this.localContent = content;
        this.$emit('input', content);
        this.$emit('change', content);
      }
    },
    
    /**
     * 处理输入内容变化（fallback）
     */
    handleContentChange(event) {
      const content = event.target.value;
      this.localContent = content;
      this.$emit('input', content);
      this.$emit('change', content);
    },
    
    /**
     * 插入黑色圆点
     */
    insertBulletPoint() {
      if (this.editorInstance) {
        const selection = this.editorInstance.selection;
        const selectedText = selection.getContent({ format: 'text' });
        
        if (selectedText) {
          // 如果有选中文本，在前面添加圆点
          const htmlContent = `• ${selectedText}`;
          this.editorInstance.execCommand('mceReplaceContent', false, htmlContent);
        } else {
          // 如果没有选中文本，直接插入圆点
          this.editorInstance.execCommand('mceInsertContent', false, '• ');
        }
        
        this.editorInstance.focus();
      } else {
        // Fallback：直接在文本框中插入
        const textarea = document.getElementById(this.editorId);
        if (textarea) {
          const start = textarea.selectionStart;
          const end = textarea.selectionEnd;
          const text = textarea.value;
          
          const newText = text.substring(0, start) + '• ' + text.substring(end);
          this.localContent = newText;
          this.$emit('input', newText);
          
          this.$nextTick(() => {
            textarea.focus();
            textarea.setSelectionRange(start + 2, start + 2);
          });
        }
      }
    },
    
    /**
     * 切换全屏模式
     */
    toggleFullscreen() {
      this.isFullscreen = !this.isFullscreen;
      
      if (this.isFullscreen) {
        document.body.style.overflow = 'hidden';
      } else {
        document.body.style.overflow = '';
      }
    },
    
    /**
     * 处理键盘事件
     */
    handleKeydown(event) {
      if (event.key === 'Escape' && this.isFullscreen) {
        this.toggleFullscreen();
      }
    },
    
    /**
     * 更新字数统计
     */
    updateWordCount() {
      // 移除HTML标签后计算字数
      const textContent = this.localContent.replace(/<[^>]*>/g, '');
      this.wordCount = textContent.length;
    },
    
    /**
     * 复制HTML内容
     */
    copyHtml() {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(this.localContent).then(() => {
          this.$message.success('HTML内容已复制到剪贴板');
        }).catch(err => {
          console.error('复制失败:', err);
          this.$message.error('复制失败');
        });
      } else {
        // Fallback方法
        const textArea = document.createElement('textarea');
        textArea.value = this.localContent;
        document.body.appendChild(textArea);
        textArea.select();
        try {
          document.execCommand('copy');
          this.$message.success('HTML内容已复制到剪贴板');
        } catch (err) {
          console.error('复制失败:', err);
          this.$message.error('复制失败');
        }
        document.body.removeChild(textArea);
      }
    },
    
    /**
     * 获取编辑器内容
     */
    getContent() {
      return this.localContent;
    },
    
    /**
     * 设置编辑器内容
     */
    setContent(content) {
      this.localContent = content;
      if (this.editorInstance) {
        this.editorInstance.setContent(content);
      }
    },
    
    /**
     * 清空编辑器内容
     */
    clear() {
      this.setContent('');
    },
    
    /**
     * 切换使用指南显示状态
     */
    toggleUsageGuide() {
      this.showUsageGuide = !this.showUsageGuide;
      
      if (this.showUsageGuide) {
        // 使用指南打开时，延迟初始化演示编辑器
        console.log('使用指南已打开，准备初始化演示编辑器');
        this.$nextTick(() => {
          setTimeout(() => {
            this.initDemoEditor();
          }, 500); // 增加延迟时间确保DOM完全渲染
        });
      } else {
        // 使用指南关闭时，销毁演示编辑器
        console.log('使用指南已关闭，销毁演示编辑器');
        this.destroyDemoEditor();
      }
    },
    
    /**
     * 处理发布操作
     */
    handlePublish() {
      if (!this.localContent.trim()) {
        this.$message.warning('请先输入内容再发布');
        return;
      }
      
      // 显示发布配置对话框
      this.showPublishDialog();
    },
    
    /**
     * 显示发布配置对话框
     */
    showPublishDialog() {
      // 使用更简单的输入对话框
      this.$prompt('请输入文档标题：', '发布文档', {
        confirmButtonText: '发布',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入文档标题',
        inputValue: this.documentInfo.title || `编辑器文档_${new Date().toLocaleDateString()}`,
        inputValidator: (value) => {
          if (!value || !value.trim()) {
            return '文档标题不能为空';
          }
          if (value.trim().length > 100) {
            return '文档标题不能超过100个字符';
          }
          return true;
        }
      }).then(({ value }) => {
        this.documentInfo.title = value.trim();
        
        // 显示文档类型选择
        this.showDocumentTypeDialog();
      }).catch(() => {
        console.log('用户取消发布');
      });
    },
    
    /**
     * 显示文档类型选择对话框
     */
         showDocumentTypeDialog() {
       const documentTypes = [
         { label: '其他', value: 0 },
         { label: '服务条款', value: 1 },
         { label: 'API文档', value: 2 },
         { label: '挖矿教程', value: 3 }
       ];
      
      // 生成选项HTML
      const optionsHtml = documentTypes.map(type => 
        `<option value="${type.value}"${type.value === this.documentInfo.type ? ' selected' : ''}>${type.label}</option>`
      ).join('');
      
      this.$msgbox({
        title: '选择文档类型',
        message: `
          <div style="margin: 10px 0;">
            <label style="display: block; margin-bottom: 8px; font-weight: 600;">文档类型：</label>
            <select id="documentTypeSelect" style="width: 100%; padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;">
              ${optionsHtml}
            </select>
          </div>
          <div style="margin-top: 15px; padding: 10px; background: #f8f9fa; border-radius: 4px; font-size: 13px; color: #606266;">
            <strong>文档信息：</strong><br>
            标题：${this.documentInfo.title}<br>
            字数：${this.wordCount} 字
          </div>
        `,
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确认发布',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            const selectElement = document.getElementById('documentTypeSelect');
            if (selectElement) {
              this.documentInfo.type = parseInt(selectElement.value);
            }
          }
          done();
        }
      }).then(() => {
        this.confirmPublish();
      }).catch(() => {
        console.log('用户取消选择文档类型');
      });
    },
    
    /**
     * 确认发布文档
     */
    async confirmPublish() {
      this.publishLoading = true;
      
      try {
        // 确保获取最新的编辑器内容
        let currentContent = this.localContent;
        if (this.editorInstance) {
          currentContent = this.editorInstance.getContent();
          console.log('发布前 - 从编辑器获取的最新内容:', currentContent);
          console.log('发布前 - 内容长度:', currentContent.length);
          console.log('发布前 - localContent:', this.localContent);
          
          // 同步本地内容
          this.localContent = currentContent;
        } else {
          console.warn('编辑器实例不存在，使用本地内容:', currentContent);
        }
        
        // 如果内容为空或者只有空白标签，提示用户
        const textContent = currentContent.replace(/<[^>]*>/g, '').trim();
        if (!textContent) {
          this.$message.warning('编辑器内容为空，请先输入内容');
          this.publishLoading = false;
          return;
        }
        
        // 准备发送给后端的文档数据（参考 addDocument 接口）
        const manageDocumentVo = {
          id: null, // 新增文档时为 null
          title: this.documentInfo.title,
          subTitle: this.documentInfo.subTitle || '',
          content: currentContent,
          lang: this.$i18n?.locale || this.documentInfo.lang,
          type: this.documentInfo.type
        };
        
        console.log('=== 发布文档数据调试信息 ===');
        console.log('完整参数:', manageDocumentVo);
        console.log('当前语言:', this.$i18n?.locale);
        console.log('内容预览 (前200字符):', currentContent.substring(0, 200));
        console.log('内容是否包含h2标签:', currentContent.includes('<h2>'));
        console.log('内容是否包含h3标签:', currentContent.includes('<h3>'));
        console.log('===========================');
        
        // 调用后端接口发布文档
        const response = await addDocument(manageDocumentVo);
        
        if (response && response.code === 200) {
          this.$message.success('文档发布成功！');
          
          // 触发发布成功事件，传递完整信息
          this.$emit('publish', {
            success: true,
            documentId: response.data?.id,
            title: this.documentInfo.title,
            content: currentContent,
            wordCount: textContent.length,
            timestamp: new Date().toISOString(),
            response: response.data
          });
          
          // 发布成功通知
          this.$notify({
            title: '发布成功',
            message: `文档 "${this.documentInfo.title}" 已成功发布`,
            type: 'success',
            duration: 4000
          });
          
          // 清空本地自动保存
          this.clearAutoSave();
          
        } else {
          throw new Error(response?.message || '发布失败');
        }
        
      } catch (error) {
        console.error('文档发布失败:', error);
        this.$message.error(`发布失败：${error.message || '网络错误'}`);
        
        // 触发发布失败事件
        this.$emit('publish', {
          success: false,
          error: error.message || '发布失败',
          title: this.documentInfo.title,
          content: currentContent || this.localContent
        });
        
      } finally {
        this.publishLoading = false;
      }
    },
    
    /**
     * 初始化演示编辑器
     */
    async initDemoEditor() {
      // 确保TinyMCE已加载
      if (typeof window.tinymce === 'undefined') {
        console.error('TinyMCE未加载，无法初始化演示编辑器');
        return;
      }
      
      // 等待DOM元素完全渲染
      let attempts = 0;
      const maxAttempts = 10;
      
      const waitForElement = () => {
        const element = document.getElementById(this.demoEditorId);
        if (element && this.showUsageGuide) {
          this.doInitDemoEditor();
        } else if (attempts < maxAttempts) {
          attempts++;
          setTimeout(waitForElement, 200);
        } else {
          console.warn('演示编辑器DOM元素未找到，跳过初始化');
        }
      };
      
      waitForElement();
    },
    
    /**
     * 执行演示编辑器初始化
     */
    async doInitDemoEditor() {
      // 如果已经存在实例，先销毁
      if (this.demoEditorInstance) {
        try {
          this.demoEditorInstance.destroy();
        } catch (e) {
          console.warn('销毁旧的演示编辑器实例时出错:', e);
        }
      }
      
            try {
        console.log(`正在初始化演示编辑器，选择器: #${this.demoEditorId}`);
        
        // 演示编辑器的配置（相对简化）
        const demoConfig = {
          height: 200,
          menubar: false,
          plugins: [
            'advlist', 'autolink', 'lists', 'link', 'charmap',
            'searchreplace', 'visualblocks', 'code', 'insertdatetime',
            'table', 'help', 'wordcount'
          ],
          toolbar: [
            'undo redo | formatselect | bold italic underline strikethrough',
            'forecolor backcolor | alignleft aligncenter alignright alignjustify',
            'bullist numlist outdent indent | removeformat | help | bulletpoint'
          ].join(' | '),
          content_style: `
            body { 
              font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
              font-size: 14px; 
              line-height: 1.6;
              color: #2c3e50;
              padding: 10px;
            }
            p { margin: 10px 0; }
            ul, ol { margin: 10px 0; padding-left: 20px; }
            li { margin: 4px 0; }
          `,
          language: 'zh_CN',
          branding: false,
          resize: false,
          statusbar: true,
          placeholder: '在此演示编辑器中尝试各种功能...',
          init_instance_callback: (editor) => {
            this.demoEditorInstance = editor;
            console.log('演示编辑器实例已创建');
            
            // 设置初始演示内容
            setTimeout(() => {
              editor.setContent(`
                <h3>🎯 演示编辑器</h3>
                <p><strong>在这里直接尝试各种功能：</strong></p>
                <ul>
                  <li>选中文字后点击 <strong>粗体</strong>、<em>斜体</em>、<u>下划线</u></li>
                  <li>使用颜色按钮改变文字颜色</li>
                  <li>点击"• 圆点"按钮插入项目符号</li>
                  <li>创建有序或无序列表</li>
                </ul>
                <p>• ALEO矿工必须质押一定数量的ALEO代币</p>
                <p><em>💡 你可以直接编辑这些内容来测试功能！</em></p>
              `);
            }, 200);
          },
          setup: (editor) => {
            // 添加自定义按钮：插入圆点
            editor.ui.registry.addButton('bulletpoint', {
              text: '• 圆点',
              tooltip: '插入黑色圆点',
              onAction: () => {
                editor.insertContent('• ');
                editor.focus();
              }
            });
          }
        };
        
        await window.tinymce.init({
          selector: `#${this.demoEditorId}`,
          ...demoConfig
        });
        
        console.log('演示编辑器初始化成功');
      } catch (error) {
        console.error('演示编辑器初始化失败:', error);
      }
    },
    
    /**
     * 销毁演示编辑器
     */
         destroyDemoEditor() {
       if (this.demoEditorInstance) {
         try {
           this.demoEditorInstance.destroy();
           this.demoEditorInstance = null;
           console.log('演示编辑器已销毁');
         } catch (error) {
           console.error('销毁演示编辑器时出错:', error);
         }
       }
     },
     
     /**
      * 清空自动保存的草稿
      */
     clearAutoSave() {
       try {
         // 清空本地存储的草稿
         const keys = Object.keys(localStorage);
         keys.forEach(key => {
           if (key.startsWith('splitscreen_editor_draft_')) {
             localStorage.removeItem(key);
           }
         });
         console.log('已清空自动保存的草稿');
       } catch (error) {
         console.warn('清空自动保存草稿时出错:', error);
       }
     },
     
     /**
      * 调试方法：检查演示编辑器状态
      */
     checkDemoEditorStatus() {
       console.log('=== 演示编辑器状态检查 ===');
       console.log('使用指南显示状态:', this.showUsageGuide);
       console.log('演示编辑器ID:', this.demoEditorId);
       console.log('DOM元素存在:', !!document.getElementById(this.demoEditorId));
       console.log('演示编辑器实例:', this.demoEditorInstance);
       console.log('TinyMCE可用:', typeof window.tinymce !== 'undefined');
       
       const element = document.getElementById(this.demoEditorId);
       if (element) {
         console.log('DOM元素详情:', {
           id: element.id,
           className: element.className,
           offsetHeight: element.offsetHeight,
           offsetWidth: element.offsetWidth
         });
       }
     }
  }
}
</script>

<style scoped>
/* 编辑器主容器 */
.split-screen-editor {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

/* 编辑器工具栏 */
.editor-tools {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
}

.mode-switch {
  display: flex;
  background: #fff;
  border-radius: 6px;
  padding: 2px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.mode-switch .mode-btn {
  padding: 8px 16px;
  border: none;
  background: transparent;
  cursor: pointer;
  border-radius: 4px;
  font-size: 13px;
  font-weight: 500;
  color: #7f8c8d;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 4px;
}

.mode-switch .mode-btn.active {
  background: #5721E4;
  color: #fff;
  box-shadow: 0 2px 4px rgba(87, 33, 228, 0.2);
}

.mode-switch .mode-btn:hover:not(.active) {
  background: #f0f0f0;
  color: #5721E4;
}

.tool-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.word-count {
  font-size: 12px;
  color: #7f8c8d;
  font-weight: 500;
}

/* 编辑器容器 */
.editor-container {
  transition: all 0.3s ease;
}

.editor-container.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  background: #fff;
  border-radius: 0;
}

/* 编辑器面板 */
.editor-panel {
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  overflow: hidden;
  background: #fff;
  height: 100%;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.panel-header i {
  color: #5721E4;
  margin-right: 6px;
}

.panel-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

/* 编辑器内容区域 */
.editor-content {
  padding: 0;
}

.tinymce-container {
  width: 100%;
}

.tinymce-container textarea {
  width: 100%;
  min-height: 500px;
  border: none;
  outline: none;
  padding: 16px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  font-size: 14px;
  line-height: 1.6;
  resize: vertical;
}

/* 统一的内容显示样式 - 确保编辑器、预览、后端显示一致 */
.content-display {
  /* 核心样式 - 确保空格和格式保持 */
  white-space: pre-wrap !important; /* 保持空格和换行 */
  word-wrap: break-word !important; /* 防止长单词溢出 */
  word-break: break-word !important; /* 长单词换行 */
  
  /* 字体和行高 */
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
  font-size: 14px !important;
  line-height: 1.6 !important;
  color: #2c3e50 !important;
 
}

/* 预览区域 */
.preview-content {
  padding: 16px;
  max-height: 500px;
  overflow-y: auto;
  background: #fff;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .editor-tools {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .mode-switch {
    justify-content: center;
  }
  
  .tool-actions {
    justify-content: center;
  }
  
  .panel-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start !important;
  }
  
  .panel-actions {
    align-self: stretch;
    justify-content: center;
  }
  
  .tinymce-container textarea {
    min-height: 300px;
    font-size: 13px;
  }
  
  .preview-content {
    max-height: 300px;
    font-size: 13px;
  }
}

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

.preview-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.preview-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.preview-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 使用指南面板样式 */
.usage-guide-panel {
  margin-top: 20px;
}

.usage-guide-panel :deep(.el-card__header) {
  background: linear-gradient(135deg, #5721E4, #8B5FBF);
  color: white;
  border-bottom: none;
  font-weight: 600;
}

.usage-guide-panel :deep(.el-card__header .el-button--text) {
  color: white;
  font-weight: 500;
}

.usage-guide-panel :deep(.el-card__header .el-button--text:hover) {
  color: #fff;
  background: rgba(255, 255, 255, 0.1);
}

.guide-content {
  max-height: 70vh;
  overflow-y: auto;
  padding: 20px;
}

.guide-section {
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;
}

.guide-section:last-child {
  border-bottom: none;
  padding-bottom: 0;
  margin-bottom: 0;
}

.guide-section h4 {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 20px;
  position: relative;
  padding-left: 30px;
}

.guide-section h4::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background: linear-gradient(135deg, #5721E4, #8B5FBF);
  border-radius: 2px;
}

/* 功能网格布局 */
.function-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 16px;
  margin-bottom: 16px;
}

.function-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fafbfc;
  transition: all 0.3s ease;
}

.function-item:hover {
  border-color: #5721E4;
  background: #f8f9ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(87, 33, 228, 0.1);
}

.function-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: linear-gradient(135deg, #5721E4, #8B5FBF);
  color: white;
  font-weight: 600;
  font-size: 16px;
  flex-shrink: 0;
}

.function-icon i {
  font-size: 18px;
}

.color-icon {
  width: 20px;
  height: 20px;
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4, #45b7d1, #96ceb4, #ffeaa7, #fd79a8);
  border-radius: 4px;
}

.function-detail {
  flex: 1;
}

.function-detail h5 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.function-detail p {
  margin: 0 0 6px 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}

.function-detail .tips {
  font-size: 12px;
  color: #909399;
  font-style: italic;
}

/* 快捷键样式 */
kbd {
  display: inline-block;
  padding: 2px 6px;
  font-size: 12px;
  line-height: 1.4;
  color: #2c3e50;
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 3px;
  box-shadow: 0 1px 0 rgba(0, 0, 0, 0.2), inset 0 0 0 2px #fff;
  white-space: nowrap;
  font-family: 'Monaco', 'Consolas', monospace;
}

.color-demo {
  font-weight: 600;
}

.bg-demo {
  background: #ffeb3b;
  padding: 2px 4px;
  border-radius: 2px;
  color: #333;
  font-weight: 600;
}

/* 快捷键汇总网格 */
.shortcuts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.shortcut-category {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e9ecef;
}

.shortcut-category h5 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #5721E4;
  text-align: center;
  padding-bottom: 8px;
  border-bottom: 1px solid #dee2e6;
}

.shortcut-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.shortcut-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
}

.shortcut-item kbd {
  font-size: 11px;
  padding: 1px 4px;
}

.shortcut-item span {
  color: #606266;
}

/* 专用功能样式 */
.special-features {
  background: linear-gradient(135deg, #f8f9ff, #f0f2ff);
  border: 1px solid #e4e7ff;
  border-radius: 12px;
  padding: 24px;
  margin-top: 20px;
}

.special-function {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  margin-bottom: 24px;
}

.special-function:last-child {
  margin-bottom: 0;
}

.special-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  border-radius: 12px;
  background: linear-gradient(135deg, #5721E4, #8B5FBF);
  color: white;
  font-weight: 600;
  font-size: 20px;
  flex-shrink: 0;
  box-shadow: 0 4px 12px rgba(87, 33, 228, 0.3);
}

.special-content {
  flex: 1;
}

.special-content h5 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.special-content p {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

.usage-steps {
  display: flex;
  flex-direction: column;
  gap: 8px;
  font-size: 13px;
  color: #606266;
}

.step {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #5721E4;
  color: white;
  font-size: 11px;
  font-weight: 600;
  margin-right: 8px;
  flex-shrink: 0;
}

/* 展开/收起动画 */
.slide-fade-enter-active {
  transition: all 0.4s ease;
}

.slide-fade-leave-active {
  transition: all 0.4s ease;
}

.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateY(-20px);
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .function-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .shortcuts-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .function-item {
    padding: 12px;
  }
  
  .function-icon {
    width: 36px;
    height: 36px;
    font-size: 14px;
  }
  
  .function-detail h5 {
    font-size: 14px;
  }
  
  .function-detail p {
    font-size: 13px;
  }
  
  .special-function {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
  
  .special-icon {
    align-self: center;
  }
  
  .guide-content {
    max-height: 60vh;
    padding: 16px;
  }
  
  .guide-section {
    margin-bottom: 24px;
    padding-bottom: 16px;
  }
  
  .guide-section h4 {
    font-size: 16px;
    padding-left: 20px;
  }
  
  .usage-steps {
    text-align: left;
  }
  
  /* 演示编辑器样式 */
  .demo-editor-container {
    margin: 16px 0;
    padding: 16px;
    background: #f8f9fa;
    border: 2px solid #e9ecef;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }
  
  .demo-description {
    margin-bottom: 12px;
    font-size: 14px;
    color: #495057;
    font-weight: 600;
    text-align: center;
  }
  
  .demo-editor {
    border: 2px solid #d1d5db;
    border-radius: 6px;
    min-height: 220px;
    background: white;
    width: 100%;
    display: block;
  }
  
  /* TinyMCE 编辑器内部样式覆盖 */
  .demo-editor-container .tox-tinymce {
    border: 2px solid #d1d5db !important;
    border-radius: 6px !important;
  }
  
  .demo-editor-container .tox-editor-header {
    background: #f8f9fa !important;
    border-bottom: 1px solid #e9ecef !important;
  }
  
  .demo-tips {
    margin-top: 12px;
    padding: 10px 15px;
    background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
    border: 1px solid #bbdefb;
    border-radius: 6px;
    font-size: 13px;
    text-align: center;
  }
  
  .tip-item {
    color: #1565c0;
    font-weight: 600;
  }
}
</style> 