<script setup>
definePage({
  layout: 'HomeLayout',
  style: {
    navigationBarTitleText: '数据',
    navigationStyle: 'custom',
  },
})

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

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

const teamStats = ref(null)
const conversionData = ref(null)
const myConversionActiveTab = ref('daily')
const subordinateConversionActiveTab = ref('daily')
const isLoadingConversion = ref(true)
const hasLoaded = ref(false)

async function getData() {
  try {
    const { data: teamData, error: teamError } = await getTeamStatistics()
    if (teamData.value?.code === 200 && !teamError.value) teamStats.value = teamData.value.data
    const { data: conversionRateData, error: conversionError } = await getConversionRate()
    if (conversionRateData.value?.code === 200 && !conversionError.value) conversionData.value = conversionRateData.value.data
  } finally {
    isLoadingConversion.value = false
  }
}

onMounted(() => {
  if (isAgent.value && !hasLoaded.value) {
    isLoadingConversion.value = true
    hasLoaded.value = true
    getData()
  } else if (!isAgent.value) {
    isLoadingConversion.value = false
  }
})

watch(isAgent, (val) => {
  if (val && !hasLoaded.value) {
    isLoadingConversion.value = true
    hasLoaded.value = true
    getData()
  }
})

function toTeamList() {
  uni.navigateTo({ url: '/pages/teamList/index' })
}

function toRegister() {
  const url = mobile.value
    ? `/pages/register/index?mobile=${encodeURIComponent(mobile.value)}`
    : '/pages/register/index'
  uni.navigateTo({ url })
}

</script>

<template>
  <view class="p-4 bg-gradient-to-b from-gray-50/50 to-gray-100/30 min-h-screen">
    <view v-if="isLoggedIn && !isAgent" class="rounded-xl shadow-lg mb-4 bg-white p-6 text-center">
      <view class="text-lg font-bold mb-2 text-gray-800">您还不是代理</view>
      <view class="text-sm mb-4 text-gray-500">注册成为代理后即可查看团队统计和转化率数据</view>
      <button class="px-6 py-2 rounded-full text-white" style="background: linear-gradient(135deg, #8b5cf6, #7c3aed);" @click="toRegister">
        注册成为代理
      </button>
    </view>

    <view v-if="isAgent" class="rounded-xl shadow-lg mb-4 bg-gradient-to-r from-purple-50/60 to-purple-100/50 p-6">
      <view class="flex justify-between items-center mb-4">
        <view class="flex items-center">
          <wd-icon name="user-circle" class="text-xl mr-2" color="#8b5cf6" />
          <text class="text-lg font-bold text-gray-800">团队统计</text>
        </view>
      </view>
      <view class="grid grid-cols-3 gap-3 mb-4">
        <view class="text-center p-2 rounded-lg bg-white/50">
          <view class="text-lg font-bold text-purple-600">{{ teamStats?.total_count || 0 }}</view>
          <view class="text-sm mt-1 text-gray-600">团队人数</view>
        </view>
        <view class="text-center p-2 rounded-lg bg-white/50">
          <view class="text-lg font-bold text-purple-600">{{ teamStats?.today_new_members || 0 }}</view>
          <view class="text-sm mt-1 text-gray-600">今日新增</view>
        </view>
        <view class="text-center p-2 rounded-lg bg-white/50">
          <view class="text-lg font-bold text-purple-600">{{ teamStats?.month_new_members || 0 }}</view>
          <view class="text-sm mt-1 text-gray-600">本月新增</view>
        </view>
      </view>
      <view class="grid grid-cols-4 gap-3 mb-4">
        <view class="text-center p-2 rounded-lg bg-white/50">
          <view class="text-lg font-bold text-purple-600">{{ teamStats?.direct_count || 0 }}</view>
          <view class="text-sm mt-1 text-gray-600">直接下级</view>
        </view>
        <view class="text-center p-2 rounded-lg bg-white/50">
          <view class="text-lg font-bold text-purple-600">{{ teamStats?.indirect_count || 0 }}</view>
          <view class="text-sm mt-1 text-gray-600">间接下级</view>
        </view>
        <view class="text-center p-2 rounded-lg bg-white/50">
          <view class="text-lg font-bold text-amber-600">{{ teamStats?.gold_count || 0 }}</view>
          <view class="text-sm mt-1 text-gray-600">黄金下级</view>
        </view>
        <view class="text-center p-2 rounded-lg bg-white/50">
          <view class="text-lg font-bold text-gray-600">{{ teamStats?.normal_count || 0 }}</view>
          <view class="text-sm mt-1 text-gray-600">普通下级</view>
        </view>
      </view>
      <view class="mt-4">
        <button
          class="w-full text-white rounded-full py-2 px-4 shadow-md flex items-center justify-center"
          style="background: linear-gradient(135deg, #8b5cf6, #7c3aed);"
          @click="toTeamList"
        >
          <wd-icon name="user-circle" class="mr-1" />
          查看我的团队
        </button>
      </view>
    </view>

    <view v-if="isAgent" class="relative rounded-xl shadow-lg mb-3 bg-white overflow-hidden">
      <view class="relative p-5 pb-0">
        <view class="flex items-center mb-4">
          <wd-icon name="chart-trending" class="text-lg mr-2" color="#1989fa" />
          <text class="text-lg font-bold text-gray-800">我的转化率</text>
        </view>
        <view class="absolute top-3 right-3 flex p-1 rounded-2xl bg-blue-500">
          <button
            :class="['px-6 py-2 text-sm font-medium rounded-lg mx-1', myConversionActiveTab === 'daily' ? 'bg-white text-gray-800' : 'text-white']"
            @click="myConversionActiveTab = 'daily'"
          >
            日
          </button>
          <button
            :class="['px-6 py-2 text-sm font-medium rounded-lg mx-1', myConversionActiveTab === 'weekly' ? 'bg-white text-gray-800' : 'text-white']"
            @click="myConversionActiveTab = 'weekly'"
          >
            周
          </button>
          <button
            :class="['px-6 py-2 text-sm font-medium rounded-lg mx-1', myConversionActiveTab === 'monthly' ? 'bg-white text-gray-800' : 'text-white']"
            @click="myConversionActiveTab = 'monthly'"
          >
            月
          </button>
        </view>
      </view>
      <view class="p-5 pt-0">
        <view v-if="!isLoggedIn" class="p-4 rounded-lg bg-gray-50 border border-gray-200 text-center">
          <view class="text-sm text-gray-700">正在登录中，请稍候...</view>
        </view>
        <template v-else>
          <view v-if="isLoadingConversion" class="p-3">
            <wd-skeleton :row="3" />
          </view>
          <template v-else>
            <view v-if="myConversionActiveTab === 'daily'" class="">
              <view
                v-for="item in (conversionData?.my_conversion_rate?.daily || [])"
                :key="item.period_label"
                class="p-4 flex items-center border-b border-gray-200"
              >
                <view class="text-lg font-semibold mr-4 text-gray-800">{{ item.period_label }}</view>
                <view class="flex items-center gap-6 text-base text-blue-600">
                  <text>{{ item.query_user_count || 0 }}人查询</text>
                  <text>{{ item.paid_user_count || 0 }}人付费</text>
                  <text>总金额: {{ (item.total_amount || 0).toFixed(2) }}</text>
                </view>
              </view>
              <view v-if="!(conversionData?.my_conversion_rate?.daily?.length)" class="p-6 text-center text-gray-500 text-sm">
                暂无数据
              </view>
            </view>
            <view v-if="myConversionActiveTab === 'weekly'" class="">
              <view
                v-for="item in (conversionData?.my_conversion_rate?.weekly || [])"
                :key="item.period_label"
                class="p-4 flex items-center border-b border-gray-200"
              >
                <view class="text-lg font-semibold mr-4 text-gray-800">{{ item.period_label }}</view>
                <view class="flex items-center gap-6 text-base text-blue-600">
                  <text>{{ item.query_user_count || 0 }}人查询</text>
                  <text>{{ item.paid_user_count || 0 }}人付费</text>
                  <text>总金额: {{ (item.total_amount || 0).toFixed(2) }}</text>
                </view>
              </view>
              <view v-if="!(conversionData?.my_conversion_rate?.weekly?.length)" class="p-6 text-center text-gray-500 text-sm">
                暂无数据
              </view>
            </view>
            <view v-if="myConversionActiveTab === 'monthly'" class="">
              <view
                v-for="item in (conversionData?.my_conversion_rate?.monthly || [])"
                :key="item.period_label"
                class="p-4 flex items-center border-b border-gray-200"
              >
                <view class="text-lg font-semibold mr-4 text-gray-800">{{ item.period_label }}</view>
                <view class="flex items-center gap-6 text-base text-blue-600">
                  <text>{{ item.query_user_count || 0 }}人查询</text>
                  <text>{{ item.paid_user_count || 0 }}人付费</text>
                  <text>总金额: {{ (item.total_amount || 0).toFixed(2) }}</text>
                </view>
              </view>
              <view v-if="!(conversionData?.my_conversion_rate?.monthly?.length)" class="p-6 text-center text-gray-500 text-sm">
                暂无数据
              </view>
            </view>
          </template>
        </template>
      </view>
    </view>

    <view v-if="isAgent" class="relative rounded-xl shadow-lg mb-3 bg-white overflow-hidden">
      <view class="relative p-5 pb-0">
        <view class="flex items-center mb-4">
          <wd-icon name="chart-bar" class="text-lg mr-2" color="#07c160" />
          <text class="text-lg font-bold text-gray-800">我的下级转化率</text>
        </view>
        <view class="absolute top-3 right-3 flex p-1 rounded-2xl bg-blue-500">
          <button
            :class="['px-6 py-2 text-sm font-medium rounded-lg mx-1', subordinateConversionActiveTab === 'daily' ? 'bg-white text-gray-800' : 'text-white']"
            @click="subordinateConversionActiveTab = 'daily'"
          >
            日
          </button>
          <button
            :class="['px-6 py-2 text-sm font-medium rounded-lg mx-1', subordinateConversionActiveTab === 'weekly' ? 'bg-white text-gray-800' : 'text-white']"
            @click="subordinateConversionActiveTab = 'weekly'"
          >
            周
          </button>
          <button
            :class="['px-6 py-2 text-sm font-medium rounded-lg mx-1', subordinateConversionActiveTab === 'monthly' ? 'bg-white text-gray-800' : 'text-white']"
            @click="subordinateConversionActiveTab = 'monthly'"
          >
            月
          </button>
        </view>
      </view>
      <view class="p-5 pt-0">
        <view v-if="!isLoggedIn" class="p-4 rounded-lg bg-gray-50 border border-gray-200 text-center">
          <view class="text-sm text-gray-700">正在登录中，请稍候...</view>
        </view>
        <template v-else>
          <view v-if="isLoadingConversion" class="p-3">
            <wd-skeleton :row="3" />
          </view>
          <template v-else>
            <view v-if="subordinateConversionActiveTab === 'daily'" class="">
              <view
                v-for="item in (conversionData?.subordinate_conversion_rate?.daily || [])"
                :key="item.period_label"
                class="p-4 flex items-center border-b border-gray-200"
              >
                <view class="text-lg font-semibold mr-4 text-gray-800">{{ item.period_label }}</view>
                <view class="flex items-center gap-6 text-base text-blue-600">
                  <text>{{ item.query_user_count || 0 }}人查询</text>
                  <text>{{ item.paid_user_count || 0 }}人付费</text>
                  <text>总金额: {{ (item.total_amount || 0).toFixed(2) }}</text>
                </view>
              </view>
              <view v-if="!(conversionData?.subordinate_conversion_rate?.daily?.length)" class="p-6 text-center text-gray-500 text-sm">
                暂无数据
              </view>
            </view>
            <view v-if="subordinateConversionActiveTab === 'weekly'" class="">
              <view
                v-for="item in (conversionData?.subordinate_conversion_rate?.weekly || [])"
                :key="item.period_label"
                class="p-4 flex items-center border-b border-gray-200"
              >
                <view class="text-lg font-semibold mr-4 text-gray-800">{{ item.period_label }}</view>
                <view class="flex items-center gap-6 text-base text-blue-600">
                  <text>{{ item.query_user_count || 0 }}人查询</text>
                  <text>{{ item.paid_user_count || 0 }}人付费</text>
                  <text>总金额: {{ (item.total_amount || 0).toFixed(2) }}</text>
                </view>
              </view>
              <view v-if="!(conversionData?.subordinate_conversion_rate?.weekly?.length)" class="p-6 text-center text-gray-500 text-sm">
                暂无数据
              </view>
            </view>
            <view v-if="subordinateConversionActiveTab === 'monthly'" class="">
              <view
                v-for="item in (conversionData?.subordinate_conversion_rate?.monthly || [])"
                :key="item.period_label"
                class="p-4 flex items-center border-b border-gray-200"
              >
                <view class="text-lg font-semibold mr-4 text-gray-800">{{ item.period_label }}</view>
                <view class="flex items-center gap-6 text-base text-blue-600">
                  <text>{{ item.query_user_count || 0 }}人查询</text>
                  <text>{{ item.paid_user_count || 0 }}人付费</text>
                  <text>总金额: {{ (item.total_amount || 0).toFixed(2) }}</text>
                </view>
              </view>
              <view v-if="!(conversionData?.subordinate_conversion_rate?.monthly?.length)" class="p-6 text-center text-gray-500 text-sm">
                暂无数据
              </view>
            </view>
          </template>
        </template>
      </view>
    </view>
  </view>
</template>
