<template>
  <view class="file-select-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="search-bar">
      <input 
        class="search-input" 
        v-model="searchName" 
        placeholder="搜索文件名"
        @confirm="handleSearch"
      />
      <view class="search-btn" @click="handleSearch">
        <text class="search-text">搜索</text>
      </view>
    </view>
    
    <!-- 文件列表 -->
    <scroll-view 
      scroll-y 
      class="file-list"
      @scrolltolower="handleLoadMore"
    >
      <view 
        v-for="item in fileList" 
        :key="item.id" 
        class="file-item"
        @click="handleSelectFile(item)"
      >
        <view class="file-icon-wrapper">
          <image src="/static/icon/document.svg" mode="aspectFit" class="file-icon" />
        </view>
        <view class="file-info">
          <text class="file-name">{{ item.name }}</text>
          <text class="file-detail">项目: {{ item.project }}</text>
          <text class="file-detail">文件夹: {{ item.folder }}</text>
          <text class="file-detail">创建人: {{ item.createBy }}</text>
          <text class="file-detail">截止日期: {{ formatDate(item.deadline) }}</text>
        </view>

      </view>
      
      <view v-if="fileList.length === 0 && !loading" class="empty-tip">
        <text class="empty-text">暂无待递交文件</text>
        <text class="empty-hint">您可以直接上传文件</text>
      </view>
      
      <view v-if="loading" class="loading-tip">
        <text class="loading-text">加载中...</text>
      </view>
    </scroll-view>
    
    <!-- 底部提交按钮 -->
    <view class="submit-footer">
      <view
        class="submit-btn secondary" 
        @click="handleDirectUpload"
      >
        <text class="submit-text">直接上传</text>
      </view>
      <!-- <view 
        class="submit-btn" 
        :class="{ 'full-width': fileList.length === 0 }"
        @click="fileList.length > 0 ? handleSubmitAll() : handleDirectUpload()"
      >
        <text class="submit-text">{{ fileList.length > 0 ? '提交' : '直接上传' }}</text>
      </view> -->
    </view>
  </view>
</template>

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

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

// 文件列表
const fileList = ref([])
const searchName = ref('')
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

onMounted(() => {
  // 获取系统信息
  const windowInfo = uni.getWindowInfo()
  statusBarHeight.value = windowInfo.statusBarHeight || 0
  
  // 加载文件列表
  loadFileList()
})

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

// 加载文件列表
const loadFileList = async () => {
  if (loading.value) return
  
  try {
    loading.value = true
    
    const response = await getToSubmitList({
      name: searchName.value,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    })
    
    if (response.code === 200) {
      if (pageNum.value === 1) {
        fileList.value = response.rows || []
      } else {
        fileList.value = [...fileList.value, ...(response.rows || [])]
      }
      total.value = response.total || 0
    }
  } catch (error) {
    console.error('加载文件列表失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pageNum.value = 1
  fileList.value = []
  loadFileList()
}

// 加载更多
const handleLoadMore = () => {
  if (loading.value) return
  if (fileList.value.length >= total.value) return
  
  pageNum.value++
  loadFileList()
}

// 选择文件
const handleSelectFile = async (file) => {
  try {
    // 从全局数据中获取扫描的fileBase64List
    const fileBase64List = getApp().globalData.scannedFileBase64List
    
    if (!fileBase64List || fileBase64List.length === 0) {
      uni.showToast({
        title: '未找到扫描文件',
        icon: 'none'
      })
      return
    }
    
    uni.showLoading({
      title: '提交中...',
      mask: true
    })
    
    // 调用上传接口
    const response = await uploadOnSubmit({
      documentId: file.id,
      fileBase64List: fileBase64List
    })
    
    uni.hideLoading()
    
    if (response.code === 200) {
      // 清除全局数据
      getApp().globalData.scannedFileBase64List = null
      
      uni.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 2000
      })
      
      // 返回首页
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/home/index'
        })
      }, 2000)
    } else {
      throw new Error(response.msg || '提交失败')
    }
  } catch (error) {
    uni.hideLoading()
    console.error('提交失败:', error)
    uni.showToast({
      title: error.message || '提交失败',
      icon: 'none'
    })
  }
}

// 底部提交按钮（与点击文件相同的逻辑，但需要先选择文件）
const handleSubmitAll = () => {
  if (fileList.value.length === 0) {
    uni.showToast({
      title: '暂无可选文件',
      icon: 'none'
    })
    return
  }
  
  uni.showToast({
    title: '请点击选择对应的文件',
    icon: 'none'
  })
}

// 直接上传 - 跳转到项目选择页面
const handleDirectUpload = () => {
  // 从全局数据中获取扫描的fileBase64List
  const fileBase64List = getApp().globalData.scannedFileBase64List
  
  if (!fileBase64List || fileBase64List.length === 0) {
    uni.showToast({
      title: '未找到扫描文件',
      icon: 'none'
    })
    return
  }
  
  // 跳转到项目选择页面
  uni.navigateTo({
    url: '/pages/scan/projectSelect/index'
  })
}

// 格式化日期（只显示到天）
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  // 如果日期格式是 "2026-01-04 10:58:37"，只取前10位
  return dateStr.split(' ')[0]
}
</script>

<style lang="scss" scoped>
.file-select-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;
      }
    }
  }
  
  // 搜索框
  .search-bar {
    padding: 24rpx;
    background: #ffffff;
    display: flex;
    gap: 16rpx;
    
    .search-input {
      flex: 1;
      height: 64rpx;
      padding: 0 24rpx;
      background: #f5f5f5;
      border-radius: 32rpx;
      font-size: 28rpx;
    }
    
    .search-btn {
      width: 120rpx;
      height: 64rpx;
      background: #1ec9c9;
      border-radius: 32rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      &:active {
        background: #1ab8b8;
      }
      
      .search-text {
        font-size: 28rpx;
        color: #ffffff;
        font-weight: 500;
      }
    }
  }
  
  // 文件列表
  .file-list {
    flex: 1;
    background: #ffffff;
    
    .file-item {
      padding: 24rpx;
      display: flex;
      align-items: center;
      border-bottom: 1rpx solid #f5f5f5;
      
      &:active {
        background: #f8f8f8;
      }
      
      .file-icon-wrapper {
        width: 80rpx;
        height: 80rpx;
        background: #f5f5f5;
        border-radius: 12rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 24rpx;
        
        .file-icon {
          width: 48rpx;
          height: 48rpx;
        }
      }
      
      .file-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 6rpx;
        
        .file-name {
          font-size: 32rpx;
          font-weight: 600;
          color: #333333;
          margin-bottom: 4rpx;
        }
        
        .file-detail {
          font-size: 26rpx;
          color: #666666;
          line-height: 1.5;
        }
      }
    }
    
    .empty-tip {
      padding: 200rpx 0;
      text-align: center;
      display: flex;
      flex-direction: column;
      gap: 16rpx;
      
      .empty-text {
        font-size: 28rpx;
        color: #999999;
      }
      
      .empty-hint {
        font-size: 26rpx;
        color: #1ec9c9;
      }
    }
    
    .loading-tip {
      padding: 32rpx 0;
      text-align: center;
      
      .loading-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);
    display: flex;
    gap: 16rpx;
    
    .submit-btn {
      flex: 1;
      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;
      }
      
      &.secondary {
        background: #ffffff;
        border: 2rpx solid #1ec9c9;
        box-shadow: none;
        
        .submit-text {
          color: #1ec9c9;
        }
      }
      
      .submit-text {
        font-size: 32rpx;
        font-weight: 600;
        color: #ffffff;
      }
      
      &.full-width {
        flex: 1;
      }
    }
  }
}
</style>
