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

    <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 _loadedUnclassifiedInitially = ref(false)

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

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

// 处理数据变更
const handleDataChanged = async () => {
  await loadUnclassifiedCount()
  // 重新加载数据
  listLoading.value = true
  await onLoad()
  listLoading.value = false
}

// 加载更多
const onLoad = async () => {
  if (!groupListRef.value) {
    listLoading.value = false
    return
  }
  
  try {
    await groupListRef.value.loadData()

    // 首次加载时获取统计信息（确保统计不会丢失）
    if (!_loadedUnclassifiedInitially.value) {
      await loadUnclassifiedCount()
      _loadedUnclassifiedInitially.value = true
    }
    
    error.value = false
  } catch (err) {
    console.error('加载分组数据失败:', err)
    error.value = true
  } finally {
    listLoading.value = false
  }
}

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

// 页面加载
onMounted(async () => {
  // 初始加载数据
  listLoading.value = true
  try {
    // 先确保统计加载，避免统计消失
    await loadUnclassifiedCount()
    _loadedUnclassifiedInitially.value = true
  } catch (e) {
    console.error('初始化加载未分类统计失败:', e)
  }
  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>
