<script lang="ts" setup>
import { Icon } from '@iconify/vue'
import VChart from 'vue-echarts'

import { BasicPage } from '@/components/global-layout'
import {
  useGetCoinDistributionQuery,
  useGetProfitAnalysisQuery,
  useGetRiskMetricsQuery,
  useGetTradeAnalysisQuery,
  useGetUserGrowthQuery,
} from '@/services/api/monisuo-admin.api'

// ========== 模块1: 盈利分析 ==========
const { data: profitData, isLoading: profitLoading } = useGetProfitAnalysisQuery('month')

const profitMetrics = computed(() => {
  const data = profitData.value?.data
  if (!data)
    return []

  return [
    { label: '交易手续费', value: data.tradeFee, rate: data.tradeFeeRate, icon: 'lucide:percent', color: 'text-green-600' },
    { label: '充提手续费', value: data.fundFee, rate: data.fundFeeRate, icon: 'lucide:credit-card', color: 'text-blue-600' },
    { label: '资金利差', value: data.interestProfit, rate: data.interestRate, icon: 'lucide:trending-up', color: 'text-purple-600' },
    { label: '本月收益', value: data.totalProfit, rate: '+18.5%', icon: 'lucide:dollar-sign', color: 'text-orange-600' },
  ]
})

// ========== 模块2: 交易分析 ==========
const { data: tradeData, isLoading: tradeLoading } = useGetTradeAnalysisQuery('week')

const tradeAnalysisOption = computed(() => {
  const trend = tradeData.value?.data?.trend || []

  return {
    tooltip: { trigger: 'axis' },
    legend: { data: ['买入', '卖出'], bottom: 0 },
    grid: { left: '3%', right: '4%', bottom: '15%', top: '5%', containLabel: true },
    xAxis: { type: 'category', data: trend.map((t: any) => t.date) },
    yAxis: { type: 'value' },
    series: [
      { name: '买入', type: 'line', smooth: true, data: trend.map((t: any) => t.buy), itemStyle: { color: '#10b981' } },
      { name: '卖出', type: 'line', smooth: true, data: trend.map((t: any) => t.sell), itemStyle: { color: '#ef4444' } },
    ],
  }
})

// ========== 模块3: 币种分布 ==========
const { data: coinData } = useGetCoinDistributionQuery('month')

const coinDistributionOption = computed(() => {
  const data = coinData.value?.data || []
  const colors = ['#f7931a', '#627eea', '#26a17b', '#9ca3af']

  return {
    tooltip: { trigger: 'item', formatter: '{b}: {d}%' },
    legend: { orient: 'vertical', right: '5%', top: 'center' },
    series: [{
      type: 'pie',
      radius: ['50%', '75%'],
      center: ['35%', '50%'],
      itemStyle: { borderRadius: 8, borderColor: '#fff', borderWidth: 2 },
      label: { show: true, position: 'inside', formatter: '{d}%', fontSize: 11 },
      data: data.map((item: any, index: number) => ({
        value: item.amount,
        name: item.coinCode,
        itemStyle: { color: colors[index % colors.length] },
      })),
    }],
  }
})

// ========== 模块4: 用户分析 ==========
const { data: userGrowthData } = useGetUserGrowthQuery(6)

const userMetrics = computed(() => {
  const data = userGrowthData.value?.data
  if (!data)
    return []

  return [
    { label: '新增用户', value: data.monthNewUsers, change: '+15.3%', up: true },
    { label: '活跃用户', value: data.activeUsersToday, change: '+8.7%', up: true },
    { label: '总用户', value: data.totalUsers, change: '+12.1%', up: true },
    { label: '留存率', value: '68%', change: '+5.2%', up: true },
  ]
})

const userGrowthOption = computed(() => {
  const trend = userGrowthData.value?.data?.trend || []

  return {
    tooltip: { trigger: 'axis' },
    legend: { data: ['新增', '活跃'], bottom: 0 },
    grid: { left: '3%', right: '4%', bottom: '15%', top: '5%', containLabel: true },
    xAxis: { type: 'category', boundaryGap: false, data: trend.map((t: any) => t.month) },
    yAxis: { type: 'value' },
    series: [
      { name: '新增', type: 'line', smooth: true, data: trend.map((t: any) => t.newUsers), itemStyle: { color: '#8b5cf6' }, areaStyle: { color: 'rgba(139, 92, 246, 0.1)' } },
      { name: '活跃', type: 'line', smooth: true, data: trend.map((t: any) => t.activeUsers), itemStyle: { color: '#06b6d4' }, areaStyle: { color: 'rgba(6, 182, 212, 0.1)' } },
    ],
  }
})

// ========== 模块5: 风险指标 ==========
const { data: riskData } = useGetRiskMetricsQuery()

const riskMetrics = computed(() => {
  const data = riskData.value?.data
  if (!data)
    return []

  return [
    { label: '大额交易', value: data.largeTransactions, threshold: data.largeTransactionThreshold, status: 'normal', color: 'text-blue-600', bgColor: 'bg-blue-50' },
    { label: '异常提现', value: data.abnormalWithdrawals, threshold: data.abnormalWithdrawalThreshold, status: data.abnormalWithdrawals > 0 ? 'warning' : 'normal', color: 'text-red-600', bgColor: 'bg-red-50' },
    { label: '待审KYC', value: data.pendingKyc, threshold: '身份验证', status: 'normal', color: 'text-yellow-600', bgColor: 'bg-yellow-50' },
    { label: '冻结账户', value: data.frozenAccounts, threshold: '风险账户', status: 'normal', color: 'text-gray-600', bgColor: 'bg-gray-50' },
  ]
})

// ========== 模块6: 决策建议 ==========
const suggestions = computed(() => {
  const data = profitData.value?.data
  const risk = riskData.value?.data

  const items = []

  // 基于盈利情况
  if (data && data.totalProfit > 0) {
    items.push({
      type: 'success',
      icon: 'lucide:check-circle',
      title: '盈利健康',
      desc: `本月总收益 ¥${data.totalProfit.toFixed(2)}，收益趋势良好`,
      color: 'border-green-500 bg-green-50 dark:bg-green-950/20',
    })
  }

  // 基于风险情况
  if (risk && risk.abnormalWithdrawals > 0) {
    items.push({
      type: 'warning',
      icon: 'lucide:alert-circle',
      title: '关注风险',
      desc: `检测到 ${risk.abnormalWithdrawals} 笔异常提现申请，建议加强风控审核`,
      color: 'border-yellow-500 bg-yellow-50 dark:bg-yellow-950/20',
    })
  }

  // 基于交易情况
  if (tradeData.value?.data) {
    items.push({
      type: 'info',
      icon: 'lucide:info',
      title: '交易分析',
      desc: '本周交易活跃，用户参与度良好',
      color: 'border-blue-500 bg-blue-50 dark:bg-blue-950/20',
    })
  }

  return items
})

const isLoading = computed(() => profitLoading.value || tradeLoading.value)

function formatCurrency(value: number): string {
  if (!value)
    return '¥0'
  if (value >= 10000)
    return `¥${(value / 10000).toFixed(1)}万`
  return `¥${value.toLocaleString()}`
}
</script>

<template>
  <BasicPage title="业务分析" description="多维度数据洞察，辅助业务决策">
    <div v-if="isLoading" class="flex items-center justify-center py-20">
      <UiSpinner class="w-8 h-8" />
    </div>

    <div v-else class="space-y-6">
      <!-- 模块1: 盈利分析 -->
      <section>
        <h2 class="text-sm font-medium text-muted-foreground mb-3 flex items-center gap-2">
          <Icon icon="lucide:dollar-sign" class="size-4" />
          盈利分析
        </h2>
        <div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
          <UiCard v-for="item in profitMetrics" :key="item.label" class="hover:shadow-sm transition-shadow">
            <UiCardContent class="pt-6">
              <div class="flex items-center justify-between mb-3">
                <Icon :icon="item.icon" class="size-5" :class="item.color" />
                <span class="text-xs text-muted-foreground">{{ item.rate }}</span>
              </div>
              <p class="text-xs text-muted-foreground">
                {{ item.label }}
              </p>
              <p class="text-2xl font-bold font-mono mt-1" :class="item.color">
                {{ formatCurrency(item.value) }}
              </p>
            </UiCardContent>
          </UiCard>
        </div>
      </section>

      <!-- 模块2: 交易分析 -->
      <section>
        <h2 class="text-sm font-medium text-muted-foreground mb-3 flex items-center gap-2">
          <Icon icon="lucide:trending-up" class="size-4" />
          交易分析
        </h2>
        <UiCard>
          <UiCardContent class="pt-6">
            <VChart :option="tradeAnalysisOption" autoresize style="height: 280px" />
          </UiCardContent>
        </UiCard>
      </section>

      <!-- 模块3: 币种分布 + 用户分析 -->
      <div class="grid gap-4 lg:grid-cols-3">
        <section>
          <h2 class="text-sm font-medium text-muted-foreground mb-3 flex items-center gap-2">
            <Icon icon="lucide:pie-chart" class="size-4" />
            币种交易分布
          </h2>
          <UiCard>
            <UiCardContent class="pt-6">
              <VChart :option="coinDistributionOption" autoresize style="height: 240px" />
            </UiCardContent>
          </UiCard>
        </section>

        <section class="lg:col-span-2">
          <h2 class="text-sm font-medium text-muted-foreground mb-3 flex items-center gap-2">
            <Icon icon="lucide:users" class="size-4" />
            用户分析
          </h2>
          <div class="grid gap-4">
            <div class="grid gap-3 sm:grid-cols-4">
              <UiCard v-for="item in userMetrics" :key="item.label" class="hover:shadow-sm transition-shadow">
                <UiCardContent class="pt-4 pb-4">
                  <p class="text-xs text-muted-foreground">
                    {{ item.label }}
                  </p>
                  <p class="text-xl font-bold mt-1">
                    {{ item.value }}
                  </p>
                  <p class="text-xs mt-1" :class="item.up ? 'text-green-600' : 'text-red-600'">
                    {{ item.change }}
                  </p>
                </UiCardContent>
              </UiCard>
            </div>
            <UiCard>
              <UiCardContent class="pt-6">
                <VChart :option="userGrowthOption" autoresize style="height: 180px" />
              </UiCardContent>
            </UiCard>
          </div>
        </section>
      </div>

      <!-- 模块4: 风险指标 + 决策建议 -->
      <div class="grid gap-4 lg:grid-cols-2">
        <section>
          <h2 class="text-sm font-medium text-muted-foreground mb-3 flex items-center gap-2">
            <Icon icon="lucide:shield" class="size-4" />
            风险指标
          </h2>
          <div class="grid gap-3 sm:grid-cols-2">
            <UiCard v-for="item in riskMetrics" :key="item.label" class="hover:shadow-sm transition-shadow">
              <UiCardContent class="pt-6">
                <div class="flex items-center justify-between mb-2">
                  <p class="text-sm font-medium">
                    {{ item.label }}
                  </p>
                  <span class="text-xs text-muted-foreground">{{ item.threshold }}</span>
                </div>
                <div class="flex items-baseline gap-2">
                  <p class="text-3xl font-bold" :class="item.color">
                    {{ item.value }}
                  </p>
                  <UiBadge v-if="item.status === 'warning'" variant="destructive">
                    需关注
                  </UiBadge>
                </div>
              </UiCardContent>
            </UiCard>
          </div>
        </section>

        <section>
          <h2 class="text-sm font-medium text-muted-foreground mb-3 flex items-center gap-2">
            <Icon icon="lucide:lightbulb" class="size-4" />
            决策建议
          </h2>
          <div class="space-y-3">
            <div
              v-for="item in suggestions"
              :key="item.title"
              class="p-4 rounded-lg border-l-4"
              :class="item.color"
            >
              <div class="flex items-start gap-3">
                <Icon :icon="item.icon" class="size-5 mt-0.5" />
                <div>
                  <p class="font-medium">
                    {{ item.title }}
                  </p>
                  <p class="text-sm text-muted-foreground mt-1">
                    {{ item.desc }}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </section>
      </div>
    </div>
  </BasicPage>
</template>
