<template>
  <div class="test3-container">
    <h3>功能测试页面</h3>
    <input type="file" @change="handleFileChange" accept=".docx,.doc" />

    <div v-if="convertedHtml" class="result-section">
      <h4>转换结果:</h4>
      <div v-html="convertedHtml" class="html-result" style="width: 100%" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import mammoth from 'mammoth';

defineOptions({
  name: 'Test3Page',
});

const convertedHtml = ref<string>('');
const loading = ref<boolean>(false);

const handleFileChange = (e: Event) => {
  const file = (e.target as HTMLInputElement).files?.[0];
  if (!file) return;

  loading.value = true;
  convertedHtml.value = '';

  // 读取文件为ArrayBuffer
  const reader = new FileReader();
  reader.onload = async (event) => {
    try {
      const arrayBuffer = reader.result as ArrayBuffer;

      // 定义转换选项
      const options = {
        styleMap: [
          "p[style-name='Section Title'] => h1:fresh",
          "p[style-name='Subsection Title'] => h2:fresh",
          "p[style-name='Normal'] => p:fresh",
          // 添加标题映射
          "p[style-name='Title'] => h1.document-title:fresh",
          "p[style-name='Heading 1'] => h1.heading1:fresh",
          "p[style-name='Heading 2'] => h2.heading2:fresh",
          "p[style-name='Heading 3'] => h3.heading3:fresh",
          // 添加对齐方式映射
          "p[align='center'] => p.center:fresh",
          "p[align='right'] => p.right:fresh",
          "p[align='justify'] => p.justify:fresh",
          // 添加列表段落样式
          "p[style-name='List Paragraph'] => p.list-paragraph:fresh",
          // 添加下划线样式映射
          'u => span.underline:fresh',
        ],
        includeDefaultStyleMap: true,
        ignoreEmptyParagraphs: false,
        preserveStyles: true,
        transformDocument: transformElement,
      };

      // 自定义转换函数，处理特殊字符和下划线
      function transformElement(element: any): any {
        // 处理特殊元素
        if (element.type === 'element' && element.tag && 
            (element.tag.includes('line') || element.tag.includes('shape'))) {
          return {
            type: 'element',
            tag: 'span',
            children: [],
            attributes: {
              'class': 'form-field-line'
            }
          };
        }
        
        // 处理文本内容中的下划线
        if (element.type === 'text' && element.value) {
          const text = element.value;
          
          // 检测连续的下划线、横线或特殊字符
          if (text.match(/_{3,}|—{2,}|={2,}|-{3,}/)) {
            const newText = text.replace(/_{3,}|—{2,}|={2,}|-{3,}/g, match => {
              const width = match.length * 8;
              return `<span class="form-field" style="display:inline-block;border-bottom:1px solid #000;width:${width}px;"></span>`;
            });
            
            if (newText !== text) {
              return {
                ...element,
                value: newText
              };
            }
          }
        }
        
        if (element.children) {
          const children = element.children.map((child: any) => transformElement(child));
          return {
            ...element,
            children
          };
        }
        
        return element;
      }

      // 添加后处理函数来处理HTML结果
      const postProcessHtml = (html: string): string => {
        let processedHtml = html;
        
        // 1. 处理连续的下划线和横线
        processedHtml = processedHtml.replace(/_{3,}|—{2,}|={2,}|-{3,}/g, 
          match => `<span class="form-field-underline" style="display:inline-block;border-bottom:1px solid #000;width:${match.length * 8}px;"></span>`
        );
        
        // 2. 处理Word中的表单域占位符（通常是空白区域）
        processedHtml = processedHtml.replace(
          /<v:line[^>]*>|<v:shape[^>]*>|<w:drawing[^>]*>/g,
          '<span class="form-field-underline" style="display:inline-block;border-bottom:1px solid #000;width:120px;"></span>'
        );
        
        return processedHtml;
      };

      // 使用arrayBuffer而不是path
      const result = await mammoth.convertToHtml(
        { arrayBuffer: arrayBuffer },
        options,
      );

      // 在转换结果后添加样式和后处理
      convertedHtml.value = postProcessHtml(result.value);

      // 添加必要的CSS样式到结果中
      convertedHtml.value = `
<style>
  /* 保留文档格式 */
  .document-title { 
    text-align: center;
    font-size: 1.5em;
    font-weight: bold;
    margin: 20px 0;
  }
  .center { text-align: center; }
  .right { text-align: right; }
  .justify { text-align: justify; }
  .underline { text-decoration: underline; }
  .list-paragraph { margin-left: 20px; }
  
  /* 表单域样式 */
  .form-field, .form-field-underline, .form-field-line { 
    display: inline-block;
    border-bottom: 1px solid #000;
    min-width: 80px;
    margin: 0 4px;
  }
</style>
${convertedHtml.value}`;

      // 如果有任何警告或错误，打印到控制台
      if (result.messages.length > 0) {
        console.log('转换消息:', result.messages);
      }
    } catch (error) {
      console.error('转换文档时出错:', error);
      alert(
        '转换文档时出错: ' +
          (error instanceof Error ? error.message : '未知错误'),
      );
    } finally {
      loading.value = false;
    }
  };

  reader.onerror = () => {
    loading.value = false;
    console.error('读取文件时出错');
    alert('读取文件时出错');
  };

  reader.readAsArrayBuffer(file);
};

onMounted(() => {
  console.log('Test3Page mounted');
});
</script>

<style scoped lang="scss">
.test3-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

input[type='file'] {
  margin: 20px 0;
  padding: 10px;
  border: 1px dashed #ccc;
  border-radius: 4px;
  width: 100%;
}

.result-section {
  margin-top: 30px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

h4 {
  margin-bottom: 15px;
  color: #333;
}

.html-result {
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #f9f9f9;
  min-height: 200px;
  max-height: 600px;
  overflow: auto;
}
</style>
