<template>
  <div class="app-container">
    <el-card shadow="never" class="mb16 filter-card">
      <el-form :inline="true" size="small">
        <el-form-item label="选择代理">
          <el-select v-model="selectedProxyId" placeholder="全部代理" clearable filterable @change="refreshAll" style="width:200px">
            <el-option v-for="p in enabledProxyList" :key="p.proxyId" :label="p.proxyName" :value="p.proxyId" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker v-model="statDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期" @change="refreshAll" style="width:160px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="refreshAll">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 概览卡片 -->
    <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-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
      <!-- Tab 1：代理下租户消费 -->
      <el-tab-pane label="租户消费明细" name="tenantConsume">
        <el-table border v-loading="loading" :data="tenantStats" size="small" style="width:100%">
          <el-table-column label="租户ID" prop="tenantId" min-width="70" align="center" />
          <el-table-column label="租户名称" min-width="120">
            <template slot-scope="s">{{ tenantNames[s.row.tenantId] || s.row.remark || '-' }}</template>
          </el-table-column>
          <el-table-column label="消费金额" align="center" min-width="110">
            <template slot-scope="s">
              <span style="color:#1890ff;font-weight:bold">{{ fmt(s.row.consumeAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="平台成本" align="center" min-width="110">
            <template slot-scope="s">
              <span style="color:#fa8c16">{{ fmt(s.row.platformCost) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="租户售价" align="center" min-width="110">
            <template slot-scope="s">{{ fmt(s.row.tenantPrice) }}</template>
          </el-table-column>
          <el-table-column label="利润(售价-成本)" align="center" min-width="120">
            <template slot-scope="s">
              <span style="color:#52c41a;font-weight:bold">
                {{ fmt((s.row.tenantPrice || 0) - (s.row.platformCost || 0)) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="代理分佣" align="center" min-width="110">
            <template slot-scope="s">
              <span style="color:#722ed1;font-weight:bold">{{ fmt(s.row.proxyProfit) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单数" prop="orderCount" min-width="70" align="center" />
        </el-table>
        <el-empty v-if="!loading && tenantStats.length === 0" description="暂无数据" :image-size="80" />
      </el-tab-pane>

      <!-- Tab 2：服务类型利润 -->
      <el-tab-pane label="服务类型利润" name="typeProfit">
        <el-table border v-loading="loading" :data="typeStats" size="small" style="width:100%">
          <el-table-column label="服务类型" min-width="130">
            <template slot-scope="s">
              <el-tag :type="typeTag(s.row.consumeType)">{{ typeName(s.row.consumeType) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="消费金额" align="center" min-width="110">
            <template slot-scope="s">
              <span style="color:#1890ff;font-weight:bold">{{ fmt(s.row.consumeAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="平台成本" align="center" min-width="110">
            <template slot-scope="s">
              <span style="color:#fa8c16">{{ fmt(s.row.platformCost) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="利润" align="center" min-width="110">
            <template slot-scope="s">
              <span style="color:#52c41a;font-weight:bold">
                {{ fmt((s.row.consumeAmount || 0) - (s.row.platformCost || 0)) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="代理分佣" align="center" min-width="110">
            <template slot-scope="s">
              <span style="color:#722ed1">{{ fmt(s.row.proxyProfit) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="平台收益" align="center" min-width="110">
            <template slot-scope="s">
              <b style="color:#333">
                {{ fmt((s.row.tenantPrice || 0) - (s.row.platformCost || 0) - (s.row.proxyProfit || 0)) }}
              </b>
            </template>
          </el-table-column>
          <el-table-column label="订单数" prop="orderCount" min-width="70" align="center" />
        </el-table>
        <el-empty v-if="!loading && typeStats.length === 0" description="暂无数据" :image-size="80" />
      </el-tab-pane>

      <!-- Tab 3：代理汇总 -->
      <el-tab-pane label="代理汇总" name="agentSummary">
        <el-table border v-loading="loading" :data="agentStats" size="small" style="width:100%">
          <el-table-column label="代理ID" prop="proxyId" min-width="70" align="center" />
          <el-table-column label="代理名称" min-width="120">
            <template slot-scope="s">{{ proxyNames[s.row.proxyId] || '-' }}</template>
          </el-table-column>
          <el-table-column label="消费金额" align="center" min-width="110">
            <template slot-scope="s">
              <span style="color:#1890ff;font-weight:bold">{{ fmt(s.row.consumeAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="平台成本" align="center" min-width="110">
            <template slot-scope="s">
              <span style="color:#fa8c16">{{ fmt(s.row.platformCost) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="总利润" align="center" min-width="110">
            <template slot-scope="s">
              <span style="color:#52c41a;font-weight:bold">
                {{ fmt((s.row.tenantPrice || 0) - (s.row.platformCost || 0)) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="代理分佣" align="center" min-width="110">
            <template slot-scope="s">
              <span style="color:#722ed1;font-weight:bold">{{ fmt(s.row.proxyProfit) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单数" prop="orderCount" min-width="70" align="center" />
        </el-table>
        <el-empty v-if="!loading && agentStats.length === 0" description="暂无数据" :image-size="80" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { allEnabledProxies } from '@/api/admin/proxy'
import { getDailyAgentTenants, getDailyServiceTypeProfit, getDailyAgentSummary } from '@/api/admin/dailyStatistics'

const TYPE_MAP = {
  'COURSE': '课程流量费', 'LIVE': '直播流量费', 'AI_TOKEN': 'AI TOKEN',
  'SMS': '短信发送', 'MANUAL_CALL': '手拨外呼', 'AI_CALL': 'AI智能外呼',
  'MICRO_ASSISTANT': '微助手', 'ACCOUNT_FEE': '账户费',
  'AI_MODEL': 'AI模型训练'
}
const TYPE_TAGS = {
  'COURSE': '', 'LIVE': 'warning', 'AI_TOKEN': 'info', 'SMS': 'info',
  'MANUAL_CALL': 'warning', 'AI_CALL': 'warning', 'MICRO_ASSISTANT': 'success',
  'ACCOUNT_FEE': 'danger', 'AI_MODEL': ''
}

export default {
  name: 'AdminDailyStatistics',
  data() {
    return {
      activeTab: 'tenantConsume',
      selectedProxyId: null,
      statDate: new Date().toISOString().slice(0, 10),
      loading: false,
      enabledProxyList: [],
      // Cards
      overviewCards: [
        { label: '总消费', value: '¥0.00', icon: 'el-icon-wallet', bg: '#e6f7ff' },
        { label: '平台成本', value: '¥0.00', icon: 'el-icon-coins', bg: '#fff7e6' },
        { label: '总利润', value: '¥0.00', icon: 'el-icon-data-line', bg: '#f6ffed' },
        { label: '代理分佣', value: '¥0.00', icon: 'el-icon-user-solid', bg: '#f9f0ff' }
      ],
      // Tab data
      tenantStats: [],
      tenantNames: {},
      typeStats: [],
      agentStats: [],
      proxyNames: {}
    }
  },
  created() {
    this.loadProxies()
    this.refreshAll()
  },
  methods: {
    fmt(val) {
      if (val === null || val === undefined) return '¥0.00'
      return '¥' + Number(val).toFixed(2)
    },
    typeName(t) { return TYPE_MAP[t] || t || '-' },
    typeTag(t) { return TYPE_TAGS[t] || '' },

    loadProxies() {
      allEnabledProxies().then(r => { this.enabledProxyList = r.data || [] })
    },

    resetQuery() {
      this.selectedProxyId = null
      this.statDate = new Date().toISOString().slice(0, 10)
      this.refreshAll()
    },

    handleTabClick() { this.refreshAll() },

    refreshAll() {
      const params = { statDate: this.statDate }
      if (this.selectedProxyId) params.proxyId = this.selectedProxyId

      this.loadTenantConsume(params)
      this.loadTypeProfit(params)
      this.loadAgentSummary()
    },

    loadTenantConsume(params) {
      this.tenantStats = []
      getDailyAgentTenants(params).then(r => {
        const d = r.data
        this.tenantStats = d.items || []
        this.tenantNames = d.tenantNames || {}
        this.overviewCards[0].value = this.fmt(d.totalConsume)
        this.overviewCards[1].value = this.fmt(d.totalCost)
        this.overviewCards[2].value = this.fmt(d.totalProfit)
        this.overviewCards[3].value = this.fmt(d.totalAgentProfit)
      }).catch(() => { this.tenantStats = [] })
    },

    loadTypeProfit(params) {
      this.typeStats = []
      getDailyServiceTypeProfit(params).then(r => {
        this.typeStats = r.data.items || []
      }).catch(() => { this.typeStats = [] })
    },

    loadAgentSummary() {
      this.agentStats = []
      getDailyAgentSummary({ statDate: this.statDate }).then(r => {
        const d = r.data
        this.agentStats = d.items || []
        this.proxyNames = d.proxyNames || {}
      }).catch(() => { this.agentStats = [] })
    }
  }
}
</script>

<style scoped>
.filter-card { padding-bottom: 0; }
.mb16 { margin-bottom: 16px; }

.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; }
</style>
