<script setup>
definePage({
  layout: 'PageLayout',
  style: {
    navigationBarTitleText: '调整下级级别',
    navigationStyle: 'default',
  },
})

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

const agentStore = useAgentStore()
const { isAgent, level } = storeToRefs(agentStore)

const teamMembers = ref([])
const loading = ref(false)
const finished = ref(false)
const page = ref(1)
const pageSize = 10
const refreshing = ref(false)
const searchMobile = ref('')
const showConfirmDialog = ref(false)
const currentUpgradeItem = ref(null)
const isUpgrading = ref(false)

// 检查是否是钻石代理
const isDiamondAgent = computed(() => {
  return isAgent.value && level.value === 3
})

onBeforeMount(() => {
  page.value = 1
  finished.value = false
})

// 获取团队列表（仅普通代理）
async function fetchTeamMembers() {
  if (loading.value || finished.value) return

  loading.value = true
  try {
    const params = {
      page: page.value,
      page_size: pageSize,
    }
    if (searchMobile.value && searchMobile.value.trim()) {
      params.mobile = searchMobile.value.trim()
    }

    const { data, error } = await getTeamList(params)

    if (data.value && !error.value) {
      if (data.value.code === 200) {
        let list = data.value.data.list || []

        // 过滤出普通代理（level === 1）
        list = list.filter((item) => {
          const agentLevel = item.level || (item.level_name === '普通' ? 1 : item.level_name === '黄金' ? 2 : item.level_name === '钻石' ? 3 : 1)
          return agentLevel === 1
        })

        if (page.value === 1) {
          teamMembers.value = list
        } else {
          teamMembers.value.push(...list)
        }

        // 判断是否加载完成
        if (list.length < pageSize) {
          finished.value = true
        } else if (teamMembers.value.length >= data.value.data.total) {
          finished.value = true
        } else {
          page.value++
        }
      } else {
        finished.value = true
        uni.showToast({ title: data.value.msg || '获取团队列表失败', icon: 'none' })
      }
    } else {
      finished.value = true
      uni.showToast({ title: '获取团队列表失败', icon: 'none' })
      console.error('获取团队列表失败:', error.value || '请求失败')
    }
  } catch (err) {
    finished.value = true
    console.error('获取团队列表失败:', err)
    uni.showToast({ title: '获取团队列表失败', icon: 'none' })
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 下拉刷新
function onRefresh() {
  finished.value = false
  page.value = 1
  fetchTeamMembers()
}

// 搜索功能
function handleSearch() {
  finished.value = false
  page.value = 1
  fetchTeamMembers()
}

// 清空搜索
function handleClear() {
  searchMobile.value = ''
  finished.value = false
  page.value = 1
  fetchTeamMembers()
}

// 处理升级
function handleUpgrade(item) {
  currentUpgradeItem.value = item
  showConfirmDialog.value = true
}

// 确认升级
async function confirmUpgrade() {
  if (!currentUpgradeItem.value) return

  isUpgrading.value = true
  try {
    const { data, error } = await upgradeSubordinate({
      subordinate_id: currentUpgradeItem.value.agent_id || currentUpgradeItem.value.id,
      to_level: 2, // 只能升级为黄金代理
    })

    if (data.value && !error.value) {
      if (data.value.code === 200) {
        uni.showToast({ title: '升级成功', icon: 'success' })
        showConfirmDialog.value = false
        currentUpgradeItem.value = null

        // 刷新列表
        finished.value = false
        page.value = 1
        await fetchTeamMembers()

        // 刷新代理状态
        await agentStore.fetchAgentStatus()
      } else {
        uni.showToast({ title: data.value.msg || '升级失败', icon: 'none' })
      }
    } else {
      uni.showToast({ title: '升级失败，请重试', icon: 'none' })
    }
  } catch (err) {
    console.error('升级失败:', err)
    uni.showToast({ title: '升级失败，请重试', icon: 'none' })
  } finally {
    isUpgrading.value = false
  }
}

// 格式化时间
function formatTime(timeStr) {
  if (!timeStr) return '-'
  return timeStr.split(' ')[0]
}

// 格式化金额
function formatNumber(num) {
  if (!num) return '0.00'
  return Number(num).toFixed(2)
}

// 格式化数字
function formatCount(num) {
  if (!num) return '0'
  return Number(num).toLocaleString()
}

// 上拉加载更多
function onLoadMore() {
  if (!finished.value && !loading.value) {
    fetchTeamMembers()
  }
}

onMounted(() => {
  // 检查权限
  if (!isDiamondAgent.value) {
    uni.showToast({ title: '只有钻石代理可以升级下级', icon: 'none' })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
    return
  }
  fetchTeamMembers()
})
</script>

<template>
  <view class="min-h-screen bg-gray-50 pb-4">
    <!-- 说明卡片 -->
    <view class="bg-white mx-4 mt-4 rounded-xl p-4 shadow-sm">
        <view class="flex gap-3">
          <wd-icon name="info-o" class="text-lg text-blue-500 flex-shrink-0 mt-0.5" />
          <view class="flex-1">
            <view class="text-base font-semibold text-gray-800 mb-2">调整说明</view>
            <view class="text-sm text-gray-600 space-y-1">
              <view>• 仅可升级普通代理为黄金代理</view>
              <view>• 调整操作免费，无需支付费用</view>
            </view>
          </view>
        </view>
    </view>

    <!-- 搜索框 -->
    <view class="mx-4 mt-4">
      <view class="flex gap-2">
        <input
          v-model="searchMobile"
          type="text"
          placeholder="请输入手机号搜索"
          class="flex-1 px-4 py-2.5 border border-gray-300 rounded-lg text-base bg-white"
          @confirm="handleSearch"
        />
        <button
          class="px-4 py-2.5 bg-blue-500 text-white rounded-lg text-base whitespace-nowrap"
          @click="handleSearch"
        >
          搜索
        </button>
      </view>
    </view>

    <!-- 代理列表 -->
    <scroll-view
      scroll-y
      class="flex-1 mt-4"
      style="height: calc(100vh - 280px)"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      :lower-threshold="80"
      @scrolltolower="onLoadMore"
    >
      <view class="px-4">
        <!-- 空状态 -->
        <view
          v-if="teamMembers.length === 0 && !loading"
          class="bg-white rounded-xl p-12 flex flex-col items-center justify-center"
        >
          <wd-icon name="user-o" class="text-6xl text-gray-300 mb-4" />
          <text class="text-base text-gray-500">暂无可调整的普通代理</text>
        </view>

        <!-- 成员卡片 -->
        <view
          v-for="(item, index) in teamMembers"
          :key="item.agent_id || item.id"
          class="bg-white rounded-xl p-4 mb-3 shadow-sm"
        >
          <view class="flex items-start gap-3 mb-3">
            <view
              class="w-7 h-7 flex items-center justify-center bg-gray-200 text-gray-600 rounded-md text-sm font-semibold flex-shrink-0"
            >
              {{ index + 1 }}
            </view>
            <view class="flex-1 min-w-0">
              <view class="text-base font-semibold text-gray-800 mb-1">
                {{ item.mobile || '未绑定手机' }}
              </view>
              <view class="text-xs text-gray-500">加入时间：{{ formatTime(item.create_time) }}</view>
            </view>
            <view class="flex-shrink-0">
              <view
                class="px-3 py-1 bg-gray-200 text-gray-600 rounded-xl text-xs font-medium"
              >
                普通代理
              </view>
            </view>
          </view>

          <view class="grid grid-cols-3 gap-3 mb-4 p-3 bg-gray-50 rounded-lg">
            <view class="text-center">
              <view class="text-xs text-gray-500 mb-1">总查询量</view>
              <view class="text-sm font-semibold text-gray-800">{{ formatCount(item.total_queries || 0) }}</view>
            </view>
            <view class="text-center">
              <view class="text-xs text-gray-500 mb-1">返佣总额</view>
              <view class="text-sm font-semibold text-gray-800">¥{{ formatNumber(item.total_rebate_amount || 0) }}</view>
            </view>
            <view class="text-center">
              <view class="text-xs text-gray-500 mb-1">邀请人数</view>
              <view class="text-sm font-semibold text-gray-800">{{ formatCount(item.total_invites || 0) }}</view>
            </view>
          </view>

          <view class="flex justify-end">
            <button
              class="px-4 py-2 bg-blue-500 text-white rounded-lg text-sm font-medium flex items-center justify-center"
              @click="handleUpgrade(item)"
            >
              <text>调整为黄金代理</text>
            </button>
          </view>
        </view>

        <!-- 加载状态 -->
        <view v-if="teamMembers.length > 0" class="py-4 text-center text-gray-400 text-sm">
          <text v-if="loading">加载中...</text>
          <text v-else-if="finished">没有更多了</text>
          <text v-else>上拉加载更多</text>
        </view>
      </view>
    </scroll-view>

    <!-- 确认升级弹窗 -->
    <view
      v-if="showConfirmDialog"
      class="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
      @click.self="showConfirmDialog = false"
    >
      <view class="mx-4 w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl" @click.stop>
        <view class="flex items-center gap-3 mb-4">
          <wd-icon name="warning-o" class="text-2xl text-amber-500" />
          <view class="text-lg font-semibold text-gray-800">确认升级</view>
        </view>
        <view class="mb-6">
          <view class="text-base text-gray-700 mb-4 leading-relaxed">
            确定要将
            <text class="text-blue-500 font-semibold">{{ currentUpgradeItem?.mobile }}</text>
            升级为黄金代理吗？
          </view>
          <view class="bg-amber-50 rounded-lg p-3 text-sm text-amber-800 space-y-1">
            <view>• 升级操作不可撤销</view>
            <view>• 升级操作免费</view>
          </view>
        </view>
        <view class="flex gap-3">
          <button
            class="flex-1 py-3 rounded-lg text-base font-medium text-gray-700 bg-gray-100"
            @click="showConfirmDialog = false"
          >
            取消
          </button>
          <button
            class="flex-1 py-3 rounded-lg text-base font-medium text-white bg-blue-500"
            :disabled="isUpgrading"
            @click="confirmUpgrade"
          >
            {{ isUpgrading ? '升级中...' : '确认升级' }}
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<style scoped>
/* 确保样式正确应用 */
</style>
