<template>
  <div class="export-button">
    <a-dropdown :trigger="['click']">
      <a-button type="text" class="export-trigger">
        <img src="../../assets/svg/export.svg" alt="export" class="export-icon" />
      </a-button>
      <template #overlay>
        <a-menu>
          <a-menu-item key="pdf" @click="exportAs('pdf')">
            <img src="../../assets/svg/pdf.svg" alt="pdf" class="menu-icon" />
            <span>导出为 PDF</span>
          </a-menu-item>
          <a-menu-item key="markdown" @click="exportAs('markdown')">
            <img src="../../assets/svg/markdown.svg" alt="markdown" class="menu-icon" />
            <span>导出为 Markdown</span>
          </a-menu-item>
          <a-menu-item key="word" @click="exportAs('word')">
            <img src="../../assets/svg/word.svg" alt="word" class="menu-icon" />
            <span>导出为 Word</span>
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
  </div>
</template>

<script setup>
import { defineProps } from 'vue';
import { message } from 'ant-design-vue';
import html2pdf from 'html2pdf.js';
import { saveAs } from 'file-saver';
import { Document, Packer, Paragraph, TextRun } from 'docx';

const props = defineProps({
  conversation: {
    type: Object,
    required: true
  }
});

const exportAs = async (format) => {
  try {
    switch (format) {
      case 'pdf':
        await exportToPdf();
        break;
      case 'markdown':
        exportToMarkdown();
        break;
      case 'word':
        exportToWord();
        break;
    }
    message.success(`导出${format.toUpperCase()}成功`);
  } catch (error) {
    console.error('Export failed:', error);
    message.error('导出失败');
  }
};

const exportToPdf = async () => {
  const content = document.createElement('div');
  content.innerHTML = formatConversationForPdf();
  
  const opt = {
    margin: 1,
    filename: `对话记录_${new Date().toLocaleDateString()}.pdf`,
    image: { type: 'jpeg', quality: 0.98 },
    html2canvas: { scale: 2 },
    jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
  };
  
  await html2pdf().set(opt).from(content).save();
};

const exportToMarkdown = () => {
  const markdown = formatConversationForMarkdown();
  const blob = new Blob([markdown], { type: 'text/markdown;charset=utf-8' });
  saveAs(blob, `对话记录_${new Date().toLocaleDateString()}.md`);
};

const exportToWord = () => {
  const doc = new Document({
    sections: [{
      properties: {},
      children: formatConversationForWord()
    }]
  });

  Packer.toBlob(doc).then(blob => {
    saveAs(blob, `对话记录_${new Date().toLocaleDateString()}.docx`);
  });
};

const formatConversationForPdf = () => {
  return props.conversation.messages.map(msg => `
    <div style="margin-bottom: 20px;">
      <div style="font-weight: bold; margin-bottom: 5px;">
        ${msg.role === 'user' ? '用户' : 'AI助手'}:
      </div>
      <div style="white-space: pre-wrap;">${msg.content}</div>
    </div>
  `).join('');
};

const formatConversationForMarkdown = () => {
  return props.conversation.messages.map(msg => 
    `### ${msg.role === 'user' ? '用户' : 'AI助手'}\n\n${msg.content}\n\n`
  ).join('---\n\n');
};

const formatConversationForWord = () => {
  return props.conversation.messages.flatMap(msg => [
    new Paragraph({
      children: [
        new TextRun({
          text: `${msg.role === 'user' ? '用户' : 'AI助手'}:`,
          bold: true
        })
      ]
    }),
    new Paragraph({
      children: [
        new TextRun(msg.content)
      ]
    }),
    new Paragraph({
      children: [new TextRun('\n')]
    })
  ]);
};
</script>

<style scoped>
.export-button {
  display: inline-block;
}

.export-trigger {
  padding: 4px;
  height: 32px;
  width: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.export-icon {
  width: 16px;
  height: 16px;
}

.menu-icon {
  width: 14px;
  height: 14px;
  margin-right: 8px;
}

:deep(.ant-dropdown-menu-item) {
  display: flex;
  align-items: center;
  padding: 8px 12px;
}
</style> 