<template>
  <div class="markdown-editor">
    <div class="editor-header">
      <el-input v-model="title" placeholder="标题" class="title-input" />
      <el-input v-model="fileName" placeholder="文件名" class="file-input" />
    </div>

    <v-md-editor
      v-model="content" 
      height="500px"
      :disabled-menus="[]"
      @upload-image="handleImageUpload"
    ></v-md-editor>
    
    <div class="editor-footer">
      <el-button type="primary" @click="saveMarkdown">保存</el-button>
      <el-button @click="previewMarkdown">预览</el-button>
    </div>
  </div>
</template>

<script>
import MarkdownEditor from '@/components/MarkdownEditor.vue';
import VMdPreview from '@kangc/v-md-editor/lib/preview';
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

export default {
  name: 'MarkdownEditor',
  setup() {
    const title = ref('');
    const fileName = ref('');
    const content = ref('');
    const userId = ref(1); // 示例用户ID，实际应用中从登录信息获取
    const currentFileId = ref(null);

    const saveMarkdown = async () => {
      try {
        const API_BASE_URL = 'http://localhost:8083';
        let response;
        
        if (currentFileId.value) {
          // 更新已有文件：content作为请求体
          response = await axios.post(`${API_BASE_URL}/api/markdown/${currentFileId.value}`, 
            content.value, {
              withCredentials: true,
              headers: {
                'Content-Type': 'text/plain'
              }
            }
          );
        } else {
          // 创建新文件：userId, title, fileName作为查询参数，content作为请求体
          const params = new URLSearchParams();
          params.append('userId', userId.value);
          params.append('title', title.value);
          params.append('fileName', fileName.value);
          
          response = await axios.post(`${API_BASE_URL}/api/markdown`, 
            content.value, {
              params: params,
              withCredentials: true,
              headers: {
                'Content-Type': 'text/plain'
              }
            }
          );
          currentFileId.value = response.data.id;
        }
        
        ElMessage.success('保存成功');
      } catch (error) {
        ElMessage.error('保存失败: ' + error.message);
      }
    };

    const previewMarkdown = () => {
      if (!currentFileId.value) {
        ElMessage.warning('请先保存文档');
        return;
      }
      window.open(`/api/markdown/${currentFileId.value}`, '_blank');
    };

    const handleImageUpload = async (event, insertImage, files) => {
      const file = files[0];
      const formData = new FormData();
      formData.append('file', file);
      formData.append('userId', userId.value);
      formData.append('markdownId', currentFileId.value);

      try {
        const API_BASE_URL = 'http://localhost:8083';
        const response = await axios.post(`${API_BASE_URL}/api/images`, formData, {
          withCredentials: true,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        
        // 插入图片到编辑器
        insertImage({
          url: response.data.url,
          desc: response.data.originalName
        });
      } catch (error) {
        ElMessage.error('图片上传失败: ' + error.message);
      }
    };

    return {
      title,
      fileName,
      content,
      saveMarkdown,
      previewMarkdown,
      handleImageUpload,
      MarkdownEditor
    };
  }
};
</script>

<style scoped>
.markdown-editor {
  padding: 20px;
}
.editor-header {
  display: flex;
  margin-bottom: 15px;
}
.title-input {
  flex: 2;
  margin-right: 10px;
}
.file-input {
  flex: 1;
}
.editor-footer {
  margin-top: 15px;
  text-align: right;
}
</style>
