<script setup>
import { ref, computed } from 'vue'
import { getAgentRevenue } from '@/api/apis'
import GzhQrcode from '@/components/GzhQrcode.vue'
import { getAgentTabShareTitle } from '@/utils/runtimeEnv.js'

// 分享给好友、分享到朋友圈
useShare({ title: getAgentTabShareTitle() })

// 日期选项映射
const dateRangeMap = {
  today: 'today',
  week: 'last7d',
  month: 'last30d'
}

// 日期文本映射
const dateTextMap = {
  today: '今日',
  week: '近7天',
  month: '近1月'
}

// 直推报告数据
const promoteDateOptions = [
  { label: '今日', value: 'today' },
  { label: '近7天', value: 'week' },
  { label: '近1月', value: 'month' }
]
const selectedPromoteDate = ref('today')

// 团队奖励数据（仅保留：下级推广/下级转化/下级提现）
const teamDateOptions = [
  { label: '今日', value: 'today' },
  { label: '近7天', value: 'week' },
  { label: '近1月', value: 'month' }
]
const selectedTeamDate = ref('today')

const data = ref(null)

// 控制公众号二维码弹窗显示
const showGzhQrcode = ref(false)

// 计算当前直推数据
const currentPromoteData = computed(() => {
  const range = dateRangeMap[selectedPromoteDate.value]
  return data.value?.direct_push?.[range] || { commission: 0, report: 0 }
})

const currentTeamData = computed(() => {
  const range = dateRangeMap[selectedTeamDate.value]
  return data.value?.active_reward?.[range] || {
    sub_promote_reward: 0,
    sub_upgrade_reward: 0,
    sub_withdraw_reward: 0
  }
})

// 计算日期文本
const promoteTimeText = computed(() => {
  return dateTextMap[selectedPromoteDate.value] || '今日'
})

const teamTimeText = computed(() => {
  return dateTextMap[selectedTeamDate.value] || '今日'
})

const getData = async () => {
  try {
    const res = await getAgentRevenue()
    if (res.code === 200) {
      data.value = res.data
    }
  } catch {}
}

onBeforeMount(() => {
  if (uni.getStorageSync('token')) {
    getData()
  }
})

// 路由跳转
function goToPromoteDetail() {
  uni.navigateTo({
    url: '/pages/promoteDetails'
  })
}

function goToRewardsDetail() {
  uni.navigateTo({
    url: '/pages/rewardsDetails'
  })
}

function toWithdraw() {
  // 弹出公众号二维码提示提现
  showGzhQrcode.value = true
}

// 关闭公众号二维码弹窗
function closeGzhQrcode() {
  showGzhQrcode.value = false
}

function toWithdrawDetails() {
  uni.navigateTo({
    url: '/pages/withdrawDetails'
  })
}
</script>

<template>
  <view class="safe-area-top min-h-screen">
    <view class="p-4">
      <!-- 资产卡片 -->
      <view class="rounded-xl shadow-lg mb-4 bg-gradient-to-r from-blue-50/70 to-blue-100/50 p-6">
        <view class="flex justify-between items-center mb-3">
          <view class="flex items-center">


            <text class="text-lg font-bold text-gray-800">余额</text>
          </view>
          <text class="text-3xl text-blue-600 font-bold">¥ {{ (data?.balance || 0).toFixed(2) }}</text>
        </view>
        <view class="text-sm text-gray-500 mb-2">累计收益：¥ {{ (data?.total_earnings || 0).toFixed(2) }}</view>
        <view class="text-sm text-gray-500 mb-6">冻结余额：¥ {{ (data?.frozen_balance || 0).toFixed(2) }}</view>
        <view class="grid grid-cols-2 gap-3">
          <view @click="toWithdraw"
            class="bg-gradient-to-r from-blue-500 to-blue-400 text-white rounded-full py-2 shadow-md flex items-center justify-center">
            <text>提现</text>
          </view>
          <view @click="toWithdrawDetails"
            class="bg-white/90 text-gray-600 border border-gray-200/50 rounded-full py-2 shadow-sm flex items-center justify-center">
            <text>提现记录</text>
          </view>
        </view>
      </view>

      <!-- 直推报告收益 -->
      <view class="rounded-xl shadow-lg mb-4 bg-gradient-to-r from-blue-50/40 to-cyan-50/50 p-6">
        <view class="flex justify-between items-center mb-4">
          <view class="flex items-center">
            <text class="text-lg font-bold text-gray-800">直推报告收益</text>
          </view>
          <view class="text-right">
            <text class="text-2xl text-blue-600 font-bold">¥ {{ (data?.direct_push?.total_commission || 0).toFixed(2)
              }}</text>
            <view class="text-sm text-gray-500 mt-1">有效报告 {{ data?.direct_push?.total_report || 0 }} 份</view>
          </view>
        </view>

        <!-- 日期选择 -->
        <view class="grid grid-cols-3 gap-2 mb-6">
          <view v-for="item in promoteDateOptions" :key="item.value" @click="selectedPromoteDate = item.value" :class="[
            'rounded-full transition-all py-1 px-4 text-sm text-center',
            selectedPromoteDate === item.value
              ? 'bg-blue-500 text-white shadow-md'
              : 'bg-white/90 text-gray-600 border border-gray-200/50'
          ]">
            {{ item.label }}
          </view>
        </view>

        <view class="grid grid-cols-2 gap-4 mb-6">
          <view class="bg-blue-50/60 p-3 rounded-lg backdrop-blur-sm">
            <view class="flex items-center text-sm text-gray-500">
              <text>{{ promoteTimeText }}收益</text>
            </view>
            <text class="text-xl text-blue-600 font-bold mt-1">¥ {{ currentPromoteData.commission?.toFixed(2) || '0.00'
              }}</text>
          </view>
          <view class="bg-blue-50/60 p-3 rounded-lg backdrop-blur-sm">
            <view class="flex items-center text-sm text-gray-500">
              <text>有效报告</text>
            </view>
            <text class="text-xl text-blue-600 font-bold mt-1">{{ currentPromoteData.report || 0 }} 份</text>
          </view>
        </view>

        <view class="flex items-center justify-between text-blue-500 text-sm font-semibold" @click="goToPromoteDetail">
          <text>查看收益明细</text>
          <text class="text-lg">→</text>
        </view>
      </view>

      <!-- 团队奖励（移除活跃下级/新增活跃，仅保留下级推广、转化、提现） -->
      <view class="rounded-xl shadow-lg bg-gradient-to-r from-green-50/40 to-cyan-50/30 p-6">
        <view class="flex justify-between items-center mb-4">
          <view class="flex items-center">
            <text class="text-lg font-bold text-gray-800">团队奖励</text>
          </view>
        </view>

        <view class="grid grid-cols-3 gap-2 mb-6">
          <view v-for="item in teamDateOptions" :key="item.value" @click="selectedTeamDate = item.value" :class="[
            'rounded-full transition-all py-1 px-4 text-sm text-center',
            selectedTeamDate === item.value
              ? 'bg-green-500 text-white shadow-md'
              : 'bg-white/90 text-gray-600 border border-gray-200/50'
          ]">
            {{ item.label }}
          </view>
        </view>

        <view class="grid grid-cols-1 gap-2 mb-6">
          <view class="bg-green-50/60 p-3 rounded-lg backdrop-blur-sm">
            <view class="flex items-center text-sm text-gray-500">
              <text>{{ teamTimeText }}下级推广奖励</text>
            </view>
            <text class="text-xl text-green-600 font-bold mt-1">¥ {{ (currentTeamData.sub_promote_reward || 0).toFixed(2) }}</text>
          </view>
          <view class="bg-green-50/60 p-3 rounded-lg backdrop-blur-sm">
            <view class="flex items-center text-sm text-gray-500">
              <text>{{ teamTimeText }}下级转化奖励</text>
            </view>
            <text class="text-xl text-green-600 font-bold mt-1">¥ {{ (currentTeamData.sub_upgrade_reward || 0).toFixed(2) }}</text>
          </view>
          <view class="bg-green-50/60 p-3 rounded-lg backdrop-blur-sm">
            <view class="flex items-center text-sm text-gray-500">
              <text>{{ teamTimeText }}下级提现奖励</text>
            </view>
            <text class="text-xl text-green-600 font-bold mt-1">¥ {{ (currentTeamData.sub_withdraw_reward || 0).toFixed(2) }}</text>
          </view>
        </view>

        <view class="flex items-center justify-between text-green-500 text-sm font-semibold" @click="goToRewardsDetail">
          <text>查看奖励明细</text>
          <text class="text-lg">→</text>
        </view>
      </view>
    </view>

    <!-- 公众号二维码弹窗 -->
    <GzhQrcode
      :visible="showGzhQrcode"
      type="withdraw"
      @close="closeGzhQrcode"
    />
  </view>
</template>

<style>
button {
  transition: all 0.2s ease;
}

button:hover {
  transform: translateY(-1px);
}
</style>

<route lang="json">{
  "layout": "home",
  "style": {
    "navigationBarTextStyle": "black",
    "navigationStyle": "default",
    "navigationBarBackgroundColor": "#e3f0ff"
  }
}</route>
