<template>
  <section class="commercial-section commercial-history-section" aria-labelledby="commercial-history-title">
    <header class="commercial-section-head">
      <div>
        <span>Audit-ready history</span>
        <h3 id="commercial-history-title">商业版本与事实历史</h3>
        <p>套餐、订阅和权益保留版本；当前按服务器倒序加载配置最多 100/200 条、事件最多 200 条，不伪装成全量导出。</p>
      </div>
      <button type="button" class="commercial-button secondary" :disabled="loading || !platformAdmin" @click="$emit('load')">
        <i :class="loading ? 'mdi mdi-loading mdi-spin' : 'mdi mdi-history'" aria-hidden="true"></i>
        {{ loading ? '加载中' : loaded ? '刷新历史' : '加载历史' }}
      </button>
    </header>

    <div v-if="!platformAdmin" class="commercial-state-card permission" role="status">
      <i class="mdi mdi-shield-lock-outline" aria-hidden="true"></i>
      <div><strong>商业历史仅向平台管理员开放</strong><span>租户普通用户不会收到平台成本、其他版本或内部计量元数据。</span></div>
    </div>
    <div v-else-if="loading && !loaded" class="commercial-state-card" role="status" aria-live="polite">
      <i class="mdi mdi-loading mdi-spin" aria-hidden="true"></i>
      <div><strong>正在加载五类商业历史</strong><span>套餐、订阅、权益、用量和成本分别从租户隔离接口读取。</span></div>
    </div>
    <div v-else-if="!loaded" class="commercial-history-empty" role="status">
      <i class="mdi mdi-history" aria-hidden="true"></i>
      <strong>历史记录按需加载</strong>
      <span>点击“加载历史”查看服务器真实版本和事件；页面不会生成示例记录。</span>
      <button type="button" class="commercial-button secondary" @click="$emit('load')">加载历史</button>
    </div>

    <template v-else>
      <div v-if="error" class="commercial-operation-feedback danger" role="alert">
        <i class="mdi mdi-alert-circle-outline" aria-hidden="true"></i>{{ error.message }}
      </div>
      <div class="commercial-history-tabs" role="group" aria-label="商业历史类型">
        <button
          v-for="tab in tabs"
          :key="tab.key"
          type="button"
          :aria-pressed="activeTab === tab.key ? 'true' : 'false'"
          :class="{ active: activeTab === tab.key }"
          @click="activeTab = tab.key"
        >{{ tab.label }} <span>{{ history[tab.key]?.length || 0 }}</span></button>
      </div>

      <div v-if="!activeRows.length" class="commercial-table-empty commercial-history-table-empty" role="status">
        <i class="mdi mdi-database-off-outline" aria-hidden="true"></i>
        <span>{{ activeTabLabel }}暂无服务器记录；这不是零用量或零成本。</span>
      </div>
      <div v-else class="commercial-table-wrap commercial-history-table">
        <table v-if="activeTab === 'plans'">
          <thead><tr><th scope="col">套餐</th><th scope="col">状态</th><th scope="col">计价</th><th scope="col">费用</th><th scope="col">版本</th><th scope="col">创建时间</th></tr></thead>
          <tbody><tr v-for="item in activeRows" :key="item.id"><td><strong>{{ item.name }}</strong><small>{{ item.planCode }}</small></td><td><span :class="['commercial-status-pill', item.status]">{{ statusLabel(item.status) }}</span></td><td>{{ item.pricingModel }}<small>{{ item.billingInterval }}</small></td><td class="numeric">{{ formatCurrencyAmount(item.baseFee, item.currency) }}</td><td>v{{ item.version }}</td><td>{{ formatDateTime(item.createdAt) }}</td></tr></tbody>
        </table>

        <table v-else-if="activeTab === 'subscriptions'">
          <thead><tr><th scope="col">订阅</th><th scope="col">状态</th><th scope="col">当前周期</th><th scope="col">席位</th><th scope="col">版本</th><th scope="col">操作</th></tr></thead>
          <tbody><tr v-for="item in activeRows" :key="item.id"><td><strong>{{ item.subscriptionKey }}</strong><small>{{ item.id }}</small></td><td><span :class="['commercial-status-pill', item.status]">{{ statusLabel(item.status) }}</span><small v-if="latestStatusReason(item)">{{ latestStatusReason(item) }}</small></td><td>{{ formatDateTime(item.currentPeriodStart) }}<small>至 {{ formatDateTime(item.currentPeriodEnd) }}</small></td><td class="numeric">{{ item.seats }}</td><td>v{{ item.version }}</td><td><div class="commercial-history-actions"><button v-if="canRestore(item)" type="button" @click="manageSubscription('activateSubscription', item)">恢复</button><button v-if="canTransition(item)" type="button" @click="manageSubscription('transitionSubscription', item)">变更状态</button><span v-if="!canRestore(item) && !canTransition(item)">终态</span></div></td></tr></tbody>
        </table>

        <table v-else-if="activeTab === 'entitlements'">
          <thead><tr><th scope="col">权益</th><th scope="col">指标</th><th scope="col">类型</th><th scope="col">状态</th><th scope="col">版本</th><th scope="col">创建时间</th></tr></thead>
          <tbody><tr v-for="item in activeRows" :key="item.id"><td><strong>{{ item.entitlementKey }}</strong><small>{{ item.id }}</small></td><td>{{ item.metricKey }}<small>{{ item.unit }}</small></td><td>{{ item.entitlementType }}</td><td><span :class="['commercial-status-pill', item.status]">{{ statusLabel(item.status) }}</span></td><td>v{{ item.version }}</td><td>{{ formatDateTime(item.createdAt) }}</td></tr></tbody>
        </table>

        <table v-else-if="activeTab === 'usageEvents'">
          <thead><tr><th scope="col">事件</th><th scope="col">指标</th><th scope="col">数量</th><th scope="col">来源</th><th scope="col">幂等键</th><th scope="col">发生时间</th></tr></thead>
          <tbody><tr v-for="item in activeRows" :key="item.id"><td><strong>{{ item.eventType }}</strong><small>{{ item.id }}</small></td><td>{{ item.metricKey }}</td><td class="numeric">{{ item.quantity }} {{ item.unit }}</td><td>{{ item.sourceSystem }}</td><td class="commercial-mono">{{ item.idempotencyKey }}</td><td>{{ formatDateTime(item.occurredAt) }}</td></tr></tbody>
        </table>

        <table v-else>
          <thead><tr><th scope="col">成本</th><th scope="col">数量</th><th scope="col">报告金额</th><th scope="col">提供商</th><th scope="col">幂等键</th><th scope="col">发生时间</th></tr></thead>
          <tbody><tr v-for="item in activeRows" :key="item.id"><td><strong>{{ item.costCategory }}</strong><small>{{ item.eventType }} · {{ item.id }}</small></td><td class="numeric">{{ item.quantity }} {{ item.unit }}</td><td class="numeric">{{ formatCurrencyAmount(item.reportingAmount, item.reportingCurrency) }}<small>原币 {{ item.originalCurrency }} · 汇率 {{ item.fxRate }}</small></td><td>{{ item.provider || '—' }}</td><td class="commercial-mono">{{ item.idempotencyKey }}</td><td>{{ formatDateTime(item.occurredAt) }}</td></tr></tbody>
        </table>
      </div>
    </template>
  </section>
</template>

<script setup>
import { computed, ref } from 'vue'

import { formatCurrencyAmount, statusLabel } from './commercialWorkspaceModel.js'

const props = defineProps({
  platformAdmin: { type: Boolean, default: false },
  history: { type: Object, required: true },
  loaded: { type: Boolean, default: false },
  loading: { type: Boolean, default: false },
  error: { type: Object, default: null }
})
const emit = defineEmits(['load', 'manage-subscription'])
const tabs = [
  { key: 'plans', label: '套餐版本' },
  { key: 'subscriptions', label: '订阅历史' },
  { key: 'entitlements', label: '权益版本' },
  { key: 'usageEvents', label: '用量事件' },
  { key: 'costEvents', label: '成本事件' }
]
const activeTab = ref('plans')
const activeRows = computed(() => Array.isArray(props.history[activeTab.value]) ? props.history[activeTab.value] : [])
const activeTabLabel = computed(() => tabs.find((item) => item.key === activeTab.value)?.label || '当前分类')

function formatDateTime(value) {
  const date = new Date(value)
  return Number.isFinite(date.getTime()) ? date.toLocaleString('zh-CN', { hour12: false }) : '—'
}

function latestStatusReason(item) {
  const rows = item?.metadataJson?.statusHistory
  return Array.isArray(rows) && rows.length ? String(rows.at(-1)?.reason || '') : ''
}

function canRestore(item) {
  return ['past_due', 'suspended'].includes(item.status)
}

function canTransition(item) {
  return !['canceled', 'expired'].includes(item.status)
}

function manageSubscription(kind, item) {
  emit('manage-subscription', {
    kind,
    form: { resourceId: item.id, expectedVersion: item.version, currentStatus: item.status }
  })
}
</script>
