<template>
  <div v-if="visible" class="risk-waiver-record">
    <div class="risk-waiver-record-head">
      <strong>豁免申请与决定</strong>
      <em :class="disposition.waiverDecision || 'pending'">{{ decisionLabel }}</em>
    </div>
    <dl>
      <div>
        <dt>申请人</dt>
        <dd>
          {{ disposition.waiverRequesterName || disposition.waiverRequesterId || '未记录' }}
          <small>{{ formatDateTime(disposition.waiverRequestedAt) }}</small>
        </dd>
      </div>
      <div>
        <dt>申请理由</dt>
        <dd>{{ disposition.waiverReason || '未记录' }}</dd>
      </div>
      <div>
        <dt>豁免范围</dt>
        <dd>{{ disposition.waiverScope || '未记录' }}</dd>
      </div>
      <div>
        <dt>有效期至</dt>
        <dd :class="{ expired }">{{ formatDateTime(disposition.waiverExpiresAt) }}</dd>
      </div>
      <div class="wide">
        <dt>补偿条件</dt>
        <dd>
          <span v-if="!disposition.waiverConditions?.length">无附加条件</span>
          <ul v-else>
            <li v-for="condition in disposition.waiverConditions" :key="condition">
              {{ condition }}
            </li>
          </ul>
        </dd>
      </div>
      <div v-if="disposition.waiverDecision" class="wide">
        <dt>决定记录</dt>
        <dd>
          {{ disposition.waiverDeciderName || disposition.waiverDeciderId || '未记录决定人' }}
          <small>{{ formatDateTime(disposition.waiverDecidedAt) }}</small>
          <span>{{ disposition.waiverDecisionReason || '未记录决定理由' }}</span>
        </dd>
      </div>
    </dl>
    <section v-if="waiverEvents.length" class="risk-waiver-history">
      <h4>豁免审计轨迹</h4>
      <ol>
        <li v-for="event in waiverEvents" :key="event.key">
          <div>
            <strong>{{ event.label }}</strong>
            <em>v{{ event.version }}</em>
          </div>
          <p>{{ event.actor }} · {{ formatDateTime(event.createdAt) }}</p>
          <p v-if="event.comment">{{ event.comment }}</p>
          <span v-for="detail in event.details" :key="detail">{{ detail }}</span>
          <code v-if="event.requestId">请求 ID：{{ event.requestId }}</code>
        </li>
      </ol>
    </section>
  </div>
</template>

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

const props = defineProps({
  disposition: { type: Object, default: () => ({}) },
  expired: { type: Boolean, default: false }
})

const visible = computed(() => Boolean(
  props.disposition.waiverRequesterId
  || props.disposition.waiverRequesterName
  || props.disposition.waiverRequestedAt
))
const decisionLabel = computed(() => {
  if (props.disposition.waiverDecision === 'approved') {
    return props.expired ? '已批准 · 已到期' : '已批准'
  }
  if (props.disposition.waiverDecision === 'rejected') return '已拒绝'
  return '等待决定'
})
const waiverEvents = computed(() => (
  (props.disposition.events || [])
    .filter((event) => ['request_waiver', 'approve_waiver', 'reject_waiver'].includes(event.action))
    .map((event, index) => {
      const state = event.afterState || {}
      const details = event.action === 'request_waiver'
        ? [
            formatAuditDetail('原因', stateValue(state, 'waiver_reason', 'waiverReason')),
            formatAuditDetail('范围', stateValue(state, 'waiver_scope', 'waiverScope')),
            formatAuditDetail(
              '有效期至',
              formatDateTime(stateValue(state, 'waiver_expires_at', 'waiverExpiresAt'))
            ),
            formatAuditConditions(
              stateValue(state, 'waiver_conditions_json', 'waiverConditions')
            )
          ].filter(Boolean)
        : []
      return {
        key: event.id || `${event.action}:${event.version}:${index}`,
        label: formatWaiverAction(event.action),
        version: event.version,
        actor: formatActor(event),
        createdAt: event.createdAt,
        comment: event.comment,
        requestId: event.requestId,
        details
      }
    })
))

function stateValue(state, snakeKey, camelKey) {
  return state?.[snakeKey] ?? state?.[camelKey]
}

function formatAuditDetail(label, value) {
  const text = String(value || '').trim()
  return text && text !== '未记录' ? `${label}：${text}` : ''
}

function formatAuditConditions(value) {
  const conditions = Array.isArray(value)
    ? value.map((item) => String(item || '').trim()).filter(Boolean)
    : []
  return conditions.length ? `条件：${conditions.join('；')}` : ''
}

function formatActor(event) {
  const name = String(event.actorName || '').trim()
  const id = String(event.actorId || '').trim()
  if (name && id && name !== id) return `${name}（${id}）`
  return name || id || '未记录处理人'
}

function formatWaiverAction(action) {
  return {
    request_waiver: '提交豁免申请',
    approve_waiver: '批准豁免',
    reject_waiver: '拒绝豁免'
  }[action] || action
}

function formatDateTime(value) {
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return '未记录'
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    hour12: false
  }).format(date)
}
</script>

<style scoped src="../../assets/styles/components/risk-waiver-record.css"></style>
