<template>
  <section
    class="commercial-section commercial-pricing-section"
    aria-labelledby="commercial-pricing-title"
    :aria-busy="loading ? 'true' : 'false'"
  >
    <header class="commercial-section-head">
      <div>
        <span>Pricing corridor</span>
        <h3 id="commercial-pricing-title">可持续定价场景</h3>
        <p>用真实内部成本确定价格下限，用财务确认现金节省确定价值上限；结果只用于谈判，不会自动写入套餐。</p>
      </div>
      <span :class="['commercial-pricing-access', platformAdmin ? 'allowed' : 'denied']">
        <i :class="platformAdmin ? 'mdi mdi-calculator-variant-outline' : 'mdi mdi-shield-lock-outline'" aria-hidden="true"></i>
        {{ platformAdmin ? '平台管理员可计算' : '无计算权限' }}
      </span>
    </header>

    <div v-if="!platformAdmin" class="commercial-state-card permission" role="status">
      <i class="mdi mdi-shield-account-outline" aria-hidden="true"></i>
      <div>
        <strong>定价场景仅向平台管理员开放</strong>
        <span>该结果包含平台内部成本和单位经济性，普通租户账号不会收到这些数据。</span>
      </div>
    </div>

    <template v-else>
      <div v-if="loading" class="commercial-operation-feedback pricing-progress" role="status" aria-live="polite">
        <i class="mdi mdi-loading mdi-spin" aria-hidden="true"></i>
        正在按币种核对成本与已确认价值；已有结果会保留到本次计算成功。
      </div>
      <div v-if="error" ref="errorSummary" class="commercial-operation-feedback danger" role="alert" tabindex="-1">
        <i class="mdi mdi-alert-circle-outline" aria-hidden="true"></i>
        <span>
          <strong>定价场景计算失败</strong>
          {{ view ? '当前继续显示上一次成功结果。' : '' }}{{ error.message || '请核对输入和权限后重试。' }}
        </span>
      </div>

      <form v-if="step === 'edit'" class="commercial-pricing-form" @submit.prevent="reviewPricing">
        <fieldset :disabled="loading">
          <legend>计算参数</legend>
          <div class="commercial-pricing-fields">
            <label for="commercial-pricing-start">
              <span>分析开始日期 *</span>
              <input id="commercial-pricing-start" v-model="draft.start" type="date" required />
            </label>
            <label for="commercial-pricing-end">
              <span>分析结束日期 *</span>
              <input id="commercial-pricing-end" v-model="draft.end" type="date" required />
            </label>
            <label for="commercial-pricing-as-of">
              <span>证据截止时间（as_of）*</span>
              <input id="commercial-pricing-as-of" v-model="draft.asOf" type="datetime-local" required />
              <small>只使用此时点前可追溯、已确认的真实事实。</small>
            </label>
            <label for="commercial-pricing-margin">
              <span>目标贡献毛利率 *</span>
              <div class="commercial-percent-input">
                <input
                  id="commercial-pricing-margin"
                  v-model.trim="draft.targetContributionMarginPercent"
                  type="number"
                  inputmode="decimal"
                  min="0"
                  max="94.9999"
                  step="0.1"
                  required
                />
                <span aria-hidden="true">%</span>
              </div>
              <small>必须大于等于 0 且小于 95%。</small>
            </label>
            <label for="commercial-pricing-share">
              <span>最大价值分享比例 *</span>
              <div class="commercial-percent-input">
                <input
                  id="commercial-pricing-share"
                  v-model.trim="draft.maxVerifiedSavingsSharePercent"
                  type="number"
                  inputmode="decimal"
                  min="0.000001"
                  max="100"
                  step="0.1"
                  required
                />
                <span aria-hidden="true">%</span>
              </div>
              <small>只作用于财务确认现金节省，不包含预计机会或风险暴露。</small>
            </label>
          </div>
        </fieldset>
        <p v-if="localError" ref="localErrorSummary" class="commercial-form-error" role="alert" tabindex="-1">
          {{ localError }}
        </p>
        <footer class="commercial-pricing-form-actions">
          <span>单次分析最长 731 天；所有金额按原币种分别计算。</span>
          <button type="submit" class="commercial-button primary" :disabled="loading">
            <i class="mdi mdi-clipboard-check-outline" aria-hidden="true"></i>核对计算条件
          </button>
        </footer>
      </form>

      <section
        v-else
        ref="reviewSection"
        class="commercial-pricing-confirmation"
        role="region"
        aria-labelledby="commercial-pricing-confirm-title"
        tabindex="-1"
      >
        <header>
          <i class="mdi mdi-shield-check-outline" aria-hidden="true"></i>
          <div>
            <strong id="commercial-pricing-confirm-title">确认计算条件</strong>
            <span>这次操作只生成定价建议，不创建、激活或修改任何套餐。</span>
          </div>
        </header>
        <dl>
          <div><dt>分析时间窗</dt><dd>{{ formatWindow(reviewedPayload) }}</dd></div>
          <div><dt>证据截止</dt><dd>{{ formatDateTime(reviewedPayload?.asOf) }}</dd></div>
          <div><dt>目标贡献毛利率</dt><dd>{{ formatRatio(reviewedPayload?.targetContributionMarginRate) }}</dd></div>
          <div><dt>最大价值分享</dt><dd>{{ formatRatio(reviewedPayload?.maxVerifiedSavingsShare) }}</dd></div>
        </dl>
        <p v-if="localError" ref="localErrorSummary" class="commercial-form-error" role="alert" tabindex="-1">
          {{ localError }}
        </p>
        <footer>
          <button type="button" class="commercial-button ghost" :disabled="loading" @click="step = 'edit'">返回修改</button>
          <button type="button" class="commercial-button primary" :disabled="loading" @click="confirmPricing">
            <i :class="loading ? 'mdi mdi-loading mdi-spin' : 'mdi mdi-calculator-variant-outline'" aria-hidden="true"></i>
            {{ loading ? '正在计算' : '确认并计算' }}
          </button>
        </footer>
      </section>

      <div v-if="!view && !loading" class="commercial-pricing-empty" role="status">
        <i class="mdi mdi-chart-box-plus-outline" aria-hidden="true"></i>
        <div>
          <strong>尚未生成定价场景</strong>
          <span>没有结果不代表成本或客户价值为 0；请先核对参数并发起计算。</span>
        </div>
      </div>

      <section v-else-if="view" class="commercial-pricing-result" aria-labelledby="commercial-pricing-result-title" aria-live="polite">
        <header>
          <div>
            <span>Scenario result</span>
            <h4 id="commercial-pricing-result-title">定价走廊结果</h4>
            <p>{{ formatWindow(view) }} · 证据截止 {{ formatDateTime(view.asOf) }}</p>
          </div>
          <span :class="['commercial-status-pill', view.evidenceStatus]">证据{{ view.evidenceStatusLabel }}</span>
        </header>

        <div class="commercial-pricing-summary">
          <article>
            <span>推荐商业模式</span>
            <strong>{{ view.recommendedModelLabel }}</strong>
            <small>系统只给出谈判边界，不会自动写入套餐。</small>
          </article>
          <article>
            <span>计算假设</span>
            <strong>{{ view.targetMarginLabel }} 毛利 / {{ view.maxValueShareLabel }} 价值分享</strong>
            <small>{{ view.multiCurrency ? '检测到多个币种，以下结果严格分币种展示。' : '当前结果按单一币种事实展示。' }}</small>
          </article>
        </div>

        <div v-if="!view.rows.length" class="commercial-state-card warning" role="status">
          <i class="mdi mdi-database-off-outline" aria-hidden="true"></i>
          <div>
            <strong>没有可建立币种场景的事实</strong>
            <span>内部成本和财务确认现金节省均不可用；这不是零成本、零价值或免费建议。</span>
          </div>
        </div>
        <div v-else class="commercial-pricing-grid">
          <article v-for="row in view.rows" :key="row.key" :class="['commercial-pricing-card', row.status]">
            <header>
              <div><span>币种</span><strong>{{ row.currency }}</strong></div>
              <em>{{ row.statusLabel }}</em>
            </header>
            <dl>
              <div><dt>内部成本</dt><dd>{{ row.internalCostLabel }}</dd></div>
              <div><dt>财务确认节省</dt><dd>{{ row.verifiedCashSavingsLabel }}</dd></div>
              <div class="pricing-bound"><dt>可持续收费下限</dt><dd>{{ row.minimumSustainableChargeLabel }}</dd></div>
              <div class="pricing-bound"><dt>价值对齐收费上限</dt><dd>{{ row.maximumValueAlignedChargeLabel }}</dd></div>
              <div><dt>成功费封顶</dt><dd>{{ row.maximumSuccessFeeLabel }}</dd></div>
              <div><dt>下限对应客户 ROI</dt><dd>{{ row.customerRoiLabel }}</dd></div>
              <div><dt>上限对应贡献毛利率</dt><dd>{{ row.contributionMarginLabel }}</dd></div>
            </dl>
            <p>{{ row.reason }}</p>
            <div v-if="row.missingInputs.length" class="commercial-pricing-missing" role="note">
              <strong>缺失输入</strong>
              <ul><li v-for="item in row.missingInputs" :key="item">{{ item }}</li></ul>
            </div>
          </article>
        </div>

        <details v-if="view.notes.length" class="commercial-pricing-notes">
          <summary>查看证据口径与注意事项</summary>
          <ul><li v-for="note in view.notes" :key="note">{{ note }}</li></ul>
        </details>
      </section>
    </template>
  </section>
</template>

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

import {
  buildPricingScenarioPayload,
  createDefaultPricingScenarioForm,
  formatRatio
} from './commercialWorkspaceModel.js'

const props = defineProps({
  tenantId: { type: String, default: '' },
  platformAdmin: { type: Boolean, default: false },
  range: { type: Object, required: true },
  view: { type: Object, default: null },
  loading: { type: Boolean, default: false },
  error: { type: Object, default: null },
  execute: { type: Function, required: true }
})

const draft = reactive(createDefaultPricingScenarioForm(props.range))
const step = ref('edit')
const localError = ref('')
const reviewedPayload = ref(null)
const reviewSection = ref(null)
const localErrorSummary = ref(null)
const errorSummary = ref(null)

watch(() => props.tenantId, () => {
  Object.assign(draft, createDefaultPricingScenarioForm(props.range))
  step.value = 'edit'
  localError.value = ''
  reviewedPayload.value = null
})

watch(() => props.error, (error) => {
  if (error) void nextTick(() => errorSummary.value?.focus?.())
})

function reviewPricing() {
  localError.value = ''
  try {
    reviewedPayload.value = buildPricingScenarioPayload(draft)
    step.value = 'confirm'
    void nextTick(() => reviewSection.value?.focus?.())
  } catch (error) {
    localError.value = error.message || '请检查定价场景输入。'
    void nextTick(() => localErrorSummary.value?.focus?.())
  }
}

async function confirmPricing() {
  localError.value = ''
  try {
    await props.execute({ ...draft })
    step.value = 'edit'
  } catch (error) {
    localError.value = error.message || '定价场景计算失败，请修正后重试。'
    void nextTick(() => localErrorSummary.value?.focus?.())
  }
}

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

function formatWindow(value) {
  return `${formatDateTime(value?.start)} 至 ${formatDateTime(value?.end)}`
}
</script>
