<template>
  <div class="app-container">
    <!-- ===== KPI 概览卡片 ===== -->
    <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 :model="queryParams" ref="queryForm" :inline="true" size="small">
        <el-form-item label="租户名称" prop="tenantName">
          <el-input v-model="queryParams.tenantName" placeholder="请输入租户名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="消费类型" prop="eventType">
          <el-select v-model="queryParams.eventType" placeholder="全部" clearable style="width:140px">
            <el-option label="外呼通话" value="CALL" />
            <el-option label="短信" value="SMS" />
            <el-option label="AI模型" value="AI_MODEL" />
            <el-option label="龙虾引擎" value="LOBSTER" />
            <el-option label="企微服务" value="QW_SERVICE" />
            <el-option label="个微服务" value="WX_SERVICE" />
            <el-option label="直播" value="LIVE" />
            <el-option label="课程" value="COURSE" />
            <el-option label="商品" value="PRODUCT" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>
        <el-form-item label="消费时间">
          <el-date-picker v-model="dateRange" type="daterange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期"
            value-format="yyyy-MM-dd" style="width:240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- ===== 操作栏 ===== -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <!-- ===== 消费记录列表 ===== -->
    <el-table border v-loading="loading" :data="recordList" size="small" style="width:100%">
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column label="租户ID" align="center" prop="tenantId" width="80" />
      <el-table-column label="租户名称" align="center" prop="tenantName" min-width="120" />
      <el-table-column label="消费类型" align="center" prop="eventType" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.eventType === 'CALL'" type="warning" size="mini">外呼</el-tag>
          <el-tag v-else-if="scope.row.eventType === 'SMS'" type="info" size="mini">短信</el-tag>
          <el-tag v-else-if="scope.row.eventType === 'AI_MODEL'" size="mini">AI模型</el-tag>
          <el-tag v-else-if="scope.row.eventType === 'LOBSTER'" type="success" size="mini">龙虾</el-tag>
          <el-tag v-else-if="scope.row.eventType === 'QW_SERVICE'" type="danger" size="mini">企微</el-tag>
          <el-tag v-else-if="scope.row.eventType === 'WX_SERVICE'" type="danger" size="mini">个微</el-tag>
          <el-tag v-else-if="scope.row.eventType === 'LIVE'" type="warning" size="mini">直播</el-tag>
          <el-tag v-else size="mini">{{ scope.row.eventType || '其他' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="消费金额" align="center" prop="amount" width="110">
        <template slot-scope="scope">
          <span style="color:#1890ff;font-weight:bold">¥{{ scope.row.amount || '0.00' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="扣款后余额" align="center" prop="balanceAfter" width="110">
        <template slot-scope="scope">¥{{ scope.row.balanceAfter || '0.00' }}</template>
      </el-table-column>
      <el-table-column label="计费模式" align="center" prop="billingMode" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.billingMode === 'USAGE'" type="primary" size="mini">按量</el-tag>
          <el-tag v-else-if="scope.row.billingMode === 'SUBSCRIPTION'" type="success" size="mini">套餐</el-tag>
          <span v-else>{{ scope.row.billingMode || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联业务ID" align="center" prop="bizId" width="120" show-overflow-tooltip />
      <el-table-column label="消费时间" align="center" prop="occurredAt" width="160" />
      <el-table-column label="操作" align="center" width="60" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- ===== 详情弹窗 ===== -->
    <el-dialog title="消费扣款详情" :visible.sync="detailVisible" width="550px" append-to-body>
      <el-descriptions :column="2" border size="small">
        <el-descriptions-item label="租户ID">{{ detail.tenantId }}</el-descriptions-item>
        <el-descriptions-item label="租户名称">{{ detail.tenantName }}</el-descriptions-item>
        <el-descriptions-item label="消费类型">
          <el-tag v-if="detail.eventType === 'CALL'" type="warning" size="mini">外呼通话</el-tag>
          <el-tag v-else-if="detail.eventType === 'SMS'" type="info" size="mini">短信</el-tag>
          <el-tag v-else-if="detail.eventType === 'AI_MODEL'" size="mini">AI模型</el-tag>
          <el-tag v-else-if="detail.eventType === 'LOBSTER'" type="success" size="mini">龙虾引擎</el-tag>
          <el-tag v-else size="mini">{{ detail.eventType || '-' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="消费金额">
          <span style="color:#1890ff;font-weight:bold">¥{{ detail.amount || '0.00' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="扣款后余额">¥{{ detail.balanceAfter || '0.00' }}</el-descriptions-item>
        <el-descriptions-item label="计费模式">
          <el-tag v-if="detail.billingMode === 'USAGE'" type="primary" size="mini">按量</el-tag>
          <el-tag v-else-if="detail.billingMode === 'SUBSCRIPTION'" type="success" size="mini">套餐</el-tag>
          <span v-else>{{ detail.billingMode || '-' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="关联业务ID">{{ detail.bizId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="消费时间" :span="2">{{ detail.occurredAt }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detail.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { listConsumeRecords, getConsumeRecord, exportConsumeRecord } from '@/api/admin/consumeRecord'

export default {
  name: 'AdminConsumeRecord',
  data() {
    return {
      loading: false,
      exportLoading: false,
      showSearch: true,
      total: 0,
      recordList: [],
      dateRange: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tenantName: null,
        eventType: null,
        beginTime: null,
        endTime: null
      },
      detailVisible: false,
      detail: {},
      // KPI卡片
      overviewCards: [
        { label: '消费总额', value: '¥0.00', icon: 'el-icon-wallet', bg: '#e6f7ff' },
        { label: '消费笔数', value: 0, icon: 'el-icon-document', bg: '#fff7e6' },
        { label: '涉及租户数', value: 0, icon: 'el-icon-office-building', bg: '#f6ffed' },
        { label: '代理分佣', value: '¥0.00', icon: 'el-icon-user-solid', bg: '#f9f0ff' }
      ]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.beginTime = this.dateRange[0]
        this.queryParams.endTime = this.dateRange[1]
      } else {
        this.queryParams.beginTime = null
        this.queryParams.endTime = null
      }
      listConsumeRecords(this.queryParams).then(res => {
        this.recordList = res.rows || []
        this.total = res.total || 0
        this.updateOverview(res)
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    updateOverview(res) {
      // 从后端返回的汇总信息更新KPI，若后端未提供则从前端计算
      const summary = res.summary || res.data || {}
      if (summary.totalAmount !== undefined) {
        this.overviewCards[0].value = '¥' + (summary.totalAmount || 0).toFixed(2)
        this.overviewCards[1].value = summary.totalCount || this.total
        this.overviewCards[2].value = summary.tenantCount || 0
        this.overviewCards[3].value = '¥' + (summary.totalCommission || 0).toFixed(2)
      } else {
        this.overviewCards[0].value = '¥' + this.recordList.reduce((s, r) => s + (parseFloat(r.amount) || 0), 0).toFixed(2)
        this.overviewCards[1].value = this.total
        const tenants = new Set(this.recordList.map(r => r.tenantId).filter(Boolean))
        this.overviewCards[2].value = tenants.size
        this.overviewCards[3].value = '¥0.00'
      }
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleDetail(row) {
      getConsumeRecord(row.id).then(res => {
        this.detail = res.data || {}
        this.detailVisible = true
      })
    },
    handleExport() {
      this.exportLoading = true
      exportConsumeRecord(this.queryParams).then(response => {
        this.download(response.msg)
        this.exportLoading = false
      }).catch(() => { this.exportLoading = false })
    }
  }
}
</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; }
.mb16 { margin-bottom: 16px; }
.mb8 { margin-bottom: 8px; }
</style>
