<template>
  <view class="home-page">
    <!-- 顶部渐变背景区域 - 固定 -->
    <view class="header-bg" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="header-content">
        <text class="header-title">{{ t('home.title') }}</text>
      </view>
    </view>
    
    <!-- 页面内容 - 可滚动 -->
    <scroll-view 
      scroll-y 
      class="page-scroll"
      :style="{ paddingTop: (statusBarHeight + 60) + 'px' }"
      @scrolltolower="handleLoadMore"
    >
      <view class="page-content">
      <!-- 搜索框 -->
      <view class="search-box">
        <image class="search-icon" src="/static/pages/home/search.png" mode="aspectFit" />
        <input 
          class="search-input" 
          :placeholder="t('home.searchPlaceholder')"
          placeholder-class="search-placeholder"
          v-model="searchKeyword"
          @confirm="handleSearch"
        />
        <view class="search-btn" @click="handleSearch">
          <text class="search-btn-text">搜索</text>
        </view>
      </view>
      
      <!-- 轮播图 -->
      <view class="banner-section">
        <swiper 
          class="banner-swiper" 
          :indicator-dots="true" 
          :autoplay="true" 
          :interval="3000"
          :duration="500"
          indicator-color="rgba(255, 255, 255, 0.5)"
          indicator-active-color="#1ec9c9"
        >
          <swiper-item v-for="(item, index) in bannerList" :key="index">
            <image class="banner-image" :src="item.image" mode="aspectFill" />
          </swiper-item>
        </swiper>
      </view>
      
      <!-- 智能扫描卡片 -->
      <view class="scan-card" @click="handleGoToScan">
        <view class="scan-icon-wrapper">
          <image class="scan-icon" src="/static/pages/home/smart-scan.svg" mode="aspectFit" />
        </view>
        <view class="scan-info">
          <text class="scan-title">{{ t('home.intelligentScan') }}</text>
          <text class="scan-desc">{{ t('home.scanDesc') }}</text>
        </view>
      </view>
      
      <!-- 最近文档 -->
      <view class="recent-section">
        <view class="section-header">
          <text class="section-title">{{ t('home.recentDocuments') }}</text>
<!--          <view class="more-btn" @click="handleViewMore">
            <text class="more-text">{{ t('home.viewMore') }}</text>
            <text class="more-arrow">›</text>
          </view> -->
        </view>
        
        <view class="document-list">
          <view 
            v-for="(doc, index) in recentDocuments" 
            :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">{{ formatDocName(doc.name) }}</text>
              <text class="doc-meta">{{ doc.createTime }}</text>
            </view>
          </view>
          
          <!-- 加载状态 -->
          <view v-if="loading" class="loading-more">
            <text class="loading-text">{{ t('common.message.loading') }}</text>
          </view>
          
          <!-- 没有更多数据 -->
          <view v-if="!hasMore && recentDocuments.length > 0" class="no-more">
            <text class="no-more-text">没有更多了</text>
          </view>
          
          <!-- 空状态 -->
          <view v-if="!loading && recentDocuments.length === 0" class="empty-state">
            <text class="empty-text">{{ t('common.message.noData') }}</text>
          </view>
        </view>
      </view>
    </view>
    </scroll-view>
    
    <!-- 底部导航栏 -->
    <TabBar current-tab="home" />
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import TabBar from '@/components/TabBar/index.vue'
import { getCarouselList, getRecentDocuments } from '@/apis/setting'
import { formatDocumentNameForDisplay } from '@/utils/documentName'

const { t } = useI18n()

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

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

// 轮播图数据
const bannerList = ref([])

// 最近文档数据
const recentDocuments = ref([])

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

// 根据文件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'
}

// 格式化文档名称用于显示
const formatDocName = (name) => {
  return formatDocumentNameForDisplay(name)
}

onMounted(() => {
  // 获取系统信息
  const windowInfo = uni.getWindowInfo()
  statusBarHeight.value = windowInfo.statusBarHeight || 0
  
  // 获取轮播图数据
  fetchCarouselList()
  
  // 获取最近文档列表
  fetchRecentDocuments()
})

// 获取轮播图列表
const fetchCarouselList = async () => {
  try {
    const response = await getCarouselList()
    
    if (response && response.code === 200 && response.data) {
      // 按 sort 字段排序
      const sortedData = response.data.sort((a, b) => a.sort - b.sort)
      
      // 转换为轮播图所需的格式
      bannerList.value = sortedData.map(item => ({
        id: item.id,
        image: item.ossidUrl,
        note: item.note
      }))
    }
  } catch (error) {
    console.error('获取轮播图失败:', error)
    // 失败时使用默认图片
    bannerList.value = [
      {
        id: 1,
        image: '/static/pages/home/banner1.png',
        note: '默认轮播图1'
      },
      {
        id: 2,
        image: '/static/pages/home/banner2.png',
        note: '默认轮播图2'
      }
    ]
  }
}

// 获取最近文档列表
const fetchRecentDocuments = async (isLoadMore = false) => {
  if (loading.value) return
  
  try {
    loading.value = true
    
    // 构建请求参数，只在有搜索关键词时才添加 name 参数
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value
    }
    
    // 只有当搜索关键词不为空时才添加 name 参数
    if (searchKeyword.value && searchKeyword.value.trim()) {
      params.name = searchKeyword.value.trim()
    }
    
    const response = await getRecentDocuments(params)
    
    if (response && response.code === 200) {
      const { rows, total: totalCount } = response
      
      total.value = totalCount
      
      if (isLoadMore) {
        // 加载更多，追加数据
        recentDocuments.value = [...recentDocuments.value, ...rows]
      } else {
        // 首次加载或搜索，替换数据
        recentDocuments.value = rows
      }
      
      // 判断是否还有更多数据
      hasMore.value = recentDocuments.value.length < total.value
    }
  } catch (error) {
    console.error('获取最近文档失败:', error)
    
    if (!isLoadMore) {
      recentDocuments.value = []
    }
  } finally {
    loading.value = false
  }
}

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

// 搜索
const handleSearch = () => {
  // 允许空搜索，默认为 ""
  // 重置分页
  pageNum.value = 1
  hasMore.value = true
  
  // 重新加载数据
  fetchRecentDocuments()
}

// 跳转到扫描页面
const handleGoToScan = () => {
  uni.reLaunch({
    url: '/pages/scan/index'
  })
}

// 查看更多文档
const handleViewMore = () => {
  uni.showToast({
    title: '查看更多文档',
    icon: 'none'
  })
  // TODO: 跳转到文档列表页
}

// 点击文档
const handleDocumentClick = (doc) => {
  if (!doc.url && !doc.ossId) {
    uni.showToast({
      title: '文档地址无效',
      icon: 'none'
    })
    return
  }
  
  // 手动构建URL参数
  const params = []
  if (doc.name) {
    params.push(`name=${encodeURIComponent(doc.name)}`)
  }
  if (doc.url) {
    params.push(`url=${encodeURIComponent(doc.url)}`)
  }
  if (doc.ossId) {
    params.push(`ossId=${doc.ossId}`)
  }
  
  const queryString = params.join('&')
  
  uni.navigateTo({
    url: `/pages/home/documentViewer/index?${queryString}`
  })
}
</script>

<style lang="scss" scoped>
.home-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 {
      padding: 0 24rpx 16rpx;
      
      .header-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #ffffff;
        display: block;
        padding: 12rpx 0;
        line-height: 1.4;
      }
    }
  }
  
  // 可滚动区域
  .page-scroll {
    width: 100%;
    height: 100%;
    
    // 页面内容
    .page-content {
      padding: 0 24rpx 24rpx;
      padding-bottom: calc(124rpx + env(safe-area-inset-bottom));
      
      // 搜索框
      .search-box {
      background: #ffffff;
      border-radius: 16rpx;
      padding: 20rpx 24rpx;
      display: flex;
      align-items: center;
      margin-bottom: 24rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
      gap: 16rpx;
      
      .search-icon {
        width: 32rpx;
        height: 32rpx;
      }
      
      .search-input {
        flex: 1;
        font-size: 28rpx;
        color: #333333;
      }
      
      .search-placeholder {
        color: #999999;
      }
      
      .search-btn {
        padding: 8rpx 24rpx;
        background: #1ec9c9;
        border-radius: 24rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        
        &:active {
          background: #1ab8b8;
        }
        
        .search-btn-text {
          font-size: 26rpx;
          color: #ffffff;
          font-weight: 500;
        }
      }
      }
      
      // 轮播图
      .banner-section {
      margin-bottom: 24rpx;
      
      .banner-swiper {
        width: 100%;
        height: 280rpx;
        border-radius: 16rpx;
        overflow: hidden;
        
        .banner-image {
          width: 100%;
          height: 100%;
        }
        }
      }
      
      // 智能扫描卡片
      .scan-card {
      background: #ffffff;
      border-radius: 16rpx;
      padding: 32rpx 24rpx;
      display: flex;
      align-items: center;
      margin-bottom: 24rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
      
      &:active {
        background-color: #f8f8f8;
      }
      
      .scan-icon-wrapper {
        width: 88rpx;
        height: 88rpx;
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 24rpx;
        
        .scan-icon {
          width: 56rpx;
          height: 56rpx;
        }
      }
      
      .scan-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 8rpx;
        
        .scan-title {
          font-size: 32rpx;
          font-weight: 600;
          color: #333333;
        }
        
        .scan-desc {
          font-size: 24rpx;
          color: #999999;
          line-height: 1.4;
        }
        }
      }
      
      // 最近文档
      .recent-section {
      .section-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 24rpx;
        
        .section-title {
          font-size: 32rpx;
          font-weight: 600;
          color: #333333;
        }
        
        .more-btn {
          display: flex;
          align-items: center;
          gap: 4rpx;
          
          .more-text {
            font-size: 26rpx;
            color: #999999;
          }
          
          .more-arrow {
            font-size: 36rpx;
            color: #999999;
            font-weight: 300;
          }
        }
      }
      
      .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 {
              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>
