<template>
  <div class="split-editor-demo">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <i class="el-icon-s-unfold"></i>
          分屏编辑器演示
        </h1>
        <p class="page-subtitle">支持编辑、预览、分屏三种模式的富文本编辑器</p>
      </div>
      <div class="header-actions">
        <el-button @click="handleSave" :loading="saveLoading" icon="el-icon-document" type="success">
          保存内容
        </el-button>
        <el-button @click="handleClear" icon="el-icon-delete" type="danger">
          清空内容
        </el-button>
      </div>
    </div>

    <!-- 文档配置区域 -->
    <el-card class="document-config" shadow="never">
      <div slot="header">
        <span><i class="el-icon-setting"></i> 文档配置</span>
      </div>
      <el-form :model="documentForm" label-width="100px" class="config-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="文档标题">
              <el-input v-model="documentForm.title" placeholder="请输入文档标题" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文档类型">
              <el-select v-model="documentForm.type" placeholder="请选择文档类型" style="width: 100%">
                <el-option label="服务条款" value="1" />
                <el-option label="API文档" value="2" />
                <el-option label="挖矿教程" value="3" />
                <el-option label="其他" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文档状态">
              <el-tag :type="documentForm.status === 'published' ? 'success' : 'info'">
                {{ documentForm.status === 'published' ? '已发布' : '草稿' }}
              </el-tag>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 分屏编辑器 -->
    <el-card class="editor-card" shadow="never">
      <div slot="header">
        <span><i class="el-icon-edit-outline"></i> 分屏编辑器</span>
        <div class="header-tips">
          <el-tag size="mini" type="info">支持实时预览</el-tag>
          <el-tag size="mini" type="success">自动保存</el-tag>
        </div>
      </div>
      
      <SplitScreenEditor
        ref="splitEditor"
        v-model="documentForm.content"
        :height="500"
        :options="editorOptions"
        @change="handleContentChange"
        @publish="handlePublish"
      />
    </el-card>

    <!-- 使用说明 -->
    <el-card class="usage-guide" shadow="never">
      <div slot="header">
        <span><i class="el-icon-info"></i> 使用说明</span>
        <el-button 
          style="float: right; padding: 3px 0" 
          type="text" 
          @click="showGuide = !showGuide"
        >
          {{ showGuide ? '收起' : '展开' }}
        </el-button>
      </div>
      
      <transition name="slide-fade">
        <div v-show="showGuide" class="guide-content">
          <div class="guide-section">
            <h4>🖥️ 三种显示模式</h4>
            <ul>
              <li><strong>编辑模式</strong>：只显示编辑器，专注于内容编写</li>
              <li><strong>预览模式</strong>：只显示预览效果，方便查看最终结果</li>
              <li><strong>分屏模式</strong>：左边编辑，右边实时预览，所见即所得</li>
            </ul>
          </div>
          
          <div class="guide-section">
            <h4>⚡ 快捷功能</h4>
            <ul>
              <li><strong>插入圆点</strong>：点击工具栏中的"插入圆点"按钮，在当前位置插入 • 符号</li>
              <li><strong>全屏编辑</strong>：点击全屏按钮或按 F11 进入全屏模式</li>
              <li><strong>复制HTML</strong>：在预览区域可以复制生成的HTML代码</li>
              <li><strong>字数统计</strong>：实时显示当前内容的字符数量</li>
            </ul>
          </div>
          
          <div class="guide-section">
            <h4>🎯 圆点列表示例</h4>
            <p>在编辑器中输入以下内容来创建带圆点的列表：</p>
            <div class="example-box">
              <p><code>• ALEO矿工必须质押一定数量的ALEO代币</code></p>
              <p><code>• 否则将无法提交PoW工作量证明</code></p>
              <p><code>• 质押金额直接影响挖矿收益</code></p>
            </div>
          </div>
        </div>
      </transition>
    </el-card>
  </div>
</template>

<script>
import SplitScreenEditor from '@/components/SplitScreenEditor.vue'

export default {
  name: 'SplitEditorDemo',
  components: {
    SplitScreenEditor
  },
  
  data() {
    return {
      // 文档表单数据
      documentForm: {
        title: '分屏编辑器演示文档',
        type: '2',
        content: this.getDefaultContent(),
        status: 'draft'
      },
      
      // 加载状态
      saveLoading: false,
      
      // 使用指南显示状态
      showGuide: true,
      
      // 编辑器配置选项
      editorOptions: {
        height: 500,
        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 | link image table',
          'code preview fullscreen | 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;
            margin: 16px;
          }
          p { margin: 10px 0; }
          ul, ol { margin: 10px 0; padding-left: 24px; }
          li { margin: 6px 0; line-height: 1.6; }
          h1, h2, h3 { color: #2c3e50; margin: 16px 0 8px 0; }
          table { border-collapse: collapse; width: 100%; margin: 12px 0; }
          table th, table td { border: 1px solid #ddd; padding: 8px; text-align: left; }
          table th { background-color: #f2f2f2; font-weight: 600; }
          code { background: #f4f4f4; padding: 2px 4px; border-radius: 3px; }
          pre { background: #f8f8f8; padding: 12px; border-radius: 4px; overflow-x: auto; }
        `,
        placeholder: '请在此输入您的内容，支持富文本格式...',
        language: 'zh_CN',
        branding: false,
        resize: false,
        statusbar: true
      }
    }
  },
  
  methods: {
    /**
     * 获取默认内容 - 演示ALEO相关内容
     */
    getDefaultContent() {
      return `<h2>ALEO挖矿说明</h2>

<p>根据<a href="#" target="_blank">ALEO ARC-46协议</a>，ALEO挖矿机制将在2025年08月01日00:00 UTC进行如下升级，升级完成后您的ALEO挖矿可能会受到影响，请您知悉：</p>

<ol>
  <li><strong>ALEO挖矿将转变为"PoS+PoW"混合机制。</strong></li>
</ol>

<ul>
  <li>• ALEO矿工必须质押一定数量的ALEO代币，否则将无法提交PoW工作量证明(即算力)并获得挖矿收益。</li>
</ul>

<h3>重要提醒</h3>

<p>请及时了解新的挖矿机制要求，做好相应准备。如有疑问，请联系客服获取帮助。</p>

<h3>技术规格表</h3>

<table>
  <thead>
    <tr>
      <th>参数</th>
      <th>当前值</th>
      <th>升级后</th>
      <th>说明</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>共识机制</td>
      <td>PoW</td>
      <td>PoS+PoW</td>
      <td>混合共识</td>
    </tr>
    <tr>
      <td>质押要求</td>
      <td>无</td>
      <td>必需</td>
      <td>需要质押ALEO代币</td>
    </tr>
    <tr>
      <td>算力证明</td>
      <td>直接提交</td>
      <td>需要质押</td>
      <td>先质押后挖矿</td>
    </tr>
  </tbody>
</table>

<p><em>注：以上信息仅供参考，具体实施以官方公告为准。</em></p>`
    },
    
    /**
     * 处理内容变化
     */
    handleContentChange(content) {
      console.log('编辑器内容已更改:', content.length, '字符');
      // 这里可以添加自动保存逻辑
      this.autoSave();
    },
    
    /**
     * 自动保存（防抖）
     */
    autoSave() {
      clearTimeout(this.autoSaveTimer);
      this.autoSaveTimer = setTimeout(() => {
        this.saveToDraft();
      }, 2000); // 2秒后自动保存到本地
    },
    
    /**
     * 保存到本地存储
     */
    saveToDraft() {
      const draftData = {
        ...this.documentForm,
        lastSaved: new Date().toISOString()
      };
      localStorage.setItem('split_editor_draft', JSON.stringify(draftData));
      console.log('内容已自动保存到本地');
    },
    
    /**
     * 从本地存储加载草稿
     */
    loadDraft() {
      const draft = localStorage.getItem('split_editor_draft');
      if (draft) {
        try {
          const draftData = JSON.parse(draft);
          const timeDiff = new Date().getTime() - new Date(draftData.lastSaved).getTime();
          
          // 如果草稿在24小时内
          if (timeDiff < 24 * 60 * 60 * 1000) {
            this.documentForm = {
              ...this.documentForm,
              ...draftData
            };
            
            this.$message({
              message: `已恢复草稿 (${new Date(draftData.lastSaved).toLocaleString()})`,
              type: 'success',
              duration: 3000
            });
          }
        } catch (error) {
          console.error('加载草稿失败:', error);
        }
      }
    },
    
    /**
     * 保存内容
     */
    async handleSave() {
      if (!this.documentForm.title.trim()) {
        this.$message.warning('请输入文档标题');
        return;
      }
      
      if (!this.documentForm.content.trim()) {
        this.$message.warning('请输入文档内容');
        return;
      }
      
      this.saveLoading = true;
      
      try {
        // 模拟保存API调用
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 这里可以调用实际的保存API
        // const response = await addDocument(this.documentForm);
        
        this.$message.success('文档保存成功');
        this.documentForm.status = 'published';
        
        // 清除本地草稿
        localStorage.removeItem('split_editor_draft');
        
      } catch (error) {
        console.error('保存失败:', error);
        this.$message.error('保存失败: ' + (error.message || '未知错误'));
      } finally {
        this.saveLoading = false;
      }
    },
    
    /**
     * 清空内容
     */
    handleClear() {
      this.$confirm('确定要清空所有内容吗？此操作不可恢复。', '确认清空', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.documentForm.content = '';
        this.documentForm.title = '';
        this.$refs.splitEditor.clear();
        
        // 清除本地草稿
        localStorage.removeItem('split_editor_draft');
        
        this.$message.success('内容已清空');
      }).catch(() => {
        // 用户取消
      });
    },
    
    /**
     * 处理编辑器发布事件
     */
    handlePublish(publishData) {
      console.log('编辑器发布数据:', publishData);
      
      if (publishData.success) {
        // 发布成功
        console.log('文档发布成功:', {
          documentId: publishData.documentId,
          title: publishData.title,
          wordCount: publishData.wordCount
        });
        
        // 更新页面状态
        this.documentForm.title = publishData.title;
        this.documentForm.content = publishData.content;
        this.documentForm.status = 'published';
        
        // 清空本地草稿
        this.clearDraft();
        
        // 显示详细成功通知
        this.$notify({
          title: '✅ 发布成功',
          message: `文档 "${publishData.title}" 已成功发布到文档管理系统\n文档ID: ${publishData.documentId}\n字数: ${publishData.wordCount} 字`,
          type: 'success',
          duration: 5000
        });
        
      } else {
        // 发布失败
        console.error('文档发布失败:', publishData.error);
        
        this.$notify({
          title: '❌ 发布失败', 
          message: `发布失败：${publishData.error}`,
          type: 'error',
          duration: 4000
        });
      }
    }
  },
  
  mounted() {
    // 页面加载时尝试恢复草稿
    this.loadDraft();
  },
  
  beforeDestroy() {
    // 清理定时器
    if (this.autoSaveTimer) {
      clearTimeout(this.autoSaveTimer);
    }
  }
}
</script>

<style scoped>
/* 页面容器 */
.split-editor-demo {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 140px);
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.header-content {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-title i {
  color: #5721E4;
  font-size: 32px;
}

.page-subtitle {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
  line-height: 1.5;
}

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

/* 文档配置 */
.document-config {
  margin-bottom: 20px;
}

.document-config :deep(.el-card__header) {
  background: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
  font-weight: 600;
  color: #2c3e50;
}

.document-config :deep(.el-card__header i) {
  color: #5721E4;
  margin-right: 8px;
}

.config-form .el-form-item {
  margin-bottom: 16px;
}

/* 编辑器卡片 */
.editor-card {
  margin-bottom: 20px;
}

.editor-card :deep(.el-card__header) {
  background: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.editor-card :deep(.el-card__header i) {
  color: #5721E4;
  margin-right: 8px;
}

.header-tips {
  display: flex;
  gap: 8px;
}

/* 使用指南 */
.usage-guide {
  margin-bottom: 20px;
}

.usage-guide :deep(.el-card__header) {
  background: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.usage-guide :deep(.el-card__header i) {
  color: #5721E4;
  margin-right: 8px;
}

.guide-content {
  padding: 10px 0;
}

.guide-section {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px dashed #eee;
}

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

.guide-section h4 {
  font-size: 16px;
  font-weight: 600;
  color: #5721E4;
  margin-bottom: 12px;
  position: relative;
  padding-left: 20px;
}

.guide-section h4::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background: #5721E4;
  border-radius: 2px;
}

.guide-section ul {
  margin: 8px 0;
  padding-left: 20px;
}

.guide-section li {
  margin: 6px 0;
  line-height: 1.6;
  color: #2c3e50;
}

.guide-section li strong {
  color: #5721E4;
  font-weight: 600;
}

.example-box {
  background: #f8f9fa;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  padding: 12px;
  margin: 8px 0;
}

.example-box p {
  margin: 4px 0;
  font-family: 'Monaco', 'Consolas', monospace;
  font-size: 13px;
}

.example-box code {
  background: #fff;
  color: #e74c3c;
  padding: 2px 6px;
  border-radius: 3px;
  border: 1px solid #ddd;
}

/* 展开/收起动画 */
.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(-10px);
  opacity: 0;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .split-editor-demo {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .config-form .el-row .el-col {
    width: 100% !important;
    margin-bottom: 12px;
  }
  
  .page-title {
    font-size: 24px;
    text-align: center;
  }
  
  .page-title i {
    font-size: 28px;
  }
  
  .page-subtitle {
    text-align: center;
  }
  
  .header-tips {
    justify-content: center;
    flex-wrap: wrap;
  }
}
</style> 