<template>
  <div class="dashboard-page">
    <!-- 顶栏 -->
    <header class="dash-header">
      <div class="header-left">
        <h1 class="live-title">{{ liveName || '直播实时大屏' }}</h1>
        <div class="meta-tags">
          <span class="tag" v-if="startTime">
            <i class="el-icon-time"></i> 开播 {{ formatTime(startTime) }}
          </span>
          <span class="tag tag-live" v-if="!liveDataFrozen">直播中</span>
          <span class="tag tag-frozen" v-if="liveDataFrozen">直播数据已冻结</span>
          <span class="tag tag-frozen" v-if="replayDataFrozen && liveStatus === 4">回放数据已冻结</span>
        </div>
      </div>
      <div class="header-right">
        <span class="refresh-tip">{{ lastRefreshText }}</span>
        <el-button type="primary" size="small" icon="el-icon-refresh" :loading="loading" @click="refreshData">
          刷新数据
        </el-button>
      </div>
    </header>

    <!-- 互动指标 -->
    <section class="section">
      <div class="section-title">实时互动</div>
      <div class="metric-grid metric-grid-4">
        <div class="metric-card accent-blue" v-for="item in interactionCards" :key="item.label">
          <div class="metric-icon">{{ item.icon }}</div>
          <div class="metric-body">
            <div class="metric-label">{{ item.label }}</div>
            <div class="metric-value">{{ item.value }}</div>
            <div class="metric-sub" v-if="item.sub">{{ item.sub }}</div>
          </div>
        </div>
      </div>
    </section>

    <!-- 订单整体数据 -->
    <section class="section">
      <div class="section-title">订单整体数据</div>
      <div class="metric-grid metric-grid-4">
        <div class="metric-card" v-for="item in orderCards" :key="item.label">
          <div class="metric-label">{{ item.label }}</div>
          <div class="metric-value" :class="{ money: item.isMoney }">{{ item.value }}</div>
        </div>
      </div>
    </section>

    <!-- 商品数据 + 邀请榜 -->
    <section class="section section-split">
      <div class="panel product-panel">
        <div class="section-title">商品数据</div>
        <el-table
          :data="productStats"
          size="small"
          height="320"
          class="dark-table"
          empty-text="暂无商品订单数据">
          <el-table-column prop="productName" label="商品" min-width="120" show-overflow-tooltip />
          <el-table-column prop="totalOrderCount" label="累计下单" width="80" align="center" />
          <el-table-column label="累计金额" width="100" align="right">
            <template slot-scope="{ row }">{{ formatMoney(row.totalOrderAmount) }}</template>
          </el-table-column>
          <el-table-column prop="paidOrderCount" label="成交数" width="70" align="center" />
          <el-table-column label="成交额" width="100" align="right">
            <template slot-scope="{ row }">{{ formatMoney(row.paidOrderAmount) }}</template>
          </el-table-column>
          <el-table-column prop="unpaidOrderCount" label="待支付" width="70" align="center" />
          <el-table-column prop="refundApplyCount" label="退款申请" width="80" align="center" />
        </el-table>
      </div>

      <div class="panel rank-panel">
        <div class="section-title">
          销售邀请榜
          <span class="invite-total">共 {{ totalInviteCount }} 人</span>
        </div>
        <ul class="rank-list" v-if="rankList.length">
          <li v-for="(item, index) in rankList" :key="index" class="rank-item">
            <span class="rank-badge" :class="'rank-' + (index + 1)">{{ index + 1 }}</span>
            <span class="rank-name">{{ item.userName || '未知销售' }}</span>
            <span class="rank-count">{{ item.inviteNum }} 人</span>
          </li>
        </ul>
        <div class="empty-rank" v-else>暂无邀请数据</div>
      </div>
    </section>
  </div>
</template>

<script>
import { dashboardData } from '@/api/live/liveData'

export default {
  props: {
    liveId: { type: String, default: null }
  },
  data() {
    return {
      loading: false,
      liveName: '',
      startTime: null,
      liveStatus: null,
      liveDataFrozen: false,
      replayDataFrozen: false,
      totalInviteCount: 0,
      interactionCards: [],
      orderCards: [],
      productStats: [],
      rankList: [],
      lastRefreshAt: null,
      nowTick: Date.now(),
      timer: null,
      tickTimer: null
    }
  },
  computed: {
    lastRefreshText() {
      if (!this.lastRefreshAt) return '等待首次加载'
      const diff = Math.max(0, Math.floor((this.nowTick - this.lastRefreshAt) / 1000))
      if (diff < 60) return `${diff} 秒前更新`
      return `${Math.floor(diff / 60)} 分钟前更新`
    }
  },
  created() {
    this.refreshData()
    this.timer = setInterval(() => this.refreshData(), 30000)
    this.tickTimer = setInterval(() => {
      this.nowTick = Date.now()
    }, 1000)
  },
  beforeDestroy() {
    if (this.timer) clearInterval(this.timer)
    if (this.tickTimer) clearInterval(this.tickTimer)
  },
  methods: {
    refreshData() {
      if (!this.liveId) return
      this.loading = true
      dashboardData(this.liveId).then(res => {
        if (res.code === 200 && res.data) {
          this.applyData(res.data)
          this.lastRefreshAt = Date.now()
        }
      }).finally(() => {
        this.loading = false
      })
    },
    applyData(data) {
      this.liveName = data.liveName || ''
      this.startTime = data.startTime || null
      this.liveStatus = data.liveStatus
      this.liveDataFrozen = !!data.liveDataFrozen
      this.replayDataFrozen = !!data.replayDataFrozen
      this.totalInviteCount = data.totalInviteCount || 0
      this.rankList = data.inviteUserList || []
      this.productStats = data.productStats || []

      const totalView = (data.liveViewNum || 0) + (data.replayViewNum || 0)
      const totalLike = (data.liveLikeNum || 0) + (data.replayLikeNum || 0)
      const totalComment = Number(data.liveCommentNum || 0) + Number(data.replayCommentNum || 0)

      this.interactionCards = [
        { icon: '👁', label: '实时在线', value: data.onlineNum || 0, sub: `离线 ${data.offlineNum || 0}` },
        { icon: '📊', label: '累计观看人数', value: data.uniqueViewCount || 0, sub: `人次 ${totalView}` },
        { icon: '👍', label: '累计点赞', value: totalLike, sub: `直播 ${data.liveLikeNum || 0} / 回放 ${data.replayLikeNum || 0}` },
        { icon: '💬', label: '累计评论', value: totalComment, sub: `直播 ${data.liveCommentNum || 0} / 回放 ${data.replayCommentNum || 0}` }
      ]

      const os = data.orderStats || {}
      this.orderCards = [
        { label: '累计下单数', value: os.totalOrderCount || 0 },
        { label: '累计下单金额', value: this.formatMoney(os.totalOrderAmount), isMoney: true },
        { label: '现存成交订单数', value: os.paidOrderCount || 0 },
        { label: '现存成交额', value: this.formatMoney(os.paidOrderAmount), isMoney: true },
        { label: '申请退款订单数', value: os.refundApplyCount || 0 },
        { label: '申请退款金额', value: this.formatMoney(os.refundApplyAmount), isMoney: true },
        { label: '待支付订单数', value: os.unpaidOrderCount || 0 },
        { label: '待支付金额', value: this.formatMoney(os.unpaidOrderAmount), isMoney: true }
      ]
    },
    formatMoney(val) {
      const num = Number(val || 0)
      return '¥' + num.toFixed(2)
    },
    formatTime(val) {
      if (!val) return '-'
      const d = new Date(val)
      if (isNaN(d.getTime())) return val
      const p = n => String(n).padStart(2, '0')
      return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
    }
  }
}
</script>

<style scoped>
.dashboard-page {
  min-height: 92vh;
  background: #f5f8fc;
  color: #334155;
  padding: 20px 24px;
  box-sizing: border-box;
  overflow-y: auto;
}

.dash-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 14px;
  border-bottom: 1px solid #e8eef5;
}

.live-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 8px;
  color: #1e293b;
}

.meta-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.tag {
  font-size: 12px;
  padding: 3px 10px;
  border-radius: 20px;
  background: #eef2f7;
  color: #64748b;
}

.tag-live {
  background: #ecfdf5;
  color: #059669;
}

.tag-frozen {
  background: #fffbeb;
  color: #d97706;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.refresh-tip {
  font-size: 12px;
  color: #94a3b8;
}

.section {
  margin-bottom: 18px;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #64748b;
  margin-bottom: 12px;
  letter-spacing: 0.3px;
}

.section-split {
  display: grid;
  grid-template-columns: 1fr 340px;
  gap: 16px;
}

.metric-grid {
  display: grid;
  gap: 12px;
}

.metric-grid-4 {
  grid-template-columns: repeat(4, 1fr);
}

@media (max-width: 1200px) {
  .metric-grid-4 { grid-template-columns: repeat(2, 1fr); }
  .section-split { grid-template-columns: 1fr; }
}

.metric-card {
  background: #fff;
  border: 1px solid #e8eef5;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 1px 2px rgba(15, 23, 42, 0.03);
  transition: border-color 0.2s, box-shadow 0.2s;
}

.metric-card:hover {
  border-color: #c7d7fe;
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.08);
}

.metric-card.accent-blue {
  display: flex;
  align-items: center;
  gap: 12px;
}

.metric-icon {
  font-size: 28px;
  line-height: 1;
}

.metric-label {
  font-size: 12px;
  color: #94a3b8;
  margin-bottom: 6px;
}

.metric-value {
  font-size: 24px;
  font-weight: 700;
  color: #1e293b;
  line-height: 1.2;
}

.metric-value.money {
  color: #ea580c;
}

.metric-sub {
  font-size: 11px;
  color: #94a3b8;
  margin-top: 4px;
}

.panel {
  background: #fff;
  border: 1px solid #e8eef5;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 1px 2px rgba(15, 23, 42, 0.03);
}

.invite-total {
  font-size: 12px;
  font-weight: 400;
  color: #4f46e5;
  margin-left: 8px;
}

.rank-list {
  list-style: none;
  padding: 0;
  margin: 0;
  max-height: 320px;
  overflow-y: auto;
}

.rank-item {
  display: flex;
  align-items: center;
  padding: 10px 8px;
  border-bottom: 1px solid #f1f5f9;
  font-size: 13px;
}

.rank-badge {
  width: 24px;
  height: 24px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 700;
  background: #f1f5f9;
  color: #64748b;
  flex-shrink: 0;
}

.rank-1 { background: #fef3c7; color: #b45309; }
.rank-2 { background: #e2e8f0; color: #475569; }
.rank-3 { background: #ffedd5; color: #c2410c; }

.rank-name {
  flex: 1;
  margin: 0 12px;
  color: #334155;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.rank-count {
  color: #4f46e5;
  font-weight: 600;
}

.empty-rank {
  text-align: center;
  color: #94a3b8;
  padding: 40px 0;
  font-size: 13px;
}

.dark-table {
  background: transparent !important;
}

.dark-table >>> .el-table {
  background: transparent;
  color: #334155;
}

.dark-table >>> .el-table th {
  background: #f8fafc !important;
  color: #64748b;
  border-bottom: 1px solid #e8eef5;
}

.dark-table >>> .el-table td {
  background: #fff !important;
  border-bottom: 1px solid #f1f5f9;
}

.dark-table >>> .el-table tr {
  background: #fff !important;
}

.dark-table >>> .el-table--enable-row-hover .el-table__body tr:hover > td {
  background: #f8fafc !important;
}

.dark-table >>> .el-table::before {
  display: none;
}
</style>
