<template>
  <view class="scan-page">
    <!-- 顶部导航栏 -->
    <view class="header-bg" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="header-content">
        <view class="back-btn" @click="handleBack">
          <text class="back-icon">‹</text>
        </view>
        <text class="header-title">小程序扫描</text>
        <view class="placeholder"></view>
      </view>
    </view>
    
    <!-- 扫描区域 -->
    <view class="scan-area">
      <camera 
        device-position="back" 
        flash="off" 
        class="camera"
        @error="handleCameraError"
      >
        <!-- 检测边框覆盖层 -->
        <canvas 
          v-if="detectedBorders.length > 0"
          canvas-id="borderCanvas" 
          class="border-canvas"
          :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
        ></canvas>
      </camera>
      
      <!-- 模式切换按钮 - 在底部操作栏上方 -->
      <view class="mode-switch-wrapper">
        <view class="mode-switch">
          <view 
            class="mode-btn" 
            :class="{ active: scanMode === 'single' }"
            @click="switchToSingle"
          >
            <text class="mode-text">单页</text>
          </view>
          <view 
            class="mode-btn" 
            :class="{ active: scanMode === 'multiple' }"
            @click="switchToMultiple"
          >
            <text class="mode-text">多页</text>
          </view>
        </view>
      </view>
      
      <!-- 底部操作按钮 -->
      <view class="action-buttons">
        <view class="action-btn" @click="handleSelectImage">
          <image class="btn-icon" src="/static/pages/scan/image.png" mode="aspectFit" />
          <text class="btn-text">导入图片</text>
        </view>
        
        <view class="capture-btn" @click="handleCapture">
          <view class="capture-inner"></view>
        </view>
        
        <view class="action-btn" @click="handleSelectFile">
          <image class="btn-icon" src="/static/pages/scan/file.png" mode="aspectFit" />
          <text class="btn-text">导入文档</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

// 状态栏高度
const statusBarHeight = ref(0)

// 扫描模式：single-单页，multiple-多页
const scanMode = ref('single')

// 检测到的边框
const detectedBorders = ref([])

// Canvas尺寸
const canvasWidth = ref(0)
const canvasHeight = ref(0)

// 相机上下文
let cameraContext = null

// Canvas上下文
let canvasContext = null

// 扫描定时器
let scanTimer = null

onMounted(() => {
  // 获取系统信息
  const windowInfo = uni.getWindowInfo()
  statusBarHeight.value = windowInfo.statusBarHeight || 0
  
  // 获取屏幕尺寸
  const systemInfo = uni.getSystemInfoSync()
  canvasWidth.value = systemInfo.windowWidth
  canvasHeight.value = systemInfo.windowHeight - statusBarHeight.value - 88 - 200 // 减去头部和底部按钮高度
  
  // 初始化相机上下文
  cameraContext = uni.createCameraContext()
  
  // 初始化Canvas上下文
  canvasContext = uni.createCanvasContext('borderCanvas')
  
  // 开始实物检测
  startDetection()
})

onUnmounted(() => {
  // 停止检测
  stopDetection()
})

// 返回上一页
const handleBack = () => {
  uni.reLaunch({
    url: '/pages/home/index'
  })
}

// 切换扫描模式
const toggleScanMode = () => {
  scanMode.value = scanMode.value === 'single' ? 'multiple' : 'single'
  
  uni.showToast({
    title: scanMode.value === 'single' ? '已切换到单页模式' : '已切换到多页模式',
    icon: 'none',
    duration: 1500
  })
}

// 切换到单页模式
const switchToSingle = () => {
  if (scanMode.value === 'single') return
  scanMode.value = 'single'
  
  uni.showToast({
    title: '已切换到单页模式',
    icon: 'none',
    duration: 1500
  })
}

// 切换到多页模式
const switchToMultiple = () => {
  if (scanMode.value === 'multiple') return
  scanMode.value = 'multiple'
  
  uni.showToast({
    title: '已切换到多页模式',
    icon: 'none',
    duration: 1500
  })
}

// 相机错误处理
const handleCameraError = (e) => {
  console.error('相机错误:', e)
  uni.showToast({
    title: '相机启动失败',
    icon: 'none'
  })
}

// 开始实物检测
const startDetection = () => {
  // 每隔一段时间进行一次实物检测
  scanTimer = setInterval(() => {
    detectObject()
  }, 300) // 每300ms检测一次
}

// 停止检测
const stopDetection = () => {
  if (scanTimer) {
    clearInterval(scanTimer)
    scanTimer = null
  }
}

// 检测实物
const detectObject = () => {
  if (!cameraContext) return
  
  // 拍摄临时照片用于检测
  cameraContext.takePhoto({
    quality: 'low', // 使用低质量以提高检测速度
    success: (res) => {
      // 分析图片检测实物
      analyzeImage(res.tempImagePath)
    },
    fail: () => {
      // 静默失败，继续下一次检测
    }
  })
}

// 分析图片中的实物
const analyzeImage = (imagePath) => {
  // TODO: 调用后端API或图像识别服务检测实物
  // 这里需要接入实际的物体检测API，例如：
  // - 百度AI文字识别OCR
  // - 腾讯云文档识别
  // - 阿里云文档检测
  
  // 模拟检测结果 - 检测到1-3个实物
  const hasObject = Math.random() > 0.3 // 70%概率检测到实物
  
  if (hasObject) {
    const objectCount = Math.floor(Math.random() * 3) + 1 // 1-3个实物
    const borders = []
    
    for (let i = 0; i < objectCount; i++) {
      // 生成随机位置的实物边框（模拟检测结果）
      const x = Math.random() * (canvasWidth.value - 200) + 50
      const y = Math.random() * (canvasHeight.value - 300) + 50
      const width = Math.random() * 200 + 150
      const height = Math.random() * 250 + 200
      
      borders.push({
        x,
        y,
        width,
        height,
        // 四个角点坐标（用于绘制更精确的边框）
        points: [
          { x, y }, // 左上
          { x: x + width, y }, // 右上
          { x: x + width, y: y + height }, // 右下
          { x, y: y + height } // 左下
        ]
      })
    }
    
    detectedBorders.value = borders
    
    // 绘制边框
    drawBorders(borders)
    
    // 自动对焦到第一个检测到的实物
    if (borders.length > 0) {
      autoFocus(borders[0])
    }
  } else {
    // 没有检测到实物，清空边框
    detectedBorders.value = []
    clearCanvas()
  }
}

// 绘制检测到的边框
const drawBorders = (borders) => {
  if (!canvasContext || !borders || borders.length === 0) return
  
  // 清空画布
  canvasContext.clearRect(0, 0, canvasWidth.value, canvasHeight.value)
  
  // 绘制每个检测到的边框
  borders.forEach((border, index) => {
    // 设置边框样式
    canvasContext.setStrokeStyle('#1ec9c9')
    canvasContext.setLineWidth(3)
    canvasContext.setLineDash([10, 5], 0) // 虚线效果
    
    // 绘制四边形边框
    canvasContext.beginPath()
    canvasContext.moveTo(border.points[0].x, border.points[0].y)
    border.points.forEach((point, i) => {
      if (i > 0) {
        canvasContext.lineTo(point.x, point.y)
      }
    })
    canvasContext.closePath()
    canvasContext.stroke()
    
    // 绘制四个角点
    border.points.forEach(point => {
      canvasContext.beginPath()
      canvasContext.arc(point.x, point.y, 8, 0, 2 * Math.PI)
      canvasContext.setFillStyle('#1ec9c9')
      canvasContext.fill()
      
      // 角点外圈
      canvasContext.beginPath()
      canvasContext.arc(point.x, point.y, 12, 0, 2 * Math.PI)
      canvasContext.setStrokeStyle('#ffffff')
      canvasContext.setLineWidth(2)
      canvasContext.stroke()
    })
    
    // 添加半透明填充
    canvasContext.setFillStyle('rgba(30, 201, 201, 0.1)')
    canvasContext.beginPath()
    canvasContext.moveTo(border.points[0].x, border.points[0].y)
    border.points.forEach((point, i) => {
      if (i > 0) {
        canvasContext.lineTo(point.x, point.y)
      }
    })
    canvasContext.closePath()
    canvasContext.fill()
  })
  
  // 绘制到屏幕
  canvasContext.draw()
}

// 清空画布
const clearCanvas = () => {
  if (!canvasContext) return
  canvasContext.clearRect(0, 0, canvasWidth.value, canvasHeight.value)
  canvasContext.draw()
}

// 自动对焦到实物
const autoFocus = (position) => {
  if (!cameraContext || !position) return
  
  // 计算实物中心点（相对于屏幕的比例）
  const centerX = (position.x + position.width / 2) / 750
  const centerY = (position.y + position.height / 2) / 1334
  
  // 设置对焦点
  console.log('自动对焦到实物:', centerX, centerY)
  
  // 注意：实际对焦效果取决于设备和平台支持
}

// 拍照
const handleCapture = () => {
  if (!cameraContext) return
  
  // 暂停检测
  stopDetection()
  
  cameraContext.takePhoto({
    quality: 'high',
    success: (res) => {
      console.log('拍照成功:', res.tempImagePath)
      
      uni.showLoading({
        title: '处理中...',
        mask: true
      })
      
      // TODO: 上传图片到服务器
      setTimeout(() => {
        uni.hideLoading()
        
        uni.showToast({
          title: '拍照成功',
          icon: 'success'
        })
        
        // 恢复检测
        startDetection()
      }, 1000)
    },
    fail: (err) => {
      console.error('拍照失败:', err)
      uni.showToast({
        title: '拍照失败',
        icon: 'none'
      })
      
      // 恢复检测
      startDetection()
    }
  })
}

// 导入图片
const handleSelectImage = () => {
  stopDetection()
  
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album'],
    success: (res) => {
      console.log('选择图片成功:', res.tempFilePaths)
      
      uni.showLoading({
        title: '处理中...',
        mask: true
      })
      
      // TODO: 上传图片到服务器
      setTimeout(() => {
        uni.hideLoading()
        
        uni.showToast({
          title: '图片导入成功',
          icon: 'success'
        })
        
        startDetection()
      }, 1000)
    },
    fail: () => {
      startDetection()
    }
  })
}

// 导入文档
const handleSelectFile = () => {
  stopDetection()
  
  uni.chooseMessageFile({
    count: 1,
    type: 'file',
    success: (res) => {
      console.log('选择文件成功:', res.tempFiles)
      
      uni.showLoading({
        title: '处理中...',
        mask: true
      })
      
      // TODO: 上传文件到服务器
      setTimeout(() => {
        uni.hideLoading()
        
        uni.showToast({
          title: '文档导入成功',
          icon: 'success'
        })
        
        startDetection()
      }, 1000)
    },
    fail: () => {
      startDetection()
    }
  })
}
</script>

<style lang="scss" scoped>
.scan-page {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #000000;
  
  // 顶部导航栏
  .header-bg {
    background: linear-gradient(180deg, #1ec9c9 0%, #1eb8b8 100%);
    position: relative;
    z-index: 100;
    
    .header-content {
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 24rpx;
      
      .back-btn {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        
        .back-icon {
          font-size: 56rpx;
          color: #ffffff;
          font-weight: 300;
        }
      }
      
      .header-title {
        flex: 1;
        text-align: center;
        font-size: 32rpx;
        font-weight: 600;
        color: #ffffff;
      }
      
      .placeholder {
        width: 60rpx;
      }
    }
  }
  
  // 扫描区域
  .scan-area {
    flex: 1;
    position: relative;
    display: flex;
    flex-direction: column;
    
    .camera {
      flex: 1;
      width: 100%;
      position: relative;
      
      // 边框检测画布
      .border-canvas {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 10;
        pointer-events: none;
      }
    }
    
    // 模式切换按钮 - 在底部操作栏上方
    .mode-switch-wrapper {
      position: absolute;
      bottom: 280rpx;
      left: 50%;
      transform: translateX(-50%);
      z-index: 10;
      
      .mode-switch {
        display: flex;
        background: rgba(0, 0, 0, 0.6);
        border-radius: 40rpx;
        padding: 6rpx;
        backdrop-filter: blur(10rpx);
        
        .mode-btn {
          padding: 12rpx 32rpx;
          border-radius: 34rpx;
          transition: all 0.3s;
          
          .mode-text {
            font-size: 26rpx;
            color: rgba(255, 255, 255, 0.6);
            font-weight: 500;
            transition: all 0.3s;
          }
          
          &.active {
            background: rgba(255, 255, 255, 0.9);
            
            .mode-text {
              color: #333333;
              font-weight: 600;
            }
          }
          
          &:active {
            transform: scale(0.95);
          }
        }
      }
    }
    
    // 底部操作按钮
    .action-buttons {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      background: #ffffff;
      padding: 32rpx 40rpx;
      padding-bottom: calc(32rpx + env(safe-area-inset-bottom));
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .action-btn {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 12rpx;
        
        .btn-icon {
          width: 48rpx;
          height: 48rpx;
        }
        
        .btn-text {
          font-size: 24rpx;
          color: #666666;
        }
      }
      
      .capture-btn {
        width: 120rpx;
        height: 120rpx;
        border-radius: 50%;
        background: #1ec9c9;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 4rpx 16rpx rgba(30, 201, 201, 0.4);
        
        &:active {
          transform: scale(0.95);
        }
        
        .capture-inner {
          width: 100rpx;
          height: 100rpx;
          border-radius: 50%;
          background: #ffffff;
        }
      }
    }
  }
}
</style>
