<template>
  <view class="upload-edit-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>
    
    <!-- 页面内容 -->
    <scroll-view scroll-y class="page-content">
      <!-- 文件夹信息卡片 -->
      <view class="info-card">
        <view class="info-row">
          <text class="info-label">文件夹路径：</text>
          <text class="info-value">{{ folderPath }}</text>
        </view>
      </view>
      
      <!-- 文件列表 -->
      <view class="file-list-section">
        <view class="section-title">文件列表 ({{ fileList.length }})</view>
        <view class="file-list">
          <view 
            v-for="(file, index) in fileList" 
            :key="index"
            class="file-item"
          >
            <view class="file-main" @click="handlePreview(file, index)">
              <view class="file-icon-wrapper">
                <image src="/static/icon/pdf.svg" mode="aspectFit" class="file-icon" />
              </view>
              <view class="file-info">
                <text class="file-name">{{ file.name }}</text>
                <text class="file-tip">点击预览</text>
              </view>
            </view>
            
            <!-- 操作按钮 -->
            <view class="file-actions">
              <view 
                v-if="index > 0" 
                class="action-icon" 
                @click="handleMoveUp(index)"
              >
                <text class="icon-text">↑</text>
              </view>
              <view 
                v-if="index < fileList.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>
      </view>
    </scroll-view>
    
    <!-- 底部操作按钮 -->
    <view class="footer-actions">
      <view class="action-btn secondary" @click="handleCancel">
        <text class="action-text">取消</text>
      </view>
      <view class="action-btn primary" @click="handleUpload">
        <text class="action-text">上传</text>
      </view>
    </view>
    
    <!-- 上传弹出框 -->
    <view v-if="showUploadDialog" class="dialog-overlay" @click="closeDialog">
      <view class="dialog-content" @click.stop>
        <view class="dialog-header">
          <text class="dialog-title">上传文件</text>
          <view class="dialog-close" @click="closeDialog">
            <text class="close-icon">×</text>
          </view>
        </view>
        
        <view class="dialog-body">
          <view class="form-item">
            <text class="form-label">文件名</text>
            <input 
              class="form-input" 
              v-model="uploadForm.fileName" 
              placeholder="请输入文件名"
              maxlength="100"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">备注</text>
            <textarea 
              class="form-textarea" 
              v-model="uploadForm.note" 
              placeholder="请输入备注（可选）"
              maxlength="500"
              :auto-height="true"
            />
          </view>
        </view>
        
        <view class="dialog-footer">
          <view class="dialog-btn cancel" @click="closeDialog">
            <text class="btn-text">取消</text>
          </view>
          <view class="dialog-btn confirm" @click="confirmUpload">
            <text class="btn-text">确认</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { uploadNew } from '@/apis/scan.js'

export default {
  data() {
    return {
      statusBarHeight: 0,
      folderId: 0,
      projectId: 0,
      folderPath: '',
      fileList: [], // 文件列表，每个元素包含 { base64, name, path }
      showUploadDialog: false,
      uploadForm: {
        fileName: '',
        note: ''
      }
    }
  },
  onLoad(options) {
    console.log('========== 编辑上传文件页面 ==========')
    console.log('页面参数:', options)
    
    this.folderId = parseInt(options.folderId) || 0
    this.projectId = parseInt(options.projectId) || 0
    this.folderPath = decodeURIComponent(options.folderPath || '')
    
    console.log('文件夹ID:', this.folderId)
    console.log('项目ID:', this.projectId)
    console.log('文件夹路径:', this.folderPath)
  },
  onReady() {
    // 获取系统信息
    const windowInfo = uni.getWindowInfo()
    this.statusBarHeight = windowInfo.statusBarHeight || 0
    
    // 从全局数据获取文件列表
    const fileBase64List = getApp().globalData.scannedFileBase64List
    const pdfData = getApp().globalData.pdfData
    
    console.log('fileBase64List:', fileBase64List)
    console.log('pdfData:', pdfData)
    
    if (fileBase64List && fileBase64List.length > 0) {
      // 如果有 pdfData（包含文件名和路径），使用它
      if (pdfData && pdfData.length > 0) {
        this.fileList = pdfData.map((item, index) => ({
          base64: item.base64 || fileBase64List[index],
          name: item.name || `文件_${index + 1}`,
          path: item.path
        }))
      } else {
        // 否则只有 base64 数据
        this.fileList = fileBase64List.map((base64, index) => ({
          base64: base64,
          name: `文件_${index + 1}`,
          path: null
        }))
      }
      console.log('文件列表:', this.fileList)
    } else {
      console.error('未找到文件列表')
      uni.showToast({
        title: '未找到文件',
        icon: 'none'
      })
    }
  },
  methods: {
    // 返回上一页
    handleBack() {
      uni.navigateBack()
    },
    
    // 取消
    handleCancel() {
      uni.showModal({
        title: '提示',
        content: '确定要取消上传吗？',
        confirmText: '确定',
        cancelText: '继续编辑',
        success: (res) => {
          if (res.confirm) {
            // 清除全局数据
            getApp().globalData.scannedFileBase64List = null
            getApp().globalData.selectedFolder = null
            
            // 返回首页
            uni.reLaunch({
              url: '/pages/home/index'
            })
          }
        }
      })
    },
    
    // 上传
    handleUpload() {
      if (this.fileList.length === 0) {
        uni.showToast({
          title: '没有可上传的文件',
          icon: 'none'
        })
        return
      }
      
      // 显示上传弹出框
      this.showUploadDialog = true
    },
    
    // 关闭弹出框
    closeDialog() {
      this.showUploadDialog = false
      this.uploadForm = {
        fileName: '',
        note: ''
      }
    },
    
    // 确认上传
    async confirmUpload() {
      // 验证文件名
      if (!this.uploadForm.fileName.trim()) {
        uni.showToast({
          title: '请输入文件名',
          icon: 'none'
        })
        return
      }
      
      console.log('========== 开始上传 ==========')
      console.log('文件夹ID:', this.folderId)
      console.log('项目ID:', this.projectId)
      console.log('文件名:', this.uploadForm.fileName)
      console.log('备注:', this.uploadForm.note)
      console.log('文件数量:', this.fileList.length)
      
      // 准备上传数据（在关闭弹出框之前）
      const uploadData = {
        folderId: this.folderId,
        fileName: this.uploadForm.fileName.trim(),
        projectId: this.projectId,
        note: this.uploadForm.note.trim(),
        files: this.fileList.map(item => item.base64)
      }
      
      // 关闭弹出框
      this.closeDialog()
      
      // 显示加载提示
      uni.showLoading({
        title: '上传中...',
        mask: true
      })
      
      try {
        // 调用上传接口
        await uploadNew(uploadData)
        
        uni.hideLoading()
        
        uni.showToast({
          title: '上传成功',
          icon: 'success',
          duration: 2000
        })
        
        // 清除全局数据
        getApp().globalData.scannedFileBase64List = null
        getApp().globalData.selectedFolder = null
        getApp().globalData.pdfData = null
        
        // 返回首页
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/home/index'
          })
        }, 2000)
      } catch (error) {
        console.error('上传失败:', error)
        uni.hideLoading()
        
        uni.showToast({
          title: error.msg || '上传失败',
          icon: 'none',
          duration: 2000
        })
      }
    },
    
    // 预览文件
    async handlePreview(file, index) {
      console.log('预览文件:', file.name)
      console.log('文件索引:', index)
      
      if (!file.base64) {
        uni.showToast({
          title: '文件数据异常',
          icon: 'none'
        })
        return
      }
      
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
      
      try {
        // 将 base64 转换为临时文件
        const fs = uni.getFileSystemManager()
        const fileName = `${Date.now()}_${file.name}.pdf`
        const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`
        
        // 将 base64 写入文件
        fs.writeFileSync(
          filePath,
          file.base64,
          'base64'
        )
        
        console.log('临时文件路径:', filePath)
        
        uni.hideLoading()
        
        // 使用 uni.openDocument 打开文件
        uni.openDocument({
          filePath: filePath,
          fileType: 'pdf',
          showMenu: true,
          success: () => {
            console.log('文档打开成功')
          },
          fail: (err) => {
            console.error('文档打开失败:', err)
            uni.showToast({
              title: '文档打开失败',
              icon: 'none'
            })
          }
        })
      } catch (error) {
        uni.hideLoading()
        console.error('预览失败:', error)
        uni.showToast({
          title: '预览失败',
          icon: 'none'
        })
      }
    },
    
    // 上移文件
    handleMoveUp(index) {
      if (index === 0) return
      
      const temp = this.fileList[index]
      this.fileList[index] = this.fileList[index - 1]
      this.fileList[index - 1] = temp
      
      // 触发响应式更新
      this.fileList = [...this.fileList]
      
      uni.showToast({
        title: '已上移',
        icon: 'success',
        duration: 1000
      })
    },
    
    // 下移文件
    handleMoveDown(index) {
      if (index === this.fileList.length - 1) return
      
      const temp = this.fileList[index]
      this.fileList[index] = this.fileList[index + 1]
      this.fileList[index + 1] = temp
      
      // 触发响应式更新
      this.fileList = [...this.fileList]
      
      uni.showToast({
        title: '已下移',
        icon: 'success',
        duration: 1000
      })
    },
    
    // 删除文件
    handleDelete(index) {
      // 不允许删除最后一个文件
      if (this.fileList.length <= 1) {
        uni.showToast({
          title: '至少保留一个文件',
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      uni.showModal({
        title: '确认删除',
        content: `确定要删除"${this.fileList[index].name}"吗？`,
        confirmText: '删除',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.fileList.splice(index, 1)
            
            uni.showToast({
              title: '已删除',
              icon: 'success',
              duration: 1000
            })
          }
        }
      })
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (!bytes) return '0 B'
      
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      
      return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-edit-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;
      }
    }
  }
  
  // 页面内容
  .page-content {
    flex: 1;
    padding: 24rpx;
    
    // 信息卡片
    .info-card {
      background: #ffffff;
      border-radius: 16rpx;
      padding: 32rpx 24rpx;
      margin-bottom: 24rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
      
      .info-row {
        display: flex;
        align-items: flex-start;
        margin-bottom: 20rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .info-label {
          font-size: 28rpx;
          color: #666666;
          min-width: 180rpx;
        }
        
        .info-value {
          flex: 1;
          font-size: 28rpx;
          color: #333333;
          font-weight: 500;
          word-break: break-all;
        }
      }
    }
    
    // 文件列表区域
    .file-list-section {
      .section-title {
        font-size: 30rpx;
        font-weight: 600;
        color: #333333;
        margin-bottom: 16rpx;
      }
      
      .file-list {
        background: #ffffff;
        border-radius: 16rpx;
        overflow: hidden;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
        
        .file-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 24rpx;
          border-bottom: 1rpx solid #f5f5f5;
          
          &:last-child {
            border-bottom: none;
          }
          
          .file-main {
            flex: 1;
            display: flex;
            align-items: center;
            
            &:active {
              opacity: 0.7;
            }
            
            .file-icon-wrapper {
              width: 64rpx;
              height: 64rpx;
              background: #f5f5f5;
              border-radius: 12rpx;
              display: flex;
              align-items: center;
              justify-content: center;
              margin-right: 16rpx;
              
              .file-icon {
                width: 40rpx;
                height: 40rpx;
              }
            }
            
            .file-info {
              flex: 1;
              display: flex;
              flex-direction: column;
              gap: 8rpx;
              
              .file-name {
                font-size: 28rpx;
                color: #333333;
                font-weight: 500;
              }
              
              .file-tip {
                font-size: 24rpx;
                color: #999999;
              }
            }
          }
          
          .file-actions {
            display: flex;
            align-items: center;
            gap: 12rpx;
            margin-left: 16rpx;
            
            .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;
              }
            }
          }
        }
      }
    }
  }
  
  // 底部操作按钮
  .footer-actions {
    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);
    display: flex;
    gap: 16rpx;
    
    .action-btn {
      flex: 1;
      height: 88rpx;
      border-radius: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      &:active {
        transform: scale(0.98);
        opacity: 0.9;
      }
      
      &.secondary {
        background: #ffffff;
        border: 2rpx solid #1ec9c9;
        
        .action-text {
          color: #1ec9c9;
        }
      }
      
      &.primary {
        background: linear-gradient(135deg, #1ec9c9 0%, #1eb8b8 100%);
        box-shadow: 0 4rpx 16rpx rgba(30, 201, 201, 0.3);
        
        .action-text {
          color: #ffffff;
        }
      }
      
      .action-text {
        font-size: 32rpx;
        font-weight: 600;
      }
    }
  }
  
  // 弹出框遮罩
  .dialog-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    
    .dialog-content {
      width: 600rpx;
      background: #ffffff;
      border-radius: 24rpx;
      overflow: hidden;
      
      .dialog-header {
        padding: 32rpx 32rpx 24rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1rpx solid #f5f5f5;
        
        .dialog-title {
          font-size: 32rpx;
          font-weight: 600;
          color: #333333;
        }
        
        .dialog-close {
          width: 48rpx;
          height: 48rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          
          &:active {
            opacity: 0.7;
          }
          
          .close-icon {
            font-size: 48rpx;
            color: #999999;
            line-height: 1;
          }
        }
      }
      
      .dialog-body {
        padding: 32rpx;
        
        .form-item {
          margin-bottom: 32rpx;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .form-label {
            display: block;
            font-size: 28rpx;
            color: #333333;
            margin-bottom: 16rpx;
            font-weight: 500;
          }
          
          .form-input {
            width: 100%;
            height: 80rpx;
            padding: 0 24rpx;
            background: #f5f5f5;
            border-radius: 12rpx;
            font-size: 28rpx;
            color: #333333;
            box-sizing: border-box;
          }
          
          .form-textarea {
            width: 100%;
            min-height: 120rpx;
            padding: 16rpx 24rpx;
            background: #f5f5f5;
            border-radius: 12rpx;
            font-size: 28rpx;
            color: #333333;
            box-sizing: border-box;
          }
        }
      }
      
      .dialog-footer {
        padding: 24rpx 32rpx 32rpx;
        display: flex;
        gap: 16rpx;
        
        .dialog-btn {
          flex: 1;
          height: 80rpx;
          border-radius: 40rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          
          &:active {
            transform: scale(0.98);
            opacity: 0.9;
          }
          
          &.cancel {
            background: #f5f5f5;
            
            .btn-text {
              color: #666666;
            }
          }
          
          &.confirm {
            background: linear-gradient(135deg, #1ec9c9 0%, #1eb8b8 100%);
            
            .btn-text {
              color: #ffffff;
            }
          }
          
          .btn-text {
            font-size: 30rpx;
            font-weight: 600;
          }
        }
      }
    }
  }
}
</style>
