<template>
  <div class="markdown-editor-container">
    <div class="editor-header">
      <div class="title">
        <icon-file />
        <span>Markdown 编辑器</span>
        <a-divider type="vertical" />
        <a-tooltip content="自动保存已启用">
          <span class="save-status" :class="{ 'saved': !hasChanges }">
            {{ hasChanges ? '未保存' : '已保存' }}
          </span>
        </a-tooltip>
      </div>
      <div class="actions">
        <a-tooltip content="清空内容">
          <a-button size="small" type="outline" @click="clearContent">
            <icon-delete />
          </a-button>
        </a-tooltip>
        <a-tooltip content="全屏编辑">
          <a-button size="small" type="outline" @click="toggleFullscreen">
            <icon-expand />
          </a-button>
        </a-tooltip>
        <PdfExportButton @export-complete="onExportComplete" />
      </div>
    </div>
    
    <div ref="editorContentRef" class="editor-content" :class="{ 'fullscreen': isFullscreen }">
      <div class="editor-panel" :class="{ 'expanded': isEditorExpanded }" :style="{ width: editorWidthPercent + '%' }">
        <div class="panel-header">
          <span>编辑</span>
          <div class="panel-controls">
            <a-tooltip content="展开编辑器">
              <a-button size="small" type="text" @click="toggleEditorExpand">
                <icon-align-left v-if="!isEditorExpanded" />
                <icon-shrink v-else />
              </a-button>
            </a-tooltip>
          </div>
        </div>
        <div class="editor-wrapper">
          <textarea 
            ref="textarea"
            v-model="markdownContent"
            class="markdown-textarea"
            placeholder="在这里输入 Markdown 内容...

# 标题
## 二级标题
**粗体** *斜体*

- 列表项 1
- 列表项 2

\`\`\`javascript
console.log('Hello, World!')
\`\`\`

> 引用内容"
            @input="handleInput"
            @keydown="handleKeydown"
          />
        </div>
      </div>
      
      <div class="resizer" @mousedown="handleResize"></div>
      
      <div class="preview-panel" :class="{ 'expanded': isPreviewExpanded }" :style="{ width: (100 - editorWidthPercent) + '%' }">
        <div class="panel-header">
          <span>预览</span>
          <div class="panel-controls">
            <a-tooltip content="展开预览">
              <a-button size="small" type="text" @click="togglePreviewExpand">
                <icon-align-left v-if="!isPreviewExpanded" />
                <icon-shrink v-else />
              </a-button>
            </a-tooltip>
            <a-tooltip content="刷新预览">
              <a-button size="small" type="text" @click="renderPreview">
                <icon-sync />
              </a-button>
            </a-tooltip>
          </div>
        </div>
        <div ref="previewRef" class="preview-wrapper">
          <MarkdownPreview :content="markdownContent" />
        </div>
      </div>
    </div>
    
    <div class="editor-footer">
      <div class="status">
        <span>{{ wordCount }} 字符 | {{ lineCount }} 行 | {{ readingTime }} 分钟阅读</span>
      </div>
      <div class="shortcuts">
        <a-tooltip content="快捷键: Ctrl + S 保存">
          <a-button size="small" @click="saveContent" :disabled="!hasChanges">
            <icon-save />
            保存
          </a-button>
        </a-tooltip>
        <a-tooltip content="快捷键: Ctrl + / 切换预览">
          <a-button size="small" @click="togglePreview">
            <icon-eye />
          </a-button>
        </a-tooltip>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import MarkdownPreview from './MarkdownPreview.vue'
import PdfExportButton from './PdfExportButton.vue'
import IconFile from '@arco-design/web-vue/es/icon/icon-file'
import IconDelete from '@arco-design/web-vue/es/icon/icon-delete'
import IconExpand from '@arco-design/web-vue/es/icon/icon-expand'
import IconShrink from '@arco-design/web-vue/es/icon/icon-shrink'
import IconSync from '@arco-design/web-vue/es/icon/icon-sync'
import IconSave from '@arco-design/web-vue/es/icon/icon-save'
import IconEye from '@arco-design/web-vue/es/icon/icon-eye'
import IconAlignLeft from '@arco-design/web-vue/es/icon/icon-align-left'
import { createResizeHandler } from '@/utils/resize'

export default {
  name: 'MarkdownEditor',
  components: {
    MarkdownPreview,
    PdfExportButton,
    IconFile,
    IconDelete,
    IconExpand,
    IconShrink,
    IconSync,
    IconSave,
    IconEye,
    IconAlignLeft
  },
  emits: ['content-change', 'update:content', 'save'],
  props: {
    content: {
      type: String,
      default: ''
    }
  },
  setup(props, { emit }) {
    const markdownContent = ref(props.content)
    const textarea = ref(null)
    const hasChanges = ref(false)
    const lastSavedContent = ref('')
    const isFullscreen = ref(false)
    const isEditorExpanded = ref(false)
    const isPreviewExpanded = ref(false)
    const editorWidthPercent = ref(50)
    const editorContentRef = ref(null)
    const previewRef = ref<HTMLElement | null>(null)

    // 计算属性
    const wordCount = computed(() => {
      return markdownContent.value.length
    })

    const lineCount = computed(() => {
      return markdownContent.value.split('\n').length
    })

    const readingTime = computed(() => {
      // 平均阅读速度：每分钟 200 字符
      const wordsPerMinute = 200
      const minutes = Math.ceil(wordCount.value / wordsPerMinute)
      return minutes
    })

    // 方法
    const handleInput = () => {
      hasChanges.value = markdownContent.value !== lastSavedContent.value
      emit('content-change', markdownContent.value)
      emit('update:content', markdownContent.value)
    }

    const handleKeydown = (event) => {
      // Ctrl + S 保存
      if ((event.ctrlKey || event.metaKey) && event.key === 's') {
        event.preventDefault()
        saveContent()
      }
      // Ctrl + / 切换预览
      if ((event.ctrlKey || event.metaKey) && event.key === '/') {
        event.preventDefault()
        togglePreview()
      }
    }

    const saveContent = () => {
      lastSavedContent.value = markdownContent.value
      hasChanges.value = false
      emit('save', markdownContent.value)
      Message.success('内容已保存')
      // 保存到本地存储
      localStorage.setItem('u-desk-markdown-content', markdownContent.value)
    }

    const onExportComplete = () => {
      Message.success('PDF 导出完成')
    }

    // 自动调整 textarea 高度
    const adjustTextareaHeight = () => {
      if (textarea.value) {
        textarea.value.style.height = 'auto'
        textarea.value.style.height = textarea.value.scrollHeight + 'px'
      }
    }

    // 分割拖拽调整宽度
    const handleResize = createResizeHandler(
      () => editorContentRef.value,
      () => editorWidthPercent.value,
      {
        direction: 'horizontal',
        minPercent: 15,
        maxPercent: 85,
        minPixels: 100,
        onResize: (percent) => { editorWidthPercent.value = percent },
      }
    )

    // 切换功能
    const togglePreview = () => {
      // 预览面板始终显示，保留快捷键兼容性
      nextTick(() => {
        adjustTextareaHeight()
      })
    }

    const toggleFullscreen = () => {
      isFullscreen.value = !isFullscreen.value
      if (isFullscreen.value) {
        document.body.style.overflow = 'hidden'
      } else {
        document.body.style.overflow = ''
      }
    }

    const toggleEditorExpand = () => {
      isEditorExpanded.value = !isEditorExpanded.value
      if (isEditorExpanded.value && isPreviewExpanded.value) {
        isPreviewExpanded.value = false
      }
      nextTick(() => {
        adjustTextareaHeight()
      })
    }

    const togglePreviewExpand = () => {
      isPreviewExpanded.value = !isPreviewExpanded.value
      if (isPreviewExpanded.value && isEditorExpanded.value) {
        isEditorExpanded.value = false
      }
    }

    const clearContent = () => {
      Modal.confirm({
        title: '确认清空',
        content: '确定要清空所有内容吗？此操作不可恢复。',
        okButtonProps: { status: 'danger' },
        onOk: () => {
          markdownContent.value = ''
          hasChanges.value = true
          lastSavedContent.value = ''
          emit('content-change', '')
          Message.success('内容已清空')
        }
      })
    }

    const renderPreview = () => {
      // 强制重新渲染预览
      if (previewRef.value) {
        previewRef.value.style.opacity = '0'
        nextTick(() => {
          if (previewRef.value) previewRef.value.style.opacity = '1'
        })
      }
    }

    // 自动保存定时器
    let autoSaveTimer = null

    // 监听内容变化：自动保存 + 调整高度
    watch(markdownContent, () => {
      // 自动保存
      if (hasChanges.value) {
        clearTimeout(autoSaveTimer)
        autoSaveTimer = setTimeout(() => {
          saveContent()
        }, 5000)
      }
      // 调整高度
      // computeRendered 是 computed ref，值变化即触发，无需 deep
      nextTick(() => {
        adjustTextareaHeight()
      })
    })

    // 初始化
    onMounted(() => {
      nextTick(() => {
        adjustTextareaHeight()
      })
    })

    onUnmounted(() => {
      if (autoSaveTimer) {
        clearTimeout(autoSaveTimer)
      }
    })

    return {
      markdownContent,
      textarea,
      hasChanges,
      wordCount,
      lineCount,
      readingTime,
      isFullscreen,
      isEditorExpanded,
      isPreviewExpanded,
      handleInput,
      handleKeydown,
      saveContent,
      onExportComplete,
      togglePreview,
      toggleFullscreen,
      toggleEditorExpand,
      togglePreviewExpand,
      clearContent,
      renderPreview
    }
  }
}
</script>

<style scoped>
.markdown-editor-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--color-bg-2);
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
}

.markdown-editor-container.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  border-radius: 0;
  height: 100vh;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: var(--color-bg-1);
  border-bottom: 1px solid var(--color-border);
}

.title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: var(--color-text-1);
}

.save-status {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  background: var(--color-warning-light-1);
  color: var(--color-warning-6);
}

.save-status.saved {
  background: var(--color-success-light-1);
  color: var(--color-success-6);
}

.actions {
  display: flex;
  gap: 8px;
}

.editor-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.editor-panel,
.preview-panel {
  display: flex;
  flex-direction: column;
  min-width: 100px;
  overflow: hidden;
}

.editor-panel.expanded {
  flex: 2;
}

.preview-panel.expanded {
  flex: 2;
}

.editor-panel {
  border-right: 1px solid var(--color-border);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background: var(--color-fill-2);
  border-bottom: 1px solid var(--color-border);
  font-size: 12px;
  font-weight: 500;
  color: var(--color-text-2);
}

.panel-controls {
  display: flex;
  gap: 4px;
}

.editor-wrapper {
  flex: 1;
  padding: 16px;
  overflow: auto;
}

.preview-wrapper {
  flex: 1;
  padding: 16px;
  overflow: auto;
  background: var(--color-bg-1);
  transition: opacity 0.2s;
}

.resizer {
  width: 4px;
  cursor: col-resize;
  background: var(--color-border);
  transition: background-color 0.2s;
}

.resizer:hover {
  background: var(--color-primary-light-3);
}

.markdown-textarea {
  width: 100%;
  height: 100%;
  min-height: 200px;
  padding: 12px;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
  resize: none;
  outline: none;
  background: var(--color-bg-1);
  color: var(--color-text-1);
}

.markdown-textarea:focus {
  border-color: var(--color-primary-6);
  box-shadow: 0 0 0 2px rgba(22, 93, 255, 0.2);
}

.markdown-textarea::placeholder {
  color: var(--color-text-3);
}

.editor-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background: var(--color-bg-1);
  border-top: 1px solid var(--color-border);
}

.status {
  font-size: 12px;
  color: var(--color-text-2);
}

.shortcuts {
  display: flex;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .editor-content {
    flex-direction: column;
  }

  .editor-panel {
    border-right: none;
    border-bottom: 1px solid var(--color-border);
  }

  .resizer {
    height: 4px;
    width: 100%;
    cursor: row-resize;
  }
}
</style>