<template>
  <view class="task-documents-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">{{ pageTitle }}</text>
        <view class="placeholder"></view>
      </view>
    </view>
    
    <!-- 页面内容 -->
    <scroll-view 
      scroll-y 
      class="page-scroll"
      :style="{ paddingTop: (statusBarHeight * 2 + 88) + 'rpx' }"
      @scrolltolower="handleLoadMore"
    >
      <view class="page-content">
        <!-- 搜索和筛选区域 -->
        <view class="search-filter-row">
          <!-- 搜索框 -->
          <view class="search-box">
            <image class="search-icon" src="/static/pages/home/search.png" mode="aspectFit" />
            <input 
              class="search-input" 
              :placeholder="t('taskDocuments.searchPlaceholder')"
              placeholder-class="search-placeholder"
              v-model="searchKeyword"
              @confirm="handleSearch"
            />
            <view class="search-btn" @click="handleSearch">
              <text class="btn-text">{{ t('taskDocuments.search') }}</text>
            </view>
          </view>
          
          <!-- 状态选择器 -->
          <view class="status-selector">
            <picker 
              mode="selector" 
              :range="statusOptions" 
              range-key="label"
              :value="statusOptions.findIndex(opt => opt.value === taskStatus)"
              @change="handleStatusChange"
            >
              <view class="selector-value">
                <text class="value-text">{{ selectedStatusLabel }}</text>
                <text class="arrow-icon">▼</text>
              </view>
            </picker>
          </view>
        </view>
        
        <!-- 文档列表 -->
        <view class="document-list">
          <view 
            v-for="(doc, index) in documentList" 
            :key="doc.id"
            class="document-item"
            @click="handleDocumentClick(doc)"
          >
            <image class="doc-thumbnail" :src="getFileIcon(doc.url)" mode="aspectFit" />
            <view class="doc-info">
              <text class="doc-name">{{ doc.name }}</text>
              <view class="doc-meta">
                <text class="meta-text">{{ t('taskDocuments.createTime') }}：{{ doc.createTime }}</text>
                <text class="meta-text" v-if="doc.submitter">{{ t('taskDocuments.submitter') }}：{{ doc.submitter }}</text>
              </view>
            </view>
          </view>
          
          <!-- 加载状态 -->
          <view v-if="loading" class="loading-more">
            <text class="loading-text">{{ t('taskDocuments.loading') }}</text>
          </view>
          
          <!-- 没有更多数据 -->
          <view v-if="!hasMore && documentList.length > 0" class="no-more">
            <text class="no-more-text">{{ t('taskDocuments.noMore') }}</text>
          </view>
          
          <!-- 空状态 -->
          <view v-if="!loading && documentList.length === 0" class="empty-state">
            <text class="empty-text">{{ t('taskDocuments.empty') }}</text>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { getTaskDocuments } from '@/apis/auth'

const { t } = useI18n()

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

// 任务状态
const taskStatus = ref(null)

// 状态选项列表
const statusOptions = computed(() => [
  { label: t('taskDocuments.status.all'), value: null },
  { label: t('taskDocuments.status.unUpload'), value: 0 },
  { label: t('taskDocuments.status.unAudit'), value: 1 },
  { label: t('taskDocuments.status.auditReject'), value: 2 },
  { label: t('taskDocuments.status.unFiling'), value: 3 },
  { label: t('taskDocuments.status.filing'), value: 4 },
  { label: t('taskDocuments.status.unQualityControl'), value: 5 },
  { label: t('taskDocuments.status.qualityControlPass'), value: 6 },
  { label: t('taskDocuments.status.qualityControlReject'), value: 7 }
])

// 当前选中的状态标签
const selectedStatusLabel = computed(() => {
  const option = statusOptions.value.find(opt => opt.value === taskStatus.value)
  return option ? option.label : t('taskDocuments.status.all')
})

// 搜索关键词
const searchKeyword = ref('')

// 文档列表
const documentList = ref([])

// 分页参数
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const hasMore = ref(true)

// 页面标题
const pageTitle = computed(() => {
  if (taskStatus.value === 0) return t('taskDocuments.toSubmit')
  if (taskStatus.value === 1) return t('taskDocuments.toAudit')
  return t('taskDocuments.myTasks')
})

// 根据文件URL获取文件类型图标
const getFileIcon = (url) => {
  if (!url) return '/static/icon/document.svg'
  
  // 提取文件扩展名
  const extension = url.split('.').pop().toLowerCase()
  
  // 根据扩展名返回对应图标
  const iconMap = {
    // Word文档
    'doc': '/static/icon/word.svg',
    'docx': '/static/icon/word.svg',
    
    // Excel表格
    'xls': '/static/icon/excel.svg',
    'xlsx': '/static/icon/excel.svg',
    
    // PowerPoint演示
    'ppt': '/static/icon/ppt.svg',
    'pptx': '/static/icon/ppt.svg',
    
    // PDF文档
    'pdf': '/static/icon/pdf.svg'
  }
  
  return iconMap[extension] || '/static/icon/document.svg'
}

onMounted(() => {
  // 获取系统信息
  const windowInfo = uni.getWindowInfo()
  statusBarHeight.value = windowInfo.statusBarHeight || 0
  
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const status = currentPage.options.status
  
  if (status !== undefined && status !== '') {
    taskStatus.value = parseInt(status)
  }
  
  // 加载文档列表
  fetchDocuments()
})

// 获取文档列表
const fetchDocuments = async (isLoadMore = false) => {
  if (loading.value) return
  
  try {
    loading.value = true
    
    // 构建请求参数
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value
    }
    
    // 只有当搜索关键词不为空时才添加 name 参数
    if (searchKeyword.value && searchKeyword.value.trim()) {
      params.name = searchKeyword.value.trim()
    }
    
    // 只有当状态不为空时才添加 status 参数
    if (taskStatus.value !== null && taskStatus.value !== undefined) {
      params.status = taskStatus.value
    }
    
    const response = await getTaskDocuments(params)
    
    if (response && response.code === 200) {
      const { rows, total: totalCount } = response
      
      total.value = totalCount
      
      if (isLoadMore) {
        // 加载更多，追加数据
        documentList.value = [...documentList.value, ...rows]
      } else {
        // 首次加载或搜索，替换数据
        documentList.value = rows
      }
      
      // 判断是否还有更多数据
      hasMore.value = documentList.value.length < total.value
    }
  } catch (error) {
    console.error('获取文档列表失败:', error)
    
    if (!isLoadMore) {
      documentList.value = []
    }
    
    uni.showToast({
      title: t('taskDocuments.loadFailed'),
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 加载更多
const handleLoadMore = () => {
  if (!hasMore.value || loading.value) return
  
  pageNum.value++
  fetchDocuments(true)
}

// 搜索
const handleSearch = () => {
  // 重置分页
  pageNum.value = 1
  hasMore.value = true
  
  // 重新加载数据
  fetchDocuments()
}

// 状态选择
const handleStatusChange = (e) => {
  const index = e.detail.value
  taskStatus.value = statusOptions.value[index].value
  
  // 重置分页
  pageNum.value = 1
  hasMore.value = true
  
  // 重新加载数据
  fetchDocuments()
}

// 点击文档
const handleDocumentClick = (doc) => {
  if (!doc.url) {
    uni.showToast({
      title: t('taskDocuments.invalidUrl'),
      icon: 'none'
    })
    return
  }
  
  // 构建跳转URL，传递文档信息
  const params = []
  if (doc.name) {
    params.push(`name=${encodeURIComponent(doc.name)}`)
  }
  if (doc.url) {
    params.push(`url=${encodeURIComponent(doc.url)}`)
  }
  
  const queryString = params.join('&')
  
  uni.navigateTo({
    url: `/pages/home/documentViewer/index?${queryString}`
  })
}

// 返回
const handleBack = () => {
  uni.navigateBack({
    fail: () => {
      uni.reLaunch({
        url: '/pages/my/index'
      })
    }
  })
}
</script>

<style lang="scss" scoped>
.task-documents-page {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  position: relative;
  overflow: hidden;
  
  // 顶部导航栏
  .header-bg {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    background: linear-gradient(180deg, #1ec9c9 0%, #1eb8b8 100%);
    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-scroll {
    width: 100%;
    height: 100%;
    
    .page-content {
      padding: 24rpx;
      padding-bottom: 40rpx;
      
      // 搜索和筛选行
      .search-filter-row {
        display: flex;
        gap: 16rpx;
        margin-bottom: 24rpx;
      }
      
      // 搜索框
      .search-box {
        flex: 1;
        background: #ffffff;
        border-radius: 16rpx;
        padding: 16rpx 20rpx;
        display: flex;
        align-items: center;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
        
        .search-icon {
          width: 32rpx;
          height: 32rpx;
          margin-right: 12rpx;
          flex-shrink: 0;
        }
        
        .search-input {
          flex: 1;
          font-size: 26rpx;
          color: #333333;
          min-width: 0;
        }
        
        .search-placeholder {
          color: #999999;
        }
        
        .search-btn {
          margin-left: 12rpx;
          padding: 8rpx 20rpx;
          background: linear-gradient(135deg, #1ec9c9 0%, #17b3b3 100%);
          border-radius: 8rpx;
          flex-shrink: 0;
          
          &:active {
            opacity: 0.8;
          }
          
          .btn-text {
            font-size: 24rpx;
            color: #ffffff;
            font-weight: 500;
          }
        }
      }
      
      // 状态选择器
      .status-selector {
        background: #ffffff;
        border-radius: 16rpx;
        padding: 16rpx 20rpx;
        display: flex;
        align-items: center;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
        flex-shrink: 0;
        
        picker {
          display: flex;
        }
        
        .selector-value {
          display: flex;
          align-items: center;
          gap: 8rpx;
          
          .value-text {
            font-size: 26rpx;
            color: #1ec9c9;
            font-weight: 500;
            white-space: nowrap;
          }
          
          .arrow-icon {
            font-size: 20rpx;
            color: #1ec9c9;
          }
        }
      }
      
      // 文档列表
      .document-list {
        .document-item {
          background: #ffffff;
          border-radius: 16rpx;
          padding: 24rpx;
          display: flex;
          align-items: center;
          margin-bottom: 16rpx;
          box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
          
          &:active {
            background-color: #f8f8f8;
          }
          
          .doc-thumbnail {
            width: 100rpx;
            height: 120rpx;
            border-radius: 8rpx;
            margin-right: 24rpx;
            background-color: #f0f0f0;
            padding: 10rpx;
            box-sizing: border-box;
          }
          
          .doc-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 12rpx;
            
            .doc-name {
              font-size: 28rpx;
              font-weight: 500;
              color: #333333;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            
            .doc-meta {
              display: flex;
              flex-direction: column;
              gap: 8rpx;
              
              .meta-text {
                font-size: 24rpx;
                color: #999999;
              }
            }
          }
        }
        
        // 加载更多
        .loading-more {
          padding: 32rpx;
          text-align: center;
          
          .loading-text {
            font-size: 24rpx;
            color: #999999;
          }
        }
        
        // 没有更多
        .no-more {
          padding: 32rpx;
          text-align: center;
          
          .no-more-text {
            font-size: 24rpx;
            color: #999999;
          }
        }
        
        // 空状态
        .empty-state {
          padding: 120rpx 32rpx;
          text-align: center;
          
          .empty-text {
            font-size: 28rpx;
            color: #999999;
          }
        }
      }
    }
  }
}
</style>
