<script setup>
definePage({
  layout: 'PageLayout',
  style: {
    navigationBarTitleText: '我的团队',
    navigationStyle: 'default',
  },
})

import { ref, computed, onMounted, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useAgentStore } from '@/stores/agentStore'
import { useUserStore } from '@/stores/userStore'
import { getTeamList } from '@/api/agent'

const agentStore = useAgentStore()
const userStore = useUserStore()
const { isAgent } = storeToRefs(agentStore)
const { isLoggedIn } = storeToRefs(userStore)

const list = ref([])
const total = ref(0)
const statistics = ref(null)
const page = ref(1)
const pageSize = ref(20)
const loading = ref(false)
const keyword = ref('')

const hasMore = computed(() => list.value.length < total.value)

async function loadList(isRefresh = false) {
  if (!isAgent.value) return
  if (loading.value) return
  const nextPage = isRefresh ? 1 : page.value
  if (!isRefresh && nextPage > 1 && list.value.length >= total.value && total.value > 0) return
  loading.value = true
  try {
    const params = { page: nextPage, page_size: pageSize.value }
    if (keyword.value.trim()) params.mobile = keyword.value.trim()
    const { data, error } = await getTeamList(params)
    if (data.value && !error.value && data.value.code === 200) {
      const res = data.value.data
      statistics.value = res?.statistics || null
      total.value = res?.total ?? 0
      const items = res?.list || []
      if (nextPage === 1) {
        list.value = items
        page.value = 1
      } else {
        list.value = list.value.concat(items)
      }
      page.value = nextPage
    } else {
      if (isRefresh) list.value = []
    }
  } finally {
    loading.value = false
  }
}

function onRefresh() {
  page.value = 1
  loadList(true)
}

function loadMore() {
  if (!hasMore.value || loading.value) return
  page.value += 1
  loadList(false)
}


function toRegister() {
  uni.navigateTo({ url: '/pages/register/index' })
}

function levelName(level) {
  const map = { 1: '普通代理', 2: '黄金代理', 3: '钻石代理' }
  return map[level] || '代理'
}

onMounted(() => {
  if (isAgent.value) loadList(true)
})

watch(isAgent, (val) => {
  if (val) loadList(true)
})
</script>

<template>
  <view class="p-4 min-h-screen bg-gray-50">
    <view v-if="!isLoggedIn" class="rounded-xl bg-white shadow p-6 text-center">
      <view class="text-gray-600">正在登录中，请稍候...</view>
    </view>
    <view v-else-if="!isAgent" class="rounded-xl bg-white shadow p-6 text-center">
      <view class="text-gray-600 mb-4">注册成为代理后即可查看团队列表</view>
      <wd-button type="primary" block @click="toRegister">注册成为代理</wd-button>
    </view>
    <template v-else>
      <!-- 统计 -->
      <view v-if="statistics" class="rounded-xl bg-white shadow p-4 mb-4">
        <view class="text-base font-semibold text-gray-800 mb-3">团队概览</view>
        <view class="grid grid-cols-3 gap-3">
          <view class="text-center p-2 rounded-lg bg-gray-50">
            <view class="text-lg font-bold text-primary">{{ statistics.total_members || 0 }}</view>
            <view class="text-xs text-gray-500 mt-1">团队人数</view>
          </view>
          <view class="text-center p-2 rounded-lg bg-gray-50">
            <view class="text-lg font-bold text-primary">{{ statistics.today_new_members || 0 }}</view>
            <view class="text-xs text-gray-500 mt-1">今日新增</view>
          </view>
          <view class="text-center p-2 rounded-lg bg-gray-50">
            <view class="text-lg font-bold text-primary">{{ statistics.month_new_members || 0 }}</view>
            <view class="text-xs text-gray-500 mt-1">本月新增</view>
          </view>
        </view>
        <view class="mt-3 flex gap-3">
          <view class="flex-1 text-center p-2 rounded-lg bg-gray-50">
            <view class="text-sm font-semibold text-gray-700">总收益</view>
            <view class="text-sm text-primary">¥{{ (statistics.total_earnings ?? 0).toFixed(2) }}</view>
          </view>
          <view class="flex-1 text-center p-2 rounded-lg bg-gray-50">
            <view class="text-sm font-semibold text-gray-700">今日收益</view>
            <view class="text-sm text-primary">¥{{ (statistics.today_earnings ?? 0).toFixed(2) }}</view>
          </view>
        </view>
      </view>

      <!-- 搜索 -->
      <view class="mb-3">
        <wd-search
          v-model="keyword"
          placeholder="手机号搜索"
          shape="round"
          @search="onRefresh"
          @clear="onRefresh"
        />
      </view>

      <!-- 列表 -->
      <view class="rounded-xl bg-white shadow overflow-hidden">
        <view v-if="loading && list.length === 0" class="p-6">
          <wd-skeleton :row="5" />
        </view>
        <view v-else-if="list.length === 0" class="p-8 text-center text-gray-500 text-sm">
          暂无团队成员
        </view>
        <view v-else class="divide-y divide-gray-100">
          <view
            v-for="item in list"
            :key="item.agent_id"
            class="p-4 flex items-center justify-between"
          >
            <view class="flex-1 min-w-0">
              <view class="flex items-center gap-2">
                <text class="font-medium text-gray-800">{{ item.mobile || '—' }}</text>
                <text
                  v-if="item.is_direct"
                  class="text-xs px-1.5 py-0.5 rounded bg-primary/10 text-primary"
                >
                  直推
                </text>
              </view>
              <view class="text-xs text-gray-500 mt-1">
                {{ levelName(item.level) }} · 加入 {{ item.create_time || '—' }}
              </view>
              <view class="text-xs text-gray-500 mt-0.5">
                返佣 ¥{{ (item.total_rebate_amount ?? 0).toFixed(2) }} · 查询 {{ item.total_queries ?? 0 }} 次
              </view>
            </view>
          </view>
        </view>
        <view v-if="loading && list.length > 0" class="p-3 text-center text-gray-400 text-sm">
          加载中…
        </view>
        <view
          v-else-if="hasMore && list.length > 0"
          class="p-3 text-center text-primary text-sm"
          @click="loadMore"
        >
          加载更多
        </view>
      </view>
    </template>
  </view>
</template>
