<template>
  <div class="image-recognition-container">
    <div class="recognition-card">
      <h1 class="page-title">蜂快AI·快递取件码识别</h1>
      
      <div class="upload-section">
        <div 
          class="image-upload-area" 
          @click="triggerFileInput"
          :class="{ 'has-image': previewImage }"
        >
          <div v-if="!previewImage" class="upload-placeholder">
            <div class="upload-icon">
              <i class="el-icon-upload"></i>
            </div>
            <div class="upload-text">点击上传图片</div>
            <div class="upload-hint">支持快递短信截图、取件码截图等</div>
          </div>
          <img v-else :src="previewImage" class="preview-image" alt="预览图片" />
          
          <input 
            type="file" 
            ref="fileInput" 
            accept="image/*" 
            class="file-input" 
            @change="handleFileChange" 
          />
        </div>
        
        <div class="action-buttons">
          <button 
            class="btn-upload" 
            @click="triggerFileInput" 
            :disabled="isRecognizing"
          >
            {{ previewImage ? '重新选择' : '选择图片' }}
          </button>
          <button 
            class="btn-recognize" 
            @click="recognizeImage" 
            :disabled="!previewImage || isRecognizing"
          >
            {{ isRecognizing ? 'AI识别中...' : '开始识别' }}
          </button>
        </div>
      </div>
      
      <div v-if="recognitionStatus" class="status-message" :class="statusClass">
        {{ recognitionStatus }}
      </div>
      
      <div v-if="recognitionResult" class="result-section">
        <h2 class="result-title">识别结果</h2>
        <div class="result-content">
          <pre class="formatted-result">{{ recognitionResult.formatted_text }}</pre>
          
          <div class="result-details">
            <div v-for="(station, index) in recognitionResult.raw.stations" :key="index" class="station-item">
              <div class="station-name">驿站：{{ station.name }}</div>
              <div class="pickup-codes-container">
                <div v-for="(code, codeIndex) in station.pickup_codes" :key="codeIndex" class="pickup-code">
                  取件码：<span class="code-value">{{ code }}</span>
                  <button class="btn-copy" @click="copyToClipboard(code)">复制</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import apiClient from '../services/api'

export default {
  name: 'ImageRecognition',
  setup() {
    const fileInput = ref(null)
    const previewImage = ref(null)
    const selectedFile = ref(null)
    const isRecognizing = ref(false)
    const recognitionStatus = ref('')
    const statusClass = ref('')
    const recognitionResult = ref(null)
    
    // 触发文件选择
    const triggerFileInput = () => {
      if (!isRecognizing.value) {
        fileInput.value.click()
      }
    }
    
    // 处理文件选择
    const handleFileChange = (event) => {
      const file = event.target.files[0]
      if (file) {
        selectedFile.value = file
        
        // 创建预览
        const reader = new FileReader()
        reader.onload = (e) => {
          previewImage.value = e.target.result
        }
        reader.readAsDataURL(file)
        
        // 重置识别状态
        recognitionStatus.value = ''
        recognitionResult.value = null
      }
    }
    
    // 识别图片
    const recognizeImage = async () => {
      if (!selectedFile.value || isRecognizing.value) return
      
      isRecognizing.value = true
      recognitionStatus.value = 'AI 识别中，请稍候...'
      statusClass.value = 'status-processing'
      
      try {
        const formData = new FormData()
        formData.append('file', selectedFile.value)
        
        // 添加超时处理
        const controller = new AbortController()
        const timeoutId = setTimeout(() => controller.abort(), 60000) // 60秒超时
        
        const response = await apiClient.post('/api/ai/recognition/pickup_code', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          signal: controller.signal
        })
        
        clearTimeout(timeoutId) // 清除超时
        
        if (response.data && response.data.code === 200) {
          recognitionResult.value = processRecognitionData(response.data.data)
          recognitionStatus.value = '识别成功！'
          statusClass.value = 'status-success'
        } else {
          recognitionStatus.value = response.data?.message || '识别失败，请重试'
          statusClass.value = 'status-error'
        }
      } catch (error) {
        console.error('识别失败:', error)
        
        if (error.name === 'AbortError' || error.code === 'ECONNABORTED') {
          recognitionStatus.value = '请求超时，请检查网络或稍后重试'
        } else {
          recognitionStatus.value = '识别失败，请重试'
        }
        
        statusClass.value = 'status-error'
      } finally {
        isRecognizing.value = false
      }
    }
    
    // 处理识别数据
    const processRecognitionData = (data) => {
      // 检查数据是否为数组格式
      if (Array.isArray(data)) {
        // 从数组中获取第一个元素
        const firstItem = data[0]
        
        // 构建格式化文本
        let formattedText = ''
        if (firstItem && firstItem.stations) {
          firstItem.stations.forEach(station => {
            formattedText += `驿站：${station.name}\n`
            if (station.pickup_codes && station.pickup_codes.length > 0) {
              station.pickup_codes.forEach(code => {
                formattedText += `取件码：${code}\n`
              })
            }
            formattedText += '\n'
          })
        }
        
        // 返回处理后的数据结构
        return {
          raw: firstItem || { stations: [] },
          formatted_text: formattedText.trim()
        }
      } else {
        // 如果不是数组格式，直接返回原始数据
        return data
      }
    }
    
    // 复制到剪贴板
    const copyToClipboard = (text) => {
      const tempCopyStatus = recognitionStatus.value
      const tempStatusClass = statusClass.value
      
      navigator.clipboard.writeText(text)
        .then(() => {
          recognitionStatus.value = '取件码已复制到剪贴板'
          statusClass.value = 'status-success'
          
          // 3秒后恢复原状态
          setTimeout(() => {
            recognitionStatus.value = tempCopyStatus
            statusClass.value = tempStatusClass
          }, 3000)
        })
        .catch(err => {
          console.error('复制失败:', err)
          recognitionStatus.value = '复制失败，请手动复制'
          statusClass.value = 'status-error'
          
          // 3秒后恢复原状态
          setTimeout(() => {
            recognitionStatus.value = tempCopyStatus
            statusClass.value = tempStatusClass
          }, 3000)
        })
    }
    
    onMounted(() => {
      document.title = '蜂快AI·快递取件码识别'
    })
    
    onBeforeUnmount(() => {
      document.title = '蜂快到家'
    })
    
    return {
      fileInput,
      previewImage,
      isRecognizing,
      recognitionStatus,
      statusClass,
      recognitionResult,
      triggerFileInput,
      handleFileChange,
      recognizeImage,
      copyToClipboard
    }
  }
}
</script>

<style scoped>
.image-recognition-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 15px;
  background: linear-gradient(to bottom, #FFCC00, #FFFFFF);
}

.recognition-card {
  width: 100%;
  max-width: 500px;
  background-color: #FFFFFF;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 25px 20px;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  margin-bottom: 25px;
}

.upload-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 20px;
}

.image-upload-area {
  width: 100%;
  height: 200px;
  border: 2px dashed #DDDDDD;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
}

.image-upload-area:hover {
  border-color: #FFCC00;
  background-color: rgba(255, 204, 0, 0.05);
}

.image-upload-area.has-image {
  border-style: solid;
  border-color: #FFCC00;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.upload-icon {
  font-size: 40px;
  color: #DDDDDD;
}

.upload-text {
  font-size: 16px;
  font-weight: 500;
  color: #666666;
}

.upload-hint {
  font-size: 12px;
  color: #999999;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.file-input {
  display: none;
}

.action-buttons {
  display: flex;
  gap: 15px;
}

.btn-upload, .btn-recognize {
  flex: 1;
  padding: 12px 15px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  text-align: center;
  border: none;
}

.btn-upload {
  background-color: #F2F2F2;
  color: #666666;
}

.btn-recognize {
  background-color: #FFCC00;
  color: #333333;
}

.btn-upload:hover {
  background-color: #E6E6E6;
}

.btn-recognize:hover {
  background-color: #FFD633;
}

.btn-upload:disabled, .btn-recognize:disabled {
  background-color: #DDDDDD;
  color: #999999;
  cursor: not-allowed;
}

.status-message {
  padding: 10px 15px;
  border-radius: 8px;
  font-size: 14px;
  margin-bottom: 20px;
  text-align: center;
}

.status-processing {
  background-color: rgba(255, 204, 0, 0.1);
  color: #FFCC00;
  border: 1px solid rgba(255, 204, 0, 0.3);
}

.status-success {
  background-color: rgba(0, 230, 118, 0.1);
  color: #00E676;
  border: 1px solid rgba(0, 230, 118, 0.3);
}

.status-error {
  background-color: rgba(255, 87, 87, 0.1);
  color: #FF5757;
  border: 1px solid rgba(255, 87, 87, 0.3);
}

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

.result-title {
  font-size: 18px;
  font-weight: bold;
  color: #333333;
  margin-bottom: 15px;
}

.result-content {
  background-color: #F9F9F9;
  border-radius: 8px;
  padding: 15px;
}

.formatted-result {
  font-family: monospace;
  white-space: pre-wrap;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #F2F2F2;
  border-radius: 6px;
  font-size: 14px;
  color: #333333;
}

.result-details {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.station-item {
  padding: 15px;
  background-color: #FFFFFF;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 15px;
}

.station-name {
  font-weight: 600;
  color: #333333;
  margin-bottom: 12px;
  font-size: 16px;
}

.pickup-codes-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.pickup-code {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #666666;
}

.code-value {
  font-weight: bold;
  color: #FFCC00;
  font-size: 18px;
}

.btn-copy {
  padding: 4px 8px;
  background-color: #FFCC00;
  color: #333333;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-copy:hover {
  background-color: #FFD633;
}

@media (max-width: 480px) {
  .recognition-card {
    padding: 20px 15px;
  }
  
  .page-title {
    font-size: 20px;
    margin-bottom: 20px;
  }
  
  .image-upload-area {
    height: 180px;
  }
  
  .btn-upload, .btn-recognize {
    padding: 10px 12px;
    font-size: 15px;
  }
}
</style> 