<template>
  <div>
    <div ref="editor" style="text-align:left"></div>
    <button @click="exportToXml">导出为XML</button>
    <input type="file" accept=".xml" @change="handleXmlUpload">
  </div>
</template>

<script>
import E from 'wangeditor';
import { js2xml, xml2js } from 'xml-js';

export default {
  data() {
    return {
      editor: null
    };
  },
  mounted() {
    this.editor = new E(this.$refs.editor);
    this.editor.create();
  },
  methods: {
    convertHtmlToXml(htmlContent) {
      const xmlObject = {
        declaration: {
          attributes: {
            version: '1.0',
            encoding: 'UTF-8'
          }
        },
        elements: [{
          type: 'element',
          name: 'richText',
          elements: [{
            type: 'text',
            text: htmlContent
          }]
        }]
      };
      
      return js2xml(xmlObject, { compact: false, spaces: 4 });
    },
    
    downloadXml(content, fileName = 'content.xml') {
      const blob = new Blob([content], { type: 'application/xml' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = fileName;
      link.click();
      URL.revokeObjectURL(link.href);
    },
    
    exportToXml() {
      const html = this.editor.txt.html();
      const xml = this.convertHtmlToXml(html);
      this.downloadXml(xml);
    },
    
    parseXmlToHtml(xmlString) {
      try {
        const result = xml2js(xmlString, { compact: false });
        const richTextElement = result.elements.find(el => el.name === 'richText');
        if (richTextElement && richTextElement.elements && richTextElement.elements.length > 0) {
          return richTextElement.elements[0].text;
        }
        return '';
      } catch (e) {
        console.error('XML解析错误:', e);
        return '';
      }
    },
    
    handleXmlUpload(event) {
      const file = event.target.files[0];
      if (!file) return;
      
      const reader = new FileReader();
      reader.onload = (e) => {
        const xmlString = e.target.result;
        const html = this.parseXmlToHtml(xmlString);
        if (html) {
          this.editor.txt.html(html);
        }
      };
      reader.readAsText(file);
    }
  },
  beforeDestroy() {
    if (this.editor) {
      this.editor.destroy();
    }
  }
};
</script>