<template>
  <view class="pdf-viewer-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">PDF管理 (共{{ pdfList.length }}页)</text>
        <view class="placeholder"></view>
      </view>
    </view>
    
    <!-- PDF列表 -->
    <scroll-view scroll-y class="pdf-list">
      <view 
        v-for="(item, index) in pdfList" 
        :key="item.id" 
        class="pdf-item"
      >
        <view class="pdf-icon-wrapper">
          <image src="/static/icon/pdf.svg" mode="aspectFit" class="pdf-icon" />
        </view>
        <view class="pdf-info" @click="handlePreviewPdf(item.path, index)" @longpress="handleEditName(index)">
          <text class="pdf-name">{{ item.name || `文档_${index + 1}` }}</text>
          <text class="pdf-tip">点击预览 · 长按编辑名称</text>
        </view>
        
        <!-- 操作按钮 -->
        <view class="pdf-actions">
          <view 
            v-if="index > 0" 
            class="action-icon" 
            @click="handleMoveUp(index)"
          >
            <text class="icon-text">↑</text>
          </view>
          <view 
            v-if="index < pdfList.length - 1" 
            class="action-icon" 
            @click="handleMoveDown(index)"
          >
            <text class="icon-text">↓</text>
          </view>
          <view class="action-icon delete" @click="handleDelete(index)">
            <text class="icon-text">×</text>
          </view>
        </view>
      </view>
      
      <view v-if="pdfList.length === 0" class="empty-tip">
        <text class="empty-text">暂无PDF文档</text>
      </view>
    </scroll-view>
    
    <!-- 底部提交按钮 -->
    <view class="submit-footer">
      <view class="submit-btn" @click="handleSubmit">
        <text class="submit-text">提交</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { scanUploadBatch } from '@/apis/scan'

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

// PDF列表（包含路径和base64）
const pdfList = ref([])

// 生成唯一ID
let idCounter = 0
const generateId = () => {
  return `pdf_${Date.now()}_${idCounter++}`
}

onMounted(() => {
  // 获取系统信息
  const windowInfo = uni.getWindowInfo()
  statusBarHeight.value = windowInfo.statusBarHeight || 0
  
  // 从全局数据获取PDF路径和base64
  const app = getApp()
  if (app.globalData && app.globalData.pdfData) {
    pdfList.value = app.globalData.pdfData.map(item => ({
      id: generateId(),
      path: item.path,
      base64: item.base64,
      name: item.name || `文档_${Date.now()}`
    }))
  }
})

// 返回上一页
const handleBack = () => {
  uni.navigateBack()
}

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

// 上移
const handleMoveUp = (index) => {
  if (index === 0) return
  
  const temp = pdfList.value[index]
  pdfList.value[index] = pdfList.value[index - 1]
  pdfList.value[index - 1] = temp
  
  // 触发响应式更新
  pdfList.value = [...pdfList.value]
  
  uni.showToast({
    title: '已上移',
    icon: 'success',
    duration: 1000
  })
}

// 下移
const handleMoveDown = (index) => {
  if (index === pdfList.value.length - 1) return
  
  const temp = pdfList.value[index]
  pdfList.value[index] = pdfList.value[index + 1]
  pdfList.value[index + 1] = temp
  
  // 触发响应式更新
  pdfList.value = [...pdfList.value]
  
  uni.showToast({
    title: '已下移',
    icon: 'success',
    duration: 1000
  })
}

// 删除
const handleDelete = (index) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除"${pdfList.value[index].name || `文档_${index + 1}`}"吗？`,
    confirmText: '删除',
    cancelText: '取消',
    success: (res) => {
      if (res.confirm) {
        pdfList.value.splice(index, 1)
        
        uni.showToast({
          title: '已删除',
          icon: 'success',
          duration: 1000
        })
      }
    }
  })
}

// 编辑文件名
const handleEditName = (index) => {
  const currentName = pdfList.value[index].name || `文档_${index + 1}`
  
  uni.showModal({
    title: '编辑文件名',
    content: currentName,
    editable: true,
    placeholderText: '请输入文件名',
    success: (res) => {
      if (res.confirm && res.content && res.content.trim()) {
        pdfList.value[index].name = res.content.trim()
        
        uni.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 1000
        })
      }
    }
  })
}

// 提交 - 跳转到文件选择页面
const handleSubmit = () => {
  if (pdfList.value.length === 0) {
    uni.showToast({
      title: '请先添加PDF',
      icon: 'none'
    })
    return
  }
  
  // 按顺序提取base64数组
  const base64Array = pdfList.value.map(item => item.base64)
  
  // 将base64数组存储到全局数据中
  getApp().globalData.scannedFileBase64List = base64Array
  
  // 跳转到文件选择页面
  uni.navigateTo({
    url: '/pages/scan/fileSelect/index'
  })
}

// 上传所有PDF
const handleUploadAll = async () => {
  if (pdfList.value.length === 0) {
    uni.showToast({
      title: '请先添加PDF',
      icon: 'none'
    })
    return
  }
  
  uni.showModal({
    title: '确认上传',
    content: `将按当前顺序上传${pdfList.value.length}个PDF文档`,
    confirmText: '上传',
    cancelText: '取消',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: '上传中...',
            mask: true
          })
          
          // 按顺序提取base64数组
          const base64Array = pdfList.value.map(item => item.base64)
          
          // 调用批量上传接口
          const response = await scanUploadBatch({
            files: base64Array
          })
          
          uni.hideLoading()
          
          if (response.code === 200 && response.data) {
            uni.showToast({
              title: '上传成功',
              icon: 'success',
              duration: 2000
            })
            
            // 延迟返回上一页
            setTimeout(() => {
              uni.navigateBack()
            }, 2000)
          } else {
            throw new Error(response.msg || '上传失败')
          }
        } catch (error) {
          uni.hideLoading()
          console.error('上传失败:', error)
          uni.showToast({
            title: error.message || '上传失败',
            icon: 'none'
          })
        }
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.pdf-viewer-page {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  
  // 顶部导航栏
  .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;
      }
    }
  }
  
  // PDF列表
  .pdf-list {
    flex: 1;
    padding: 24rpx;
    
    .pdf-item {
      background: #ffffff;
      border-radius: 16rpx;
      padding: 24rpx;
      margin-bottom: 16rpx;
      display: flex;
      align-items: center;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
      
      &:active {
        background: #f8f8f8;
      }
      
      .pdf-icon-wrapper {
        width: 80rpx;
        height: 80rpx;
        background: #f5f5f5;
        border-radius: 12rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 24rpx;
        
        .pdf-icon {
          width: 48rpx;
          height: 48rpx;
        }
      }
      
      .pdf-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 8rpx;
        
        .pdf-name {
          font-size: 32rpx;
          font-weight: 600;
          color: #333333;
        }
        
        .pdf-tip {
          font-size: 24rpx;
          color: #999999;
        }
      }
      
      .pdf-actions {
        display: flex;
        align-items: center;
        gap: 12rpx;
        
        .action-icon {
          width: 56rpx;
          height: 56rpx;
          border-radius: 50%;
          background: #f5f5f5;
          display: flex;
          align-items: center;
          justify-content: center;
          
          &:active {
            background: #e0e0e0;
          }
          
          &.delete {
            background: #ffe5e5;
            
            &:active {
              background: #ffcccc;
            }
            
            .icon-text {
              color: #ff4444;
              font-size: 40rpx;
            }
          }
          
          .icon-text {
            font-size: 32rpx;
            color: #666666;
            font-weight: 600;
            line-height: 1;
          }
        }
      }
      
      .arrow-icon {
        font-size: 48rpx;
        color: #cccccc;
        font-weight: 300;
      }
    }
    
    .empty-tip {
      padding: 200rpx 0;
      text-align: center;
      
      .empty-text {
        font-size: 28rpx;
        color: #999999;
      }
    }
  }
  
  // 底部提交按钮
  .submit-footer {
    background: #ffffff;
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
    
    .submit-btn {
      width: 100%;
      height: 88rpx;
      background: linear-gradient(135deg, #1ec9c9 0%, #1eb8b8 100%);
      border-radius: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 4rpx 16rpx rgba(30, 201, 201, 0.3);
      
      &:active {
        transform: scale(0.98);
        opacity: 0.9;
      }
      
      .submit-text {
        font-size: 32rpx;
        font-weight: 600;
        color: #ffffff;
      }
    }
  }
}
</style>
