<template>
  <div class="app-container">
    <!-- ===== 顶部概览卡片 ===== -->
    <el-row :gutter="16" class="mb16">
      <el-col :span="6" v-for="card in overviewCards" :key="card.label">
        <el-card shadow="hover" class="overview-card">
          <div class="card-inner">
            <div class="card-icon" :style="{ background: card.bg }">
              <i :class="card.icon"></i>
            </div>
            <div class="card-info">
              <span class="card-value">{{ card.value }}</span>
              <span class="card-label">{{ card.label }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- ===== 日期筛选工具条（全局生效） ===== -->
    <el-card shadow="never" class="mb16 filter-card">
      <el-form :inline="true" size="small">
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item>
          <inline-tenant-selector @change="handleQuery" />
      <el-button type="primary" icon="el-icon-search" @click="refreshAll">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- ===== 核心统计区：三栏并排 ===== -->
    <el-row :gutter="16" class="mb16">
      <!-- 左：代理分佣 -->
      <el-col :span="12">
        <el-card shadow="hover" class="stat-panel">
          <div slot="header">
            <i class="el-icon-user-solid"></i> 代理分佣
            <span class="header-tip">（按代理汇总）</span>
          </div>
          <el-table :data="proxyList" border size="small" max-height="360">
            <el-table-column label="代理ID" prop="proxyId" width="80" align="center" />
            <el-table-column label="消费金额" align="center">
              <template slot-scope="s">{{ fmt(s.row.consumeAmount) }}</template>
            </el-table-column>
            <el-table-column label="分佣金额" align="center">
              <template slot-scope="s"><b class="color-profit">{{ fmt(s.row.proxyProfit) }}</b></template>
            </el-table-column>
            <el-table-column label="订单数" prop="orderCount" width="80" align="center" />
            <el-table-column label="操作" width="80" align="center">
              <template slot-scope="s">
                <el-button type="text" size="mini" @click="showProxyDetail(s.row.proxyId)">明细</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 右：租户消费 -->
      <el-col :span="12">
        <el-card shadow="hover" class="stat-panel">
          <div slot="header">
            <i class="el-icon-building"></i> 租户消费
            <span class="header-tip">（按租户汇总）</span>
          </div>
          <el-table :data="tenantList" border size="small" max-height="360">
            <el-table-column label="租户ID" prop="tenantId" width="80" align="center" />
            <el-table-column label="消费金额" align="center">
              <template slot-scope="s">{{ fmt(s.row.consumeAmount) }}</template>
            </el-table-column>
            <el-table-column label="平台成本" align="center">
              <template slot-scope="s"><span class="color-cost">{{ fmt(s.row.platformCost) }}</span></template>
            </el-table-column>
            <el-table-column label="分佣" align="center">
              <template slot-scope="s">{{ fmt(s.row.proxyProfit) }}</template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template slot-scope="s">
                <el-button type="text" size="mini" @click="showTenantDetail(s.row.tenantId)">明细</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- ===== 下半区：两栏 ===== -->
    <el-row :gutter="16">
      <!-- 左：按消费类型统计 -->
      <el-col :span="12">
        <el-card shadow="hover" class="stat-panel">
          <div slot="header">
            <i class="el-icon-data-line"></i> 消费类型统计
            <span class="header-tip">（按8项服务）</span>
          </div>
          <el-table :data="typeTable" border size="small" max-height="340">
            <el-table-column label="服务类型" prop="typeName" />
            <el-table-column label="消费金额" align="center">
              <template slot-scope="s">{{ fmt(s.row.consume) }}</template>
            </el-table-column>
            <el-table-column label="平台成本" align="center">
              <template slot-scope="s"><span class="color-cost">{{ fmt(s.row.cost) }}</span></template>
            </el-table-column>
            <el-table-column label="分佣" align="center">
              <template slot-scope="s"><span class="color-profit">{{ fmt(s.row.profit) }}</span></template>
            </el-table-column>
            <el-table-column label="平台收益" align="center">
              <template slot-scope="s"><b class="color-revenue">{{ fmt(platformRevenue(s.row)) }}</b></template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 右：成本汇总 + 趋势 -->
      <el-col :span="12">
        <el-card shadow="hover" class="stat-panel mb16">
          <div slot="header"><i class="el-icon-coins"></i> 成本汇总</div>
          <el-row :gutter="12">
            <el-col :span="6" v-for="item in costItems" :key="item.label">
              <div class="cost-block" :class="item.cls">
                <span class="cost-num">{{ fmt(item.value) }}</span>
                <span class="cost-label">{{ item.label }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <el-card shadow="hover" class="stat-panel">
          <div slot="header"><i class="el-icon-time"></i> 小时统计</div>
          <template v-if="hourlyStats.length > 0">
            <el-table :data="hourlyStats" border size="small" max-height="200">
              <el-table-column label="小时" prop="statHour" width="80" align="center" />
              <el-table-column label="维度" prop="statDimension" width="80" align="center">
                <template slot-scope="s">{{ dimName(s.row.statDimension) }}</template>
              </el-table-column>
              <el-table-column label="消费金额" align="center">
                <template slot-scope="s">{{ fmt(s.row.consumeAmount) }}</template>
              </el-table-column>
              <el-table-column label="成本" align="center">
                <template slot-scope="s">{{ fmt(s.row.platformCost) }}</template>
              </el-table-column>
              <el-table-column label="分佣" align="center">
                <template slot-scope="s">{{ fmt(s.row.proxyProfit) }}</template>
              </el-table-column>
            </el-table>
          </template>
          <el-empty v-else description="暂无小时统计" :image-size="60" />
        </el-card>
      </el-col>
    </el-row>

    <!-- ===== 代理分佣明细弹窗 ===== -->
    <el-dialog :title="'代理 ' + detailProxyId + ' 分佣明细'" :visible.sync="proxyDetailVisible" width="640px">
      <el-table :data="proxyDetailList" border size="small">
        <el-table-column label="日期" prop="statDate" />
        <el-table-column label="消费金额" align="center">
          <template slot-scope="s">{{ fmt(s.row.consumeAmount) }}</template>
        </el-table-column>
        <el-table-column label="平台成本" align="center">
          <template slot-scope="s">{{ fmt(s.row.platformCost) }}</template>
        </el-table-column>
        <el-table-column label="分佣金额" align="center">
          <template slot-scope="s"><b class="color-profit">{{ fmt(s.row.proxyProfit) }}</b></template>
        </el-table-column>
        <el-table-column label="订单数" prop="orderCount" align="center" />
      </el-table>
      <el-divider />
      <span>总计分佣：<b class="color-profit">{{ fmt(proxyDetailTotal) }}</b></span>
    </el-dialog>

    <!-- ===== 租户消费明细弹窗 ===== -->
    <el-dialog :title="'租户 ' + detailTenantId + ' 消费明细'" :visible.sync="tenantDetailVisible" width="640px">
      <el-table :data="tenantDetailList" border size="small">
        <el-table-column label="日期" prop="statDate" />
        <el-table-column label="消费金额" align="center">
          <template slot-scope="s">{{ fmt(s.row.consumeAmount) }}</template>
        </el-table-column>
        <el-table-column label="平台成本" align="center">
          <template slot-scope="s">{{ fmt(s.row.platformCost) }}</template>
        </el-table-column>
        <el-table-column label="分佣" align="center">
          <template slot-scope="s">{{ fmt(s.row.proxyProfit) }}</template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  getOverview, getProxyProfitStatistics, getProxyProfitDetail,
  getTenantConsumeStatistics, getTenantDetail,
  getConsumeTypeStatistics, getCostSummary, getHourlyStatistics
} from '@/api/admin/statistics'

const TYPE_NAMES = {
  'COURSE': '课程流量费', 'LIVE': '直播流量费', 'AI_TOKEN': 'AI TOKEN',
  'SMS': '短信发送', 'MANUAL_CALL': '手拨外呼', 'AI_CALL': 'AI智能外呼',
  'MICRO_ASSISTANT': '微助手', 'ACCOUNT_FEE': '账户费'
}

import InlineTenantSelector from "@/components/InlineTenantSelector"

export default {
  name: 'AdminStatistics',
  data() {
    return {
      dateRange: [],
      // 概览卡片
      overviewCards: [
        { label: '租户总数', value: 0, icon: 'el-icon-building', bg: '#e6f7ff' },
        { label: '代理总数', value: 0, icon: 'el-icon-user-solid', bg: '#f6ffed' },
        { label: '今日消费', value: '¥0.00', icon: 'el-icon-wallet', bg: '#fff7e6' },
        { label: '今日分佣', value: '¥0.00', icon: 'el-icon-coins', bg: '#f9f0ff' }
      ],
      // 代理分佣列表
      proxyList: [],
      // 租户消费列表
      tenantList: [],
      // 消费类型统计
      typeTable: [],
      // 成本汇总
      costItems: [
        { label: '总消费', value: 0, cls: 'consume' },
        { label: '平台成本', value: 0, cls: 'cost' },
        { label: '代理分佣', value: 0, cls: 'profit' },
        { label: '平台收益', value: 0, cls: 'revenue' }
      ],
      // 小时统计
      hourlyStats: [],
      // 代理明细弹窗
      proxyDetailVisible: false,
      detailProxyId: null,
      proxyDetailList: [],
      proxyDetailTotal: 0,
      // 租户明细弹窗
      tenantDetailVisible: false,
      detailTenantId: null,
      tenantDetailList: []
    }
  },
  created() {
    this.refreshAll()
  },
  methods: {
    dateParams() {
      const [startDate, endDate] = this.dateRange || []
      return { startDate, endDate }
    },

    /** 刷新所有数据 */
    refreshAll() {
      this.loadOverview()
      this.loadProxyProfit()
      this.loadTenantConsume()
      this.loadConsumeType()
      this.loadCostSummary()
      this.loadHourly()
    },

    resetFilter() {
      this.dateRange = []
      this.refreshAll()
    },

    /** 加载概览 */
    loadOverview() {
      getOverview().then(r => {
        const d = r.data
        this.overviewCards[0].value = d.totalTenantCount || 0
        this.overviewCards[1].value = d.totalProxyCount || 0
        this.overviewCards[2].value = this.fmt(d.todayConsume)
        this.overviewCards[3].value = this.fmt(d.todayProfit)
      })
    },

    /** 加载代理分佣列表 */
    loadProxyProfit() {
      getProxyProfitStatistics(this.dateParams()).then(r => {
        this.proxyList = r.rows || r.data || []
      })
    },

    /** 加载租户消费列表 */
    loadTenantConsume() {
      getTenantConsumeStatistics(this.dateParams()).then(r => {
        this.tenantList = r.rows || r.data || []
      })
    },

    /** 加载消费类型统计 */
    loadConsumeType() {
      getConsumeTypeStatistics(this.dateParams()).then(r => {
        const d = r.data
        const consume = d.consumeByType || {}
        const cost = d.costByType || {}
        const profit = d.profitByType || {}
        const allTypes = new Set([...Object.keys(consume), ...Object.keys(cost), ...Object.keys(profit)])
        this.typeTable = [...allTypes].map(t => ({
          type: t,
          typeName: TYPE_NAMES[t] || t,
          consume: consume[t] || 0,
          cost: cost[t] || 0,
          profit: profit[t] || 0
        }))
      })
    },

    /** 加载成本汇总 */
    loadCostSummary() {
      getCostSummary(this.dateParams()).then(r => {
        const d = r.data
        this.costItems[0].value = d.totalConsume || 0
        this.costItems[1].value = d.totalCost || 0
        this.costItems[2].value = d.totalProfit || 0
        this.costItems[3].value = d.platformRevenue || 0
      })
    },

    /** 加载小时统计 */
    loadHourly() {
      const today = this.dateRange ? this.dateRange[1] : new Date().toISOString().slice(0, 10)
      getHourlyStatistics(today).then(r => {
        this.hourlyStats = r.data || []
      }).catch(() => { /* 当天可能无数据 */ })
    },

    /** 代理分佣明细 */
    showProxyDetail(proxyId) {
      this.detailProxyId = proxyId
      getProxyProfitDetail(proxyId, this.dateParams()).then(r => {
        this.proxyDetailList = r.data.details || []
        this.proxyDetailTotal = r.data.totalProfit || 0
        this.proxyDetailVisible = true
      })
    },

    /** 租户消费明细 */
    showTenantDetail(tenantId) {
      this.detailTenantId = tenantId
      getTenantDetail(tenantId, this.dateParams()).then(r => {
        this.tenantDetailList = r.data || []
        this.tenantDetailVisible = true
      })
    },

    /** 计算单个服务的平台收益 */
    platformRevenue(row) {
      return (row.consume || 0) - (row.cost || 0) - (row.profit || 0)
    },

    /** 统一格式化金额 */
    fmt(val) {
      if (val === null || val === undefined) return '¥0.00'
      return '¥' + Number(val).toFixed(2)
    },

    dimName(d) {
      return { PROXY: '代理', TENANT: '租户', TYPE: '类型' }[d] || d
    }
  }
}
</script>

<style scoped>
/* 概览卡片 */
.overview-card { cursor: default; }
.card-inner { display: flex; align-items: center; }
.card-icon {
  width: 46px; height: 46px; border-radius: 50%;
  display: flex; align-items: center; justify-content: center;
  margin-right: 14px; font-size: 22px; color: #fff;
}
.card-value { font-size: 22px; font-weight: bold; color: #333; display: block; }
.card-label { font-size: 12px; color: #999; }

/* 筛选卡片 */
.filter-card { padding-bottom: 0; }

/* 统计面板 */
.stat-panel { margin-bottom: 16px; }
.stat-panel .header-tip { font-size: 12px; color: #999; font-weight: normal; }

/* 成本区块 */
.cost-block { text-align: center; padding: 12px 0; }
.cost-num { font-size: 20px; font-weight: bold; display: block; }
.cost-label { font-size: 12px; color: #666; margin-top: 4px; display: block; }
.cost-block.consume .cost-num { color: #1890ff; }
.cost-block.cost .cost-num { color: #fa8c16; }
.cost-block.profit .cost-num { color: #52c41a; }
.cost-block.revenue .cost-num { color: #722ed1; }

/* 颜色标识 */
.color-cost { color: #fa8c16; }
.color-profit { color: #52c41a; }
.color-revenue { color: #722ed1; }

.mb16 { margin-bottom: 16px; }
</style>