<template>
  <view class="project-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">{{ t('projectSelect.title') }}</text>
        <view class="placeholder"></view>
      </view>
    </view>
    
    <!-- 搜索框 -->
    <view class="search-bar">
      <input 
        class="search-input" 
        v-model="searchName" 
        :placeholder="t('projectSelect.search.placeholder')"
        @confirm="handleSearch"
      />
      <view class="search-btn" @click="handleSearch">
        <text class="search-text">{{ t('projectSelect.search.button') }}</text>
      </view>
    </view>
    
    <!-- 项目列表 -->
    <scroll-view 
      scroll-y 
      class="project-list"
      @scrolltolower="handleLoadMore"
    >
      <view 
        v-for="item in projectList" 
        :key="item.id" 
        class="project-item"
        @click="handleSelectProject(item)"
      >
        <view class="project-icon-wrapper">
          <image 
            v-if="item.iconUrl" 
            :src="item.iconUrl" 
            mode="aspectFit" 
            class="project-icon" 
          />
          <image 
            v-else 
            src="/static/icon/project.svg" 
            mode="aspectFit" 
            class="project-icon" 
          />
        </view>
        <view class="project-info">
          <text class="project-name">{{ item.name }}</text>
          <text class="project-detail">{{ t('projectSelect.projectInfo.code') }}: {{ item.code }}</text>
          <text class="project-detail">{{ t('projectSelect.projectInfo.type') }}: {{ getProjectTypeLabel(item.type) }}</text>
          <text class="project-detail">{{ t('projectSelect.projectInfo.startTime') }}: {{ formatDate(item.startTime) }}</text>
        </view>
      </view>
      
      <view v-if="projectList.length === 0 && !loading" class="empty-tip">
        <text class="empty-text">{{ t('projectSelect.message.empty') }}</text>
      </view>
      
      <view v-if="loading" class="loading-tip">
        <text class="loading-text">{{ t('projectSelect.message.loading') }}</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { getProjectList } from '@/apis/scan'
import { getDictDataByType } from '@/apis/dict'

const { locale, t } = useI18n()

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

// 项目列表
const projectList = ref([])
const searchName = ref('')
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 字典数据（原始数据）
const projectTypeDictData = ref([])

// 当前语言
const currentLocale = computed(() => {
  // 将 zh-CN 转换为 zh_CN 格式
  return locale.value.replace('-', '_')
})

onMounted(() => {
  // 获取系统信息
  const windowInfo = uni.getWindowInfo()
  statusBarHeight.value = windowInfo.statusBarHeight || 0
  
  // 加载字典数据
  loadDictData()
  
  // 加载项目列表
  loadProjectList()
})

// 加载字典数据
const loadDictData = async () => {
  try {
    const response = await getDictDataByType('project_type')
    
    if (response && response.code === 200 && response.data) {
      projectTypeDictData.value = response.data
    }
  } catch (error) {
    console.error('加载字典数据失败:', error)
  }
}

// 解析国际化的字典标签
const parseDictLabel = (dictLabel) => {
  try {
    // 尝试解析 JSON 格式的标签
    const labelObj = JSON.parse(dictLabel)
    // 返回当前语言对应的标签，如果不存在则返回中文或第一个可用的值
    return labelObj[currentLocale.value] || labelObj['zh_CN'] || labelObj['en_US'] || dictLabel
  } catch (e) {
    // 如果不是 JSON 格式，直接返回原值
    return dictLabel
  }
}

// 获取项目类型显示文本
const getProjectTypeLabel = (typeValue) => {
  const dictItem = projectTypeDictData.value.find(item => item.dictValue === typeValue)
  if (dictItem) {
    return parseDictLabel(dictItem.dictLabel)
  }
  return typeValue || '-'
}

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

// 加载项目列表
const loadProjectList = async () => {
  if (loading.value) return
  
  try {
    loading.value = true
    
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value
    }
    
    // 搜索关键词使用 content 参数
    if (searchName.value && searchName.value.trim()) {
      params.content = searchName.value.trim()
    }
    
    const response = await getProjectList(params)
    
    if (response.code === 200) {
      if (pageNum.value === 1) {
        projectList.value = response.rows || []
      } else {
        projectList.value = [...projectList.value, ...(response.rows || [])]
      }
      total.value = response.total || 0
    }
  } catch (error) {
    console.error('加载项目列表失败:', error)
    uni.showToast({
      title: t('projectSelect.message.loadFailed'),
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  // 重置分页
  pageNum.value = 1
  projectList.value = []
  loadProjectList()
}

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

// 选择项目
const handleSelectProject = async (project) => {
  // 从全局数据中获取扫描的fileBase64List
  const fileBase64List = getApp().globalData.scannedFileBase64List
  
  if (!fileBase64List || fileBase64List.length === 0) {
    uni.showToast({
      title: t('projectSelect.message.noScanFile'),
      icon: 'none'
    })
    return
  }
  
  // 跳转到上传页面
  uni.navigateTo({
    url: `/pages/scan/upload/index?projectId=${project.id}&projectName=${encodeURIComponent(project.name)}&projectCode=${encodeURIComponent(project.code)}`
  })
}

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

<style lang="scss" scoped>
.project-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;
      }
    }
  }
  
  // 项目列表
  .project-list {
    flex: 1;
    background: #ffffff;
    
    .project-item {
      padding: 24rpx;
      display: flex;
      align-items: center;
      border-bottom: 1rpx solid #f5f5f5;
      
      &:active {
        background: #f8f8f8;
      }
      
      .project-icon-wrapper {
        width: 80rpx;
        height: 80rpx;
        background: #f5f5f5;
        border-radius: 12rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 24rpx;
        
        .project-icon {
          width: 48rpx;
          height: 48rpx;
        }
      }
      
      .project-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 6rpx;
        
        .project-name {
          font-size: 32rpx;
          font-weight: 600;
          color: #333333;
          margin-bottom: 4rpx;
        }
        
        .project-detail {
          font-size: 26rpx;
          color: #666666;
          line-height: 1.5;
        }
      }
    }
    
    .empty-tip {
      padding: 200rpx 0;
      text-align: center;
      
      .empty-text {
        font-size: 28rpx;
        color: #999999;
      }
    }
    
    .loading-tip {
      padding: 32rpx 0;
      text-align: center;
      
      .loading-text {
        font-size: 28rpx;
        color: #999999;
      }
    }
  }
}
</style>
