<template>
  <div class="canvas-ocr-container">
    <h3>Canvas内容识别</h3>

    <div class="form-section">
      <div class="form-group">
        <label for="targetUrl">目标网页URL:</label>
        <input 
          id="targetUrl"
          v-model="targetUrl" 
          type="text" 
          placeholder="https://docs.qq.com/sheet/DQVZpaFVqdnJFU3hn"
        />
        <button 
          class="btn primary-btn"
          @click="openUrlInNewTab"
          :disabled="!isValidUrl"
        >
          在新标签页中打开
        </button>
      </div>

      <div class="instruction-section">
        <h4>识别步骤：</h4>
        <ol>
          <li>输入目标网页URL并点击"在新标签页中打开"</li>
          <li>在打开的页面中定位到需要识别的Canvas区域</li>
          <li>点击下方"开始截图"按钮</li>
          <li>在弹出的共享屏幕对话框中，选择对应的浏览器标签页</li>
          <li>选择区域后，系统将自动进行OCR识别</li>
        </ol>
      </div>

      <div class="actions">
        <button 
          class="btn capture-btn" 
          @click="startScreenCapture"
          :disabled="isCapturing"
        >
          {{ isCapturing ? '截图中...' : '开始截图' }}
        </button>
      </div>
    </div>

    <!-- 截图预览 -->
    <div v-if="capturedImage" class="preview-section">
      <h4>截图预览:</h4>
      <div class="image-container">
        <img :src="capturedImage" alt="截图预览" />
      </div>
      <div class="image-actions">
        <button class="btn secondary-btn" @click="processImage">增强图像</button>
        <button class="btn primary-btn" @click="performOcr" :disabled="isOcrProcessing">
          {{ isOcrProcessing ? 'OCR识别中...' : '开始OCR识别' }}
        </button>
      </div>
    </div>

    <!-- OCR结果 -->
    <div v-if="ocrResult" class="result-section">
      <h4>OCR识别结果:</h4>
      <div class="result-container">
        <textarea 
          v-model="ocrResult" 
          rows="10"
          readonly
        />
      </div>
      <div class="result-actions">
        <button class="btn secondary-btn" @click="copyToClipboard">复制到剪贴板</button>
        <button class="btn secondary-btn" @click="downloadAsText">下载为文本文件</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { captureScreen, preprocessImageForOCR, dataURLtoBlob } from '@/utils/screenshot';
import { createWorker } from 'tesseract.js';

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

// 状态变量
const targetUrl = ref<string>('');
const capturedImage = ref<string>('');
const processedImage = ref<string>('');
const ocrResult = ref<string>('');
const isCapturing = ref<boolean>(false);
const isOcrProcessing = ref<boolean>(false);

// 计算属性
const isValidUrl = computed(() => {
  if (!targetUrl.value) return false;
  try {
    new URL(targetUrl.value);
    return true;
  } catch (e) {
    return false;
  }
});

// 在新标签页中打开URL
const openUrlInNewTab = () => {
  if (!isValidUrl.value) return;
  window.open(targetUrl.value, '_blank');
};

// 开始屏幕截图
const startScreenCapture = async () => {
  try {
    isCapturing.value = true;
    capturedImage.value = '';
    processedImage.value = '';
    ocrResult.value = '';
    
    // 调用截图功能
    const screenshotDataUrl = await captureScreen();
    capturedImage.value = screenshotDataUrl;
  } catch (error) {
    console.error('截图失败:', error);
    alert('截图失败: ' + (error instanceof Error ? error.message : '未知错误'));
  } finally {
    isCapturing.value = false;
  }
};

// 图像预处理
const processImage = async () => {
  if (!capturedImage.value) return;
  
  try {
    // 对图像进行预处理以提高OCR识别率
    processedImage.value = await preprocessImageForOCR(capturedImage.value);
    // 更新预览图像
    capturedImage.value = processedImage.value;
  } catch (error) {
    console.error('图像处理失败:', error);
    alert('图像处理失败: ' + (error instanceof Error ? error.message : '未知错误'));
  }
};

// 执行OCR识别
const performOcr = async () => {
  const imageToProcess = processedImage.value || capturedImage.value;
  if (!imageToProcess) return;
  
  try {
    isOcrProcessing.value = true;
    ocrResult.value = '';
    
    // 创建Tesseract Worker
    const worker = await createWorker(['chi_sim', 'eng'], 1, {
      logger: m => console.log(m),
      langPath: 'https://tessdata.projectnaptha.com/4.0.0'
    });
    
    // 执行OCR识别
    const { data: { text } } = await worker.recognize(imageToProcess);
    ocrResult.value = text;
    
    // 终止Worker
    await worker.terminate();
  } catch (error) {
    console.error('OCR识别失败:', error);
    alert('OCR识别失败: ' + (error instanceof Error ? error.message : '未知错误'));
  } finally {
    isOcrProcessing.value = false;
  }
};

// 复制到剪贴板
const copyToClipboard = () => {
  if (!ocrResult.value) return;
  
  navigator.clipboard.writeText(ocrResult.value)
    .then(() => {
      alert('已复制到剪贴板');
    })
    .catch(err => {
      console.error('复制失败:', err);
      alert('复制失败: ' + err);
    });
};

// 下载为文本文件
const downloadAsText = () => {
  if (!ocrResult.value) return;
  
  const blob = new Blob([ocrResult.value], { type: 'text/plain' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `ocr_result_${new Date().toISOString().replace(/[:.]/g, '-')}.txt`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};
</script>

<style scoped>
.canvas-ocr-container {
  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;
  display: flex;
  align-items: center;
  gap: 10px;
}

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

.form-group input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.instruction-section {
  background-color: #f0f8ff;
  padding: 15px;
  border-radius: 4px;
  margin: 15px 0;
}

.instruction-section h4 {
  margin-top: 0;
  margin-bottom: 10px;
}

.instruction-section ol {
  margin: 0;
  padding-left: 20px;
}

.instruction-section li {
  margin-bottom: 5px;
}

.actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

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

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

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

.primary-btn:hover:not(:disabled) {
  background-color: #45a049;
}

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

.secondary-btn:hover:not(:disabled) {
  background-color: #0b7dda;
}

.capture-btn {
  background-color: #ff9800;
  color: white;
  font-size: 16px;
  padding: 12px 24px;
}

.capture-btn:hover:not(:disabled) {
  background-color: #e68a00;
}

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

.image-container {
  max-width: 100%;
  overflow: hidden;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin: 10px 0;
}

.image-container img {
  max-width: 100%;
  height: auto;
  display: block;
}

.image-actions, .result-actions {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

.result-container {
  margin: 10px 0;
}

.result-container textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-family: monospace;
  font-size: 14px;
  resize: vertical;
}
</style> 