<template>
  <main class="commercial-workspace" aria-labelledby="commercial-workspace-title">
    <header class="commercial-hero">
      <div>
        <span class="commercial-eyebrow">Commercial control & value proof</span>
        <h2 id="commercial-workspace-title">商业化管理与价值证明</h2>
        <p>把套餐、订阅、权益、用量、成本和企业节省放进可追溯闭环，同时保持客户价值账与平台经营账严格分离。</p>
        <div class="commercial-trust-row">
          <span><i class="mdi mdi-shield-lock-outline" aria-hidden="true"></i>租户隔离</span>
          <span><i class="mdi mdi-source-branch" aria-hidden="true"></i>版本化配置</span>
          <span><i class="mdi mdi-database-lock-outline" aria-hidden="true"></i>不可变计量</span>
          <span><i class="mdi mdi-currency-usd-off" aria-hidden="true"></i>币种不混算</span>
        </div>
      </div>
      <form v-if="platformAdmin" class="commercial-tenant-picker" @submit.prevent="applyTenant">
        <label for="commercial-tenant-id">目标租户 ID</label>
        <div>
          <input id="commercial-tenant-id" v-model.trim="tenantDraft" maxlength="64" autocomplete="off" placeholder="输入需要管理的租户 ID" />
          <button type="submit" class="commercial-button primary" :disabled="!tenantDraft || tenantDraft === activeTenantId">加载租户</button>
        </div>
        <small>平台管理员必须显式选择租户，避免误操作默认上下文。</small>
      </form>
      <div v-else class="commercial-readonly-badge">
        <i class="mdi mdi-account-check-outline" aria-hidden="true"></i>
        <div><strong>当前租户只读账户</strong><span>平台内部经营数据不会越权下发</span></div>
      </div>
    </header>

    <div v-if="platformAdmin && !activeTenantId" class="commercial-empty-workspace" role="status">
      <i class="mdi mdi-domain-plus" aria-hidden="true"></i>
      <strong>请先选择目标租户</strong>
      <span>输入租户 ID 后，系统才会读取该租户的商业账户、双账分析和可执行操作。</span>
    </div>

    <template v-else>
      <div class="commercial-safety-banner" role="note">
        <i class="mdi mdi-shield-alert-outline" aria-hidden="true"></i>
        <div><strong>商业权益不能放宽安全规则</strong><span>即使配额充足，高风险审批、支付和其他安全门禁仍可要求人工复核或直接拒绝。</span></div>
      </div>

      <CommercialAccountOverview
        :account="account"
        :state="accountState"
        :error="accountError"
        :loading="accountLoading"
        :quota-rows="quotaRows"
        @retry="retryAccount"
      />

      <CommercialValueProofPanel
        :analytics="analytics"
        :ledgers="ledgers"
        :loading="analyticsLoading"
        :error="analyticsError"
        :platform-admin="platformAdmin"
        :range="range"
        @reload="retryAnalytics"
        @update-range="updateRange"
      />

      <CommercialPricingScenarioPanel
        :tenant-id="activeTenantId"
        :platform-admin="platformAdmin"
        :range="range"
        :view="pricingScenarioView"
        :loading="pricingLoading"
        :error="pricingError"
        :execute="calculatePricingScenario"
      />

      <CommercialHistoryPanel
        :platform-admin="platformAdmin"
        :history="history"
        :loaded="historyLoaded"
        :loading="historyLoading"
        :error="historyError"
        @load="loadHistory"
        @manage-subscription="openSubscriptionAction"
      />

      <CommercialAdminConsole
        ref="adminConsoleRef"
        :can-manage="canManage"
        :account="account"
        :busy="mutationLoading"
        :error="mutationError"
        :message="mutationMessage"
        :execute="executeMutation"
      />
    </template>
  </main>
</template>

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

import { useCommercialWorkspace } from '../../composables/useCommercialWorkspace.js'
import { isPlatformAdminUser } from '../../utils/accessControl.js'
import CommercialAccountOverview from './CommercialAccountOverview.vue'
import CommercialAdminConsole from './CommercialAdminConsole.vue'
import CommercialHistoryPanel from './CommercialHistoryPanel.vue'
import CommercialPricingScenarioPanel from './CommercialPricingScenarioPanel.vue'
import CommercialValueProofPanel from './CommercialValueProofPanel.vue'
import './commercial-workspace.css'

const props = defineProps({
  tenantId: { type: String, default: '' },
  currentUser: { type: Object, default: () => ({}) },
  active: { type: Boolean, default: true }
})
const emit = defineEmits(['update:tenant-id'])
const platformAdmin = computed(() => isPlatformAdminUser(props.currentUser))
const tenantDraft = ref(String(props.tenantId || '').trim())
const activeTenantId = ref(String(props.tenantId || '').trim())
const adminConsoleRef = ref(null)
const workspaceActive = computed(() => props.active && (!platformAdmin.value || Boolean(activeTenantId.value)))

const {
  account,
  accountLoading,
  accountError,
  accountState,
  analytics,
  analyticsLoading,
  analyticsError,
  mutationLoading,
  mutationError,
  mutationMessage,
  pricingScenarioView,
  pricingLoading,
  pricingError,
  history,
  historyLoading,
  historyError,
  historyLoaded,
  range,
  canManage,
  quotaRows,
  ledgers,
  loadAccount,
  loadAnalytics,
  loadHistory,
  calculatePricingScenario,
  executeMutation
} = useCommercialWorkspace({
  tenantId: activeTenantId,
  platformAdmin,
  active: workspaceActive
})

watch(() => props.tenantId, (value) => {
  const normalized = String(value || '').trim()
  tenantDraft.value = normalized
  activeTenantId.value = normalized
})

function applyTenant() {
  const normalized = tenantDraft.value.trim()
  if (!normalized) return
  activeTenantId.value = normalized
  emit('update:tenant-id', normalized)
}

function updateRange(nextRange) {
  Object.assign(range, nextRange)
}

function retryAccount() {
  return loadAccount().catch(() => null)
}

function retryAnalytics() {
  return loadAnalytics().catch(() => null)
}

function openSubscriptionAction(command) {
  adminConsoleRef.value?.openAction?.(command.kind, command.form)
}
</script>
