<template>
  <div class="tencent-doc-crawler">
    <h3>腾讯文档内容获取</h3>

    <div class="form-section">
      <div class="form-group">
        <label for="documentUrl">文档URL:</label>
        <input 
          id="documentUrl"
          v-model="documentUrl" 
          type="text" 
          placeholder="https://docs.qq.com/sheet/DQVZpaFVqdnJFU3hn"
        />
      </div>

      <div class="form-group">
        <label for="cookie">Cookie:</label>
        <textarea 
          id="cookie"
          v-model="cookie" 
          placeholder="从浏览器复制Cookie，确保已登录腾讯文档"
          rows="3"
        ></textarea>
        <div class="help-text">
          <p>提示: 获取Cookie方法</p>
          <ol>
            <li>登录腾讯文档</li>
            <li>按F12打开开发者工具</li>
            <li>选择Network（网络）选项卡</li>
            <li>刷新页面</li>
            <li>选择任意请求，在Headers中找到Cookie</li>
          </ol>
        </div>
      </div>

      <div class="actions">
        <button 
          class="primary-btn" 
          @click="startExport" 
          :disabled="isLoading || !isFormValid"
        >
          {{ isLoading ? '处理中...' : '获取文档内容' }}
        </button>
      </div>
    </div>

    <!-- 进度显示 -->
    <div v-if="isLoading" class="progress-section">
      <div class="progress-bar">
        <div class="progress-fill" :style="{ width: `${progress}%` }"></div>
      </div>
      <p>{{ progressText }}</p>
    </div>

    <!-- 错误信息 -->
    <div v-if="errorMessage" class="error-message">
      <p>{{ errorMessage }}</p>
    </div>

    <!-- 结果显示 -->
    <div v-if="exportedData" class="result-section">
      <h4>导出成功</h4>
      <div class="action-buttons">
        <button class="secondary-btn" @click="downloadExcel">
          下载Excel文件
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { TencentDocClient } from '@/utils/tencentDocApi';

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

// 表单数据
const documentUrl = ref<string>('');
const cookie = ref<string>('');
const isLoading = ref<boolean>(false);
const progress = ref<number>(0);
const progressText = ref<string>('');
const errorMessage = ref<string>('');
const exportedData = ref<ArrayBuffer | null>(null);

// 表单验证
const isFormValid = computed(() => {
  return documentUrl.value.trim() !== '' && 
         cookie.value.trim() !== '' && 
         documentUrl.value.includes('docs.qq.com');
});

// 开始导出
const startExport = async () => {
  if (!isFormValid.value) return;
  
  try {
    isLoading.value = true;
    errorMessage.value = '';
    exportedData.value = null;
    progress.value = 0;
    progressText.value = '创建导出任务...';

    // 创建API客户端
    const client = new TencentDocClient({
      cookie: cookie.value,
      documentUrl: documentUrl.value
    });

    // 创建导出任务
    const operationResult = await client.createExportTask();
    console.log(operationResult,'22222')

    if (!operationResult.status) {
      throw new Error(`创建导出任务失败: ${operationResult.message}`);
    }

    const operationId = operationResult.operationId;
    let retries = 0;
    const maxRetries = 20;
    let fileUrl = '';

    progressText.value = '等待导出处理...';

    // 轮询查询进度
    while (retries < maxRetries) {
      const progressResult = await client.queryExportProgress(operationId);
      progress.value = progressResult.progress || 0;
      progressText.value = `导出进度: ${progress.value}%`;
      
      if (progressResult.progress === 100 && progressResult.file_url) {
        fileUrl = progressResult.file_url;
        break;
      }
      
      retries++;
      await new Promise(resolve => setTimeout(resolve, 1000));
    }

    if (!fileUrl) {
      throw new Error('导出超时或未获取到文件下载地址');
    }

    progressText.value = '下载文件中...';
    // 下载文件
    exportedData.value = await client.downloadExportedFile(fileUrl);
    progressText.value = '导出成功!';

  } catch (error) {
    console.error('导出失败:', error);
    errorMessage.value = error instanceof Error ? error.message : '未知错误';
  } finally {
    isLoading.value = false;
  }
};

// 下载Excel文件
const downloadExcel = () => {
  if (!exportedData.value) return;

  const blob = new Blob([exportedData.value], { 
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
  });
  
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  
  // 从文档URL中提取文件名
  const urlParts = documentUrl.value.split('/');
  const docId = urlParts[urlParts.length - 1].split('?')[0];
  const fileName = `tencent_doc_${docId}.xlsx`;
  
  link.href = url;
  link.setAttribute('download', fileName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);
};
</script>

<style scoped>
.tencent-doc-crawler {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.form-section {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

input, textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.help-text {
  margin-top: 5px;
  font-size: 12px;
  color: #666;
}

.help-text ol {
  padding-left: 20px;
  margin-top: 5px;
}

.actions {
  margin-top: 20px;
}

.primary-btn, .secondary-btn {
  padding: 10px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.primary-btn {
  background-color: #4CAF50;
  color: white;
}

.primary-btn:hover {
  background-color: #45a049;
}

.primary-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.secondary-btn {
  background-color: #2196F3;
  color: white;
  margin-right: 10px;
}

.secondary-btn:hover {
  background-color: #0b7dda;
}

.progress-section {
  margin: 20px 0;
}

.progress-bar {
  height: 20px;
  background-color: #f1f1f1;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #4CAF50;
  transition: width 0.3s;
}

.error-message {
  background-color: #ffebee;
  color: #c62828;
  padding: 10px;
  border-radius: 4px;
  margin: 20px 0;
}

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

.action-buttons {
  margin-top: 15px;
}
</style> 