﻿<template>
  <div class="page-container-flex">
    <van-nav-bar 
      title="批量分类" 
      left-text="返回"
      left-arrow
      @click-left="handleBack" 
      placeholder
    />

    <div class="scroll-content">
      <!-- 未分类账单统计 -->
      <div class="unclassified-stat">
        <span>未分类账单数: {{ unclassifiedCount }}</span>
      </div>

      <!-- 分组列表 -->
      <van-empty v-if="!hasData && finished" description="暂无数据" />
      
      <van-list
        v-model:loading="listLoading"
        v-model:error="error"
        :finished="finished"
        finished-text="没有更多了"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <ReasonGroupList
          ref="groupListRef"
          @data-loaded="handleDataLoaded"
          @data-changed="handleDataChanged"
        />
      </van-list>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getUnclassifiedCount } from '@/api/transactionRecord'
import ReasonGroupList from '@/components/ReasonGroupList.vue'

const router = useRouter()
const groupListRef = ref(null)

// 数据状态
const listLoading = ref(false)
const error = ref(false)
const finished = ref(false)
const hasData = ref(false)
const unclassifiedCount = ref(0)

// 获取未分类账单统计
const loadUnclassifiedCount = async () => {
  try {
    const res = await getUnclassifiedCount()
    if (res.success) {
      unclassifiedCount.value = res.data || 0
    }
  } catch (error) {
    console.error('获取未分类账单数量失败:', error)
  }
}

// 处理数据加载完成
const handleDataLoaded = ({ groups, total, finished: isFinished }) => {
  hasData.value = groups.length > 0
  finished.value = isFinished
}

// 处理数据变更
const handleDataChanged = async () => {
  await loadUnclassifiedCount()
}

// 加载更多
const onLoad = async () => {
  if (!groupListRef.value) {
    listLoading.value = false
    return
  }
  
  try {
    await groupListRef.value.loadData()
    
    // 首次加载时获取统计信息
    if (!hasData.value) {
      await loadUnclassifiedCount()
    }
    
    error.value = false
  } catch (err) {
    error.value = true
  } finally {
    listLoading.value = false
  }
}

// 返回上一页
const handleBack = () => {
  router.back()
}

// 页面加载
onMounted(async () => {
  // 初始加载数据
  listLoading.value = true
  await onLoad()
})
</script>

<style scoped>
.unclassified-stat {
  padding-left: 16px;
  padding-top: 12px;
  font-size: 14px;
  font-weight: 500;
  opacity: 0.6;
}

/* 设置页面容器背景色 */
:deep(.van-nav-bar) {
  background: transparent !important;
}
</style>
