<template>
  <div class="border-gray-200 border rounded p-3 h-full flex flex-col" style="min-height: 750px; max-height: 750px;">
    <div class="text-sm font-medium mb-3">DeepSeek大模型CRM数据分析</div>
    
    <!-- Chat messages container with fixed height and scrolling -->
    <div class="mb-3 border-gray-200 border rounded overflow-y-auto flex-grow" style="min-height: 0;">
      <div class="p-3 flex flex-col gap-3">
        <div v-for="(message, index) in messages" :key="index" class="flex" :class="{'justify-end': message.role === 'user', 'justify-start': message.role === 'assistant'}">
          <div v-if="message.role === 'assistant'" class="flex items-start gap-2">
            <el-avatar :size="24" class="bg-gray-200 flex items-center justify-center">
              <el-icon><ChatLineRound /></el-icon>
            </el-avatar>
            <div class="border-gray-200 border rounded p-2 text-sm max-w-[80%] bg-gray-50 relative">
              <div class="markdown-body" v-html="renderMarkdown(message.content)"></div>
              <div v-if="message.loading" class="loading-dots">
                <span></span>
                <span></span>
                <span></span>
              </div>
              <el-button 
                v-if="!message.loading && message.role === 'assistant' && index > 0"
                @click="exportToWord(message.content)"
                size="small" 
                type="text" 
                class="absolute -bottom-3 -right-3"
                :icon="Download"
              />
            </div>
          </div>
          <div v-if="message.role === 'user'" class="flex items-start gap-2 justify-end">
            <div class="border-gray-200 border rounded p-2 text-sm max-w-[80%] bg-blue-50 markdown-body" v-html="renderMarkdown(message.content)">
            </div>
            <el-avatar :size="24" class="bg-gray-200 flex items-center justify-center">
              <el-icon><User /></el-icon>
            </el-avatar>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Data source selection -->
    <div class="mb-3 flex gap-2">
      <div>
        <span class="text-sm mr-2">数据来源</span>
        <el-select v-model="dataSource" size="small" style="width: 120px">
          <el-option label="系统表" value="system" />
          <el-option label="自定义报表" value="custom" />
          <el-option label="本地上传" value="upload" />
          <el-option label="自由交流" value="free" />
        </el-select>
      </div>
      
      <div v-if="dataSource === 'system'">
        <el-select v-model="systemTable" size="small" style="width: 120px">
          <el-option label="线索" value="clue" />
          <el-option label="商机" value="business_opportunity" />
          <el-option label="客户" value="customer" />
          <el-option label="联系人" value="contact" />
          <el-option label="合同" value="contract" />
          <el-option label="销售订单" value="order" />
          <el-option label="产品" value="product" />
        </el-select>
      </div>
      
      <div v-if="dataSource === 'upload'">
        <el-upload
          :show-file-list="false"
          :before-upload="beforeUpload"
          :http-request="handleUpload"
          accept=".xlsx,.xls"
        >
          <el-button size="small" type="primary">上传Excel</el-button> <span style="margin-left:5px;color:orange">{{ uploadedFilePath?'上传成功':'' }}</span>
        </el-upload>
      </div>
      
      <div class="ml-auto">
        <span class="text-sm mr-2">时间段</span>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          size="small"
          range-separator="/"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
        />
      </div>
    </div>
    
    <!-- Input area -->
    <div class="flex gap-2 items-end mt-auto">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="2"
        placeholder="请进行数据分析，给一个总结报告，不超过300字"
        class="flex-1"
        resize="none"
      />
      <el-button
        type="primary"
        @click="sendMessage"
        :disabled="loading || !inputMessage.trim()"
        size="small"
        style="height: 53px; "
      >
        发送
      </el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, computed, onMounted } from 'vue';
import { marked } from 'marked';
import { ChatLineRound, User, Download } from '@element-plus/icons-vue';
import { Document, Paragraph, TextRun, Packer } from 'docx';
import { 
  askAIQuestion,
  uploadFileApi, 
  getLatestQuestionList,
  type AIQuestionParams,
  type UploadFileResponse,
  type ChatContent,
  type LatestQuestionResponse,
  type AIQuestionResponse
} from '../api';
import { ElMessage } from 'element-plus/es'
import * as internal from 'stream';
const renderMarkdown = (content: string): string => {
  // Configure marked with options
  marked.setOptions({
    breaks: true,
    gfm: true
  });

  try {
    return marked.parse(content) as string;
  } catch (error) {
    console.error('Markdown parsing error:', error);
    return content.replace(/</g, '<').replace(/>/g, '>'); // Escape HTML if parsing fails
  }
};

const exportToWord = async (content: string) => {
  // 先将markdown转换为HTML
  let htmlContent = '';
  try {
    const result = await marked.parse(content, {
      breaks: true,
      gfm: true
    });
    htmlContent = result;
  } catch (error) {
    console.error('Markdown parsing error:', error);
    htmlContent = content; // Fallback to raw content
  }
  
  // 创建一个临时的div来解析HTML
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = htmlContent;
  
  // 准备Word文档的段落
  const docChildren: Paragraph[] = [];
  
  // 处理每个HTML元素并转换为Word文档元素
  Array.from(tempDiv.childNodes).forEach((node) => {
    if (node.nodeType === Node.TEXT_NODE) {
      // 处理纯文本节点
      if (node.textContent && node.textContent.trim()) {
        docChildren.push(
          new Paragraph({
            children: [new TextRun({ text: node.textContent.trim() })],
          })
        );
      }
    } else if (node.nodeType === Node.ELEMENT_NODE) {
      const element = node as HTMLElement;
      
      // 根据HTML标签类型创建不同的Word元素
      if (element.tagName === 'H1' || element.tagName === 'H2' || element.tagName === 'H3') {
        docChildren.push(
          new Paragraph({
            heading: element.tagName === 'H1' ? 'Heading1' : element.tagName === 'H2' ? 'Heading2' : 'Heading3',
            children: [
              new TextRun({
                text: element.textContent || '',
                bold: true,
                size: element.tagName === 'H1' ? 36 : element.tagName === 'H2' ? 32 : 28,
              }),
            ],
          })
        );
      } else if (element.tagName === 'P') {
        docChildren.push(
          new Paragraph({
            children: [new TextRun({ text: element.textContent || '' })],
            spacing: { after: 200 },
          })
        );
      } else if (element.tagName === 'UL' || element.tagName === 'OL') {
        // 处理列表
        Array.from(element.children).forEach((li, index) => {
          docChildren.push(
            new Paragraph({
              children: [
                new TextRun({ text: element.tagName === 'UL' ? '• ' : `${index + 1}. ` }),
                new TextRun({ text: li.textContent || '' }),
              ],
              indent: { left: 720 }, // 缩进
              spacing: { after: 120 },
            })
          );
        });
      } else if (element.tagName === 'BLOCKQUOTE') {
        docChildren.push(
          new Paragraph({
            children: [new TextRun({ text: element.textContent || '', italics: true })],
            indent: { left: 720 },
            border: { left: { color: '#CCCCCC', size: 6, space: 15, style: 'single' } },
            spacing: { after: 200 },
          })
        );
      } else if (element.tagName === 'PRE') {
        // 代码块
        docChildren.push(
          new Paragraph({
            children: [new TextRun({ 
              text: element.textContent || '', 
              font: { name: 'Courier New' } 
            })],
            shading: { 
              fill: '#F6F8FA',
              type: 'clear'
            },
            spacing: { after: 200 },
          })
        );
      } else {
        // 其他元素默认处理
        docChildren.push(
          new Paragraph({
            children: [new TextRun({ text: element.textContent || '' })],
          })
        );
      }
    }
  });
  
  // 创建Word文档
  const doc = new Document({
    sections: [{
      properties: {},
      children: docChildren,
    }],
  });

  const blob = await Packer.toBlob(doc);
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'AI分析报告.docx';
  a.click();
  URL.revokeObjectURL(url);
};

type DataSourceType = 'system' | 'custom' | 'upload' | 'free';
type SystemTableType = 'clue' | 'business_opportunity' | 'customer' | 'contact' | 'contract' | 'order' | 'product';

interface ChatMessage {
  role: 'user' | 'assistant';
  content: string;
  loading?: boolean;
}

// Data source selection
const dataSource = ref<DataSourceType>('system');
const systemTable = ref<SystemTableType>('clue');
const getFirstDayOfMonth = () => {
  const date = new Date();
  return new Date(date.getFullYear(), date.getMonth(), 1);
};

const uploadFile = ref<File | null>(null);
const uploadedFilePath = ref<string>('');

const beforeUpload = (file: File) => {
  uploadFile.value = file;
  uploadedFilePath.value = '';
  return true;
};

const handleUpload = async (options: any) => {
  try {
    const result = await uploadFileApi(options.file);
    if (result.code === 'ok') {
      uploadedFilePath.value = result.data;
      // Show upload success message
      ElMessage.success("上传成功，请输入问题并发送")
    } else {
      console.error('Upload failed:', result);
    }
  } catch (error) {
    console.error('Upload error:', error);
  }
};

const dateRange = ref([getFirstDayOfMonth(), new Date()]);

// Chat functionality
const inputMessage = ref('请进行数据分析，给一个总结报告，不超过300字');
const loading = ref(false);
const messages = reactive<ChatMessage[]>([]);
const questionId = ref<number | null>(null);

const isSameDay = (dateString: string, compareDate: Date) => {
  // Parse yyyy-MM-dd hh:mm:ss format
  const [datePart] = dateString.split(' ');
  const [year, month, day] = datePart.split('-').map(Number);
  
  return year === compareDate.getFullYear() &&
         month - 1 === compareDate.getMonth() && // Months are 0-indexed in JS
         day === compareDate.getDate();
};

onMounted(async () => {
  try {
    const result = await getLatestQuestionList();
    if (result.code === 'ok' && result.data.contents) {
      result.data.contents.forEach(content => {
        messages.push({
          role: content.type === 0 ? 'assistant' : 'user',
          content: content.content
        });

        // Check if createTime is today and set questionId
        if (content.createTime && content.questionId) {
          if (isSameDay(content.createTime, new Date())) {
            questionId.value = content.questionId;
          }
        }
      });
    } else {
      // Default message if no history
      messages.push({ role: 'assistant', content: '你好，需要分析查询哪些数据，请交给我' });
    }
  } catch (error) {
    console.error('Failed to load chat history:', error);
    messages.push({ role: 'assistant', content: '你好，需要分析查询哪些数据，请交给我' });
  }
});

const sendMessage = async () => {
  if (!inputMessage.value.trim() || loading.value) return;

  loading.value = true;
  const userMessage: ChatMessage = { role: 'user', content: inputMessage.value };
  messages.push(userMessage);
  const thinkingIndex = messages.length;
  messages.push({ role: 'assistant', content: 'AI正在思考', loading: true });
  
  try {
    type DataSourceType = 'system' | 'custom' | 'upload' | 'free';
    const dataSourceMap: Record<DataSourceType, number> = {
      'system': 1,
      'custom': 2,
      'upload': 3, 
      'free': 4
    };

    const params: AIQuestionParams & { questionId?: number } = {
      questionDataSource: dataSourceMap[dataSource.value],
      sourceContent: dataSource.value === 'system' ? systemTable.value : '',
      content: inputMessage.value,
      startDate: dateRange.value[0]?.toISOString().split('T')[0],
      endDate: dateRange.value[1]?.toISOString().split('T')[0],
      url: dataSource.value === 'upload' ? uploadedFilePath.value : ''
    };

    // Only include questionId if we have one from today's conversation
    if (questionId.value) {
      params.questionId = questionId.value;
    }

    const result = await askAIQuestion(params);
    messages[thinkingIndex] = {
      role: 'assistant',
      content: result.data.queryRes || '根据您的请求，我已分析了相关数据。分析结果显示...',
      loading: false
    };
    questionId.value = result.data.questionId;
  } catch (error) {
    console.error('API error:', error);
    messages[thinkingIndex] = {
      role: 'assistant',
      content: '抱歉，请求处理失败，请稍后再试',
      loading: false
    };
  }

  inputMessage.value = '';
  loading.value = false;
  // 触发滚动到底部
  nextTick(() => {
    const container = document.querySelector('.overflow-y-auto');
    if (container) {
      container.scrollTop = container.scrollHeight;
    }
  });
};
</script>

<style scoped>
:deep(.el-textarea__inner) {
  resize: none;
}

.markdown-body {
  line-height: 1.5;
  word-wrap: break-word;
}

.markdown-body :deep(h1),
.markdown-body :deep(h2),
.markdown-body :deep(h3),
.markdown-body :deep(h4),
.markdown-body :deep(h5),
.markdown-body :deep(h6) {
  margin-top: 0.5em;
  margin-bottom: 0.5em;
  font-weight: bold;
}

.markdown-body :deep(p) {
  margin-bottom: 1em;
}

.markdown-body :deep(ul),
.markdown-body :deep(ol) {
  padding-left: 2em;
  margin-bottom: 1em;
}

.markdown-body :deep(li) {
  margin-bottom: 0.5em;
}

.markdown-body :deep(code) {
  background-color: rgba(175, 184, 193, 0.2);
  border-radius: 3px;
  padding: 0.2em 0.4em;
  font-family: monospace;
}

.markdown-body :deep(pre) {
  background-color: #f6f8fa;
  border-radius: 3px;
  padding: 1em;
  overflow: auto;
  margin-bottom: 1em;
}

.markdown-body :deep(blockquote) {
  border-left: 4px solid #dfe2e5;
  color: #6a737d;
  padding-left: 1em;
  margin-left: 0;
  margin-bottom: 1em;
}

.loading-dots {
  display: inline-flex;
  align-items: center;
  gap: 2px;
}

.loading-dots span {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: currentColor;
  animation: bounce 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounce {
  0%, 80%, 100% { 
    transform: scale(0);
  } 40% { 
    transform: scale(1.0);
  }
}
</style>
