<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"
      >
      </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 v-if="scanMode === 'multiple' && pdfDataList.length > 0" class="thumbnail-list">
        <scroll-view scroll-x class="thumbnail-scroll">
          <view class="thumbnail-wrapper">
            <view 
              v-for="(item, index) in pdfDataList" 
              :key="index" 
              class="thumbnail-item"
              @click="handleViewAllPdf"
            >
              <view class="pdf-thumbnail-icon">
                <image src="/static/icon/pdf.svg" mode="aspectFit" class="pdf-icon-img" />
              </view>
              <view class="thumbnail-delete" @click.stop="handleDeletePdf(index)">
                <text class="delete-icon">×</text>
              </view>
              <view class="thumbnail-index">{{ index + 1 }}</view>
            </view>
          </view>
        </scroll-view>
      </view>
      
      <!-- 上传按钮（多页模式且有图片时显示） -->
      <view 
        v-if="scanMode === 'multiple' && imageBase64List.length > 0" 
        class="upload-btn"
        @click="handleMultipleUpload"
      >
        <text class="upload-text">上传</text>
      </view>
      
      <!-- PDF缩略图预览（右下角） -->
      <view v-if="showPdfThumbnail" class="pdf-thumbnail" @click="handleOpenPdf">
        <view class="pdf-close" @click.stop="handleClosePdf">
          <text class="close-icon">×</text>
        </view>
        <image class="pdf-icon" src="/static/icon/pdf.svg" mode="aspectFit" />
        <text class="pdf-text">PDF</text>
      </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'
import { scanUpload } from '@/apis/scan'

const { t } = useI18n()

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

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

// 图片base64数组（用于多页模式）
const imageBase64List = ref([])

// 图片临时路径数组（用于显示缩略图）
const imageTempPaths = ref([])

// PDF数据数组（多页模式，包含路径和base64）
const pdfDataList = ref([])

// 缓存的ossId
const cachedOssId = ref(null)

// PDF文件路径（用于预览）
const pdfFilePath = ref('')

// 是否显示PDF缩略图
const showPdfThumbnail = ref(false)

// 相机上下文
let cameraContext = null

onMounted(() => {
  // 获取系统信息
  const windowInfo = uni.getWindowInfo()
  statusBarHeight.value = windowInfo.statusBarHeight || 0
  
  // 初始化相机上下文
  cameraContext = uni.createCameraContext()
})

onUnmounted(() => {
  // 清理资源
})

// 返回上一页
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 handleCapture = () => {
  if (!cameraContext) return
  
  cameraContext.takePhoto({
    quality: 'high',
    success: async (res) => {
      try {
        uni.showLoading({
          title: '处理中...',
          mask: true
        })
        
        // 将图片转换为base64
        const base64Data = await imageToBase64(res.tempImagePath)
        
        if (scanMode.value === 'single') {
          // 单页模式：直接上传
          await uploadSingleImage(base64Data)
        } else {
          // 多页模式：立即上传并扫描
          await uploadAndScanImage(base64Data)
        }
      } catch (error) {
        uni.hideLoading()
        console.error('处理图片失败:', error)
        uni.showToast({
          title: '处理失败',
          icon: 'none'
        })
      }
    },
    fail: (err) => {
      console.error('拍照失败:', err)
      uni.showToast({
        title: '拍照失败',
        icon: 'none'
      })
    }
  })
}

// 导入图片
const handleSelectImage = async () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album'],
    success: async (res) => {
      try {
        uni.showLoading({
          title: '处理中...',
          mask: true
        })
        
        // 将图片转换为base64
        const base64Data = await imageToBase64(res.tempFilePaths[0])
        
        if (scanMode.value === 'single') {
          // 单页模式：直接上传
          await uploadSingleImage(base64Data)
        } else {
          // 多页模式：立即上传并扫描
          await uploadAndScanImage(base64Data)
        }
      } catch (error) {
        uni.hideLoading()
        console.error('处理图片失败:', error)
        uni.showToast({
          title: '处理失败',
          icon: 'none'
        })
      }
    }
  })
}

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

// 将图片转换为base64
const imageToBase64 = (filePath) => {
  return new Promise((resolve, reject) => {
    uni.getFileSystemManager().readFile({
      filePath: filePath,
      encoding: 'base64',
      success: (res) => {
        resolve(res.data)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 单页模式上传
const uploadSingleImage = async (base64Data) => {
  try {
    // 调用上传接口（单个文件）
    const response = await scanUpload({
      file: base64Data
    })
    
    uni.hideLoading()
    
    if (response.code === 200 && response.data) {
      // 缓存ossId
      cachedOssId.value = response.data.ossId
      
      // 处理PDF预览
      if (response.data.fileBase64) {
        await handlePdfPreview(response.data.fileBase64)
      } else {
        uni.showToast({
          title: '上传成功',
          icon: 'success',
          duration: 2000
        })
      }
    } else {
      throw new Error(response.msg || '上传失败')
    }
  } catch (error) {
    uni.hideLoading()
    console.error('上传失败:', error)
    uni.showToast({
      title: error.message || '上传失败',
      icon: 'none'
    })
  }
}

// 多页模式批量上传
const handleMultipleUpload = async () => {
  if (imageBase64List.value.length === 0) {
    uni.showToast({
      title: '请先添加图片',
      icon: 'none'
    })
    return
  }
  
  try {
    uni.showLoading({
      title: '上传中...',
      mask: true
    })
    
    // 调用上传接口
    const response = await scanUpload({
      files: imageBase64List.value
    })
    
    uni.hideLoading()
    
    if (response.code === 200 && response.data) {
      // 缓存ossId
      cachedOssId.value = response.data.ossId
      
      // 清空数组
      imageBase64List.value = []
      imageTempPaths.value = []
      
      // 处理PDF预览
      if (response.data.fileBase64) {
        await handlePdfPreview(response.data.fileBase64)
      } else {
        uni.showToast({
          title: '上传成功',
          icon: 'success',
          duration: 2000
        })
      }
    } else {
      throw new Error(response.msg || '上传失败')
    }
  } catch (error) {
    uni.hideLoading()
    console.error('上传失败:', error)
    uni.showToast({
      title: error.message || '上传失败',
      icon: 'none'
    })
  }
}

// 多页模式：上传并扫描单张图片
const uploadAndScanImage = async (base64Data) => {
  try {
    // 调用上传接口（单个文件）
    const response = await scanUpload({
      file: base64Data
    })
    
    uni.hideLoading()
    
    if (response.code === 200 && response.data && response.data.fileBase64) {
      // 将PDF转换为临时文件
      const pdfPath = await base64ToTempFile(response.data.fileBase64)
      
      // 添加到PDF数据列表（包含路径和base64）
      pdfDataList.value.push({
        path: pdfPath,
        base64: response.data.fileBase64
      })
      
      uni.showToast({
        title: `已扫描第${pdfDataList.value.length}页`,
        icon: 'success',
        duration: 1500
      })
    } else {
      throw new Error(response.msg || '扫描失败')
    }
  } catch (error) {
    uni.hideLoading()
    console.error('扫描失败:', error)
    uni.showToast({
      title: error.message || '扫描失败',
      icon: 'none'
    })
  }
}

// 删除指定图片
const handleDeleteImage = (index) => {
  imageBase64List.value.splice(index, 1)
  imageTempPaths.value.splice(index, 1)
  
  uni.showToast({
    title: '已删除',
    icon: 'success',
    duration: 1000
  })
}

// 删除指定PDF
const handleDeletePdf = (index) => {
  pdfDataList.value.splice(index, 1)
  
  uni.showToast({
    title: '已删除',
    icon: 'success',
    duration: 1000
  })
}

// 查看所有PDF
const handleViewAllPdf = () => {
  if (pdfDataList.value.length === 0) {
    uni.showToast({
      title: '暂无PDF',
      icon: 'none'
    })
    return
  }
  
  // 使用全局数据存储PDF数据（包含路径和base64）
  getApp().globalData.pdfData = pdfDataList.value
  
  uni.navigateTo({
    url: '/pages/scan/pdfViewer/index'
  })
}

// 处理PDF预览
const handlePdfPreview = async (base64Data) => {
  try {
    // 将base64转换为临时文件
    const filePath = await base64ToTempFile(base64Data)
    pdfFilePath.value = filePath
    showPdfThumbnail.value = true
    
    uni.showToast({
      title: '上传成功',
      icon: 'success',
      duration: 2000
    })
  } catch (error) {
    console.error('处理PDF失败:', error)
    uni.showToast({
      title: '处理PDF失败',
      icon: 'none'
    })
  }
}

// 将base64转换为临时文件
const base64ToTempFile = (base64Data) => {
  return new Promise((resolve, reject) => {
    const fs = uni.getFileSystemManager()
    const fileName = `scan_${Date.now()}.pdf`
    const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`
    
    fs.writeFile({
      filePath: filePath,
      data: base64Data,
      encoding: 'base64',
      success: () => {
        resolve(filePath)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 打开PDF预览
const handleOpenPdf = () => {
  if (!pdfFilePath.value) return
  
  uni.openDocument({
    filePath: pdfFilePath.value,
    fileType: 'pdf',
    showMenu: true,
    success: () => {
      // 预览成功
    },
    fail: (err) => {
      console.error('打开文档失败:', err)
      uni.showToast({
        title: '打开文档失败',
        icon: 'none'
      })
    }
  })
}

// 关闭PDF缩略图
const handleClosePdf = () => {
  showPdfThumbnail.value = false
  pdfFilePath.value = ''
}
</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;
    }
    
    // 模式切换按钮 - 在底部操作栏上方
    .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);
          }
        }
      }
    }
    
    // 多页模式缩略图列表
    .thumbnail-list {
      position: absolute;
      bottom: 220rpx;
      left: 0;
      right: 0;
      height: 160rpx;
      background: rgba(0, 0, 0, 0.6);
      backdrop-filter: blur(10rpx);
      
      .thumbnail-scroll {
        height: 100%;
        white-space: nowrap;
        
        .thumbnail-wrapper {
          display: inline-flex;
          padding: 20rpx;
          gap: 16rpx;
          
          .thumbnail-item {
            position: relative;
            width: 120rpx;
            height: 120rpx;
            border-radius: 12rpx;
            overflow: hidden;
            background: #ffffff;
            border: 2rpx solid #e0e0e0;
            
            .thumbnail-image {
              width: 100%;
              height: 100%;
            }
            
            .pdf-thumbnail-icon {
              width: 100%;
              height: 100%;
              display: flex;
              align-items: center;
              justify-content: center;
              background: #f5f5f5;
              
              .pdf-icon-img {
                width: 60rpx;
                height: 60rpx;
              }
            }
            
            .thumbnail-delete {
              position: absolute;
              top: 4rpx;
              right: 4rpx;
              width: 36rpx;
              height: 36rpx;
              border-radius: 50%;
              background: rgba(0, 0, 0, 0.7);
              display: flex;
              align-items: center;
              justify-content: center;
              
              .delete-icon {
                font-size: 32rpx;
                color: #ffffff;
                line-height: 1;
              }
            }
            
            .thumbnail-index {
              position: absolute;
              bottom: 4rpx;
              left: 4rpx;
              padding: 2rpx 8rpx;
              background: rgba(0, 0, 0, 0.7);
              border-radius: 8rpx;
              font-size: 20rpx;
              color: #ffffff;
            }
          }
        }
      }
    }
    
    // 上传按钮
    .upload-btn {
      position: absolute;
      bottom: 240rpx;
      right: 32rpx;
      width: 120rpx;
      height: 80rpx;
      background: #1ec9c9;
      border-radius: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 4rpx 16rpx rgba(30, 201, 201, 0.4);
      z-index: 20;
      
      &:active {
        transform: scale(0.95);
      }
      
      .upload-text {
        font-size: 28rpx;
        font-weight: 600;
        color: #ffffff;
      }
    }
    
    // PDF缩略图
    .pdf-thumbnail {
      position: absolute;
      bottom: 240rpx;
      right: 32rpx;
      width: 140rpx;
      height: 140rpx;
      background: #ffffff;
      border-radius: 16rpx;
      box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      z-index: 20;
      
      &:active {
        transform: scale(0.95);
      }
      
      .pdf-close {
        position: absolute;
        top: -8rpx;
        right: -8rpx;
        width: 40rpx;
        height: 40rpx;
        border-radius: 50%;
        background: #ff4444;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 2rpx 8rpx rgba(255, 68, 68, 0.3);
        
        .close-icon {
          font-size: 36rpx;
          color: #ffffff;
          line-height: 1;
          font-weight: 300;
        }
      }
      
      .pdf-icon {
        width: 60rpx;
        height: 60rpx;
        margin-bottom: 8rpx;
      }
      
      .pdf-text {
        font-size: 24rpx;
        color: #666666;
        font-weight: 500;
      }
    }
    
    // 底部操作按钮
    .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>
