<template>
  <section class="budget-assistant-report" aria-label="预算编制分析报告">
    <header class="budget-report-head">
      <div>
        <span class="budget-report-kicker">{{ report.basePeriod }} → {{ report.targetPeriod }}</span>
        <h3>{{ report.title }}</h3>
        <p>{{ report.departmentName }} · {{ report.subtitle }}</p>
      </div>
      <span class="budget-report-badge">
        <i class="mdi mdi-chart-donut"></i>
        分析报告
      </span>
    </header>

    <div class="budget-report-summary-grid">
      <article
        v-for="(metric, index) in summaryCards"
        :key="metric.label"
        class="budget-report-summary-card"
        :style="{ '--delay': `${index * 55}ms`, '--accent': metric.color }"
      >
        <span>{{ metric.label }}</span>
        <strong>{{ metric.value }}</strong>
        <small>{{ metric.hint }}</small>
      </article>
    </div>

    <section class="budget-report-main">
      <article class="budget-report-chart-panel">
        <div class="budget-report-section-head">
          <strong>{{ expenseStructureTitle }}</strong>
          <span>{{ report.centerLabel }}</span>
        </div>
        <DonutChart
          :items="report.items"
          :center-value="report.centerValue"
          :center-label="report.centerLabel"
        />
      </article>

      <article class="budget-report-macro-panel">
        <div class="budget-report-section-head">
          <strong>总体判断</strong>
          <span>宏观分析</span>
        </div>
        <ol class="budget-report-insight-list">
          <li v-for="item in report.macroInsights" :key="item">{{ item }}</li>
        </ol>
      </article>
    </section>

    <section class="budget-report-detail-panel">
      <div class="budget-report-section-head">
        <strong>费用类型拆解</strong>
        <span>用于编制{{ report.periodType || '下一期预算' }}</span>
      </div>
      <div class="budget-report-expense-list">
        <article
          v-for="(item, index) in report.items"
          :key="item.key"
          class="budget-report-expense-card"
          :style="{ '--accent': item.color, '--delay': `${index * 70}ms` }"
        >
          <header>
            <span class="budget-report-dot"></span>
            <strong>{{ item.name }}</strong>
            <em :class="item.trendTone">{{ item.trend }}</em>
          </header>
          <div class="budget-report-expense-stats">
            <span>开销 {{ item.amountDisplay }}</span>
            <span>占比 {{ item.share }}</span>
            <span>建议 {{ item.recommendedDisplay }}</span>
          </div>
          <p>{{ item.risk }}</p>
          <ul>
            <li v-for="driver in item.drivers" :key="driver">{{ driver }}</li>
          </ul>
          <footer>{{ item.suggestion }}</footer>
        </article>
      </div>
    </section>

    <section class="budget-report-editor-panel">
      <div class="budget-report-section-head">
        <strong>预算构成编辑</strong>
        <span>{{ editorSubtitle }}</span>
      </div>

      <div
        class="budget-editor-table"
        :class="{ 'is-review': isReviewMode }"
        role="table"
        aria-label="预算构成编辑表"
      >
        <div class="budget-editor-row head" role="row">
          <span role="columnheader">费用类型</span>
          <span role="columnheader">预算金额</span>
          <span v-if="isReviewMode" role="columnheader">建议预算</span>
          <span role="columnheader">预算说明</span>
          <span v-if="isReviewMode" role="columnheader">建议</span>
        </div>

        <div
          v-for="row in draftRows"
          :key="row.key"
          class="budget-editor-row"
          role="row"
        >
          <strong role="cell">{{ row.name }}</strong>
          <label role="cell">
            <span>预算金额</span>
            <input
              v-model.number="row.budgetAmount"
              type="number"
              min="0"
              step="1000"
              :readonly="isReviewMode"
            />
          </label>
          <label v-if="isReviewMode" role="cell">
            <span>建议预算</span>
            <input v-model.number="row.suggestedBudget" type="number" min="0" step="1000" />
          </label>
          <label class="budget-editor-note-cell" role="cell">
            <span>预算说明</span>
            <textarea v-model="row.submittedNote" :readonly="isReviewMode" rows="2" />
          </label>
          <label v-if="isReviewMode" class="budget-editor-note-cell" role="cell">
            <span>建议</span>
            <textarea v-model="row.financeSuggestion" rows="2" />
          </label>
        </div>
      </div>

      <footer class="budget-editor-footer">
        <div>
          <span>{{ totalLabel }}</span>
          <strong>{{ editableTotalDisplay }}</strong>
          <small>{{ draftStatusText }}</small>
        </div>
        <button
          type="button"
          class="budget-editor-primary"
          :class="{ danger: isReviewMode && hasReviewChanges }"
          @click="submitBudgetEditorAction"
        >
          {{ primaryActionLabel }}
        </button>
      </footer>
    </section>

    <section class="budget-report-action-panel">
      <div>
        <strong>{{ recommendationTitle }}</strong>
        <p v-for="item in report.recommendations" :key="item">{{ item }}</p>
      </div>
      <span>{{ report.generatedAt }}</span>
    </section>
  </section>
</template>

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

import DonutChart from '../charts/DonutChart.vue'

const props = defineProps({
  report: {
    type: Object,
    required: true
  }
})

const draftRows = reactive([])
const draftStatus = ref('editing')
const initialReviewSnapshot = ref('')

const formatAmount = (value) =>
  `¥${Number(value || 0).toLocaleString('zh-CN', {
    minimumFractionDigits: 0,
    maximumFractionDigits: 0
  })}`

function resetDraftRows() {
  draftRows.splice(
    0,
    draftRows.length,
    ...((props.report.editableDraft?.rows || props.report.items || []).map((item) => ({
      key: item.key,
      name: item.name,
      budgetAmount: Number(item.budgetAmount ?? item.recommendedBudget ?? 0),
      suggestedBudget: Number(item.suggestedBudget ?? item.recommendedBudget ?? item.budgetAmount ?? 0),
      submittedNote: String(item.submittedNote || item.note || item.suggestion || ''),
      financeSuggestion: String(item.financeSuggestion || '')
    })))
  )
  draftStatus.value = 'editing'
  initialReviewSnapshot.value = buildReviewSnapshot()
}

watch(() => props.report, resetDraftRows, { immediate: true })

const editableTotalDisplay = computed(() =>
  formatAmount(draftRows.reduce((sum, item) => {
    const value = isReviewMode.value ? item.suggestedBudget : item.budgetAmount
    return sum + Number(value || 0)
  }, 0))
)

const isReviewMode = computed(() =>
  props.report.mode === 'review' || props.report.editableDraft?.mode === 'review'
)

const editorSubtitle = computed(() =>
  isReviewMode.value
    ? '高级财务审核 · 修改建议预算或建议后将回退预算'
    : `${props.report.periodType || '预算'} · 仅编辑本部门预算`
)

const totalLabel = computed(() => isReviewMode.value ? '建议预算总额' : '当前编制总额')

function buildReviewSnapshot() {
  return JSON.stringify(draftRows.map((row) => ({
    key: row.key,
    suggestedBudget: Number(row.suggestedBudget || 0),
    financeSuggestion: String(row.financeSuggestion || '').trim()
  })))
}

const hasReviewChanges = computed(() =>
  isReviewMode.value && buildReviewSnapshot() !== initialReviewSnapshot.value
)

const draftStatusText = computed(() =>
  draftStatus.value === 'returned'
    ? '已标记回退预算，请预算管理者按建议调整后再次提交'
    : draftStatus.value === 'formed'
      ? '已形成预算，可进入预算中心正式生效'
      : isReviewMode.value
        ? '未调整建议时可形成预算；调整后将回退预算'
        : '保存后提交高级财务人员审核'
)

const baseBudgetLabel = computed(() =>
  isReviewMode.value
    ? '提交预算'
    : props.report.periodType === '年度预算' ? '去年预算' : '上季度预算'
)

const expenseStructureTitle = computed(() =>
  isReviewMode.value
    ? '提交预算费用结构'
    : props.report.periodType === '年度预算' ? '去年费用结构' : '上季度费用结构'
)

const recommendationTitle = computed(() => isReviewMode.value ? '审核建议' : '编制建议')

const primaryActionLabel = computed(() => {
  if (!isReviewMode.value) return '保存预算'
  return hasReviewChanges.value ? '回退预算' : '形成预算'
})

function submitBudgetEditorAction() {
  if (!isReviewMode.value) {
    draftStatus.value = 'formed'
    return
  }
  draftStatus.value = hasReviewChanges.value ? 'returned' : 'formed'
}

const summaryCards = computed(() => [
  {
    label: baseBudgetLabel.value,
    value: props.report.summary?.totalBudget || '—',
    hint: '作为编制基准',
    color: 'var(--theme-primary)'
  },
  {
    label: props.report.centerLabel || '上季度开销',
    value: props.report.summary?.totalSpend || '—',
    hint: '按四类预算口径汇总',
    color: 'var(--theme-secondary)'
  },
  {
    label: '预算使用率',
    value: props.report.summary?.usageRate || '—',
    hint: '未触达风险线',
    color: 'var(--warning)'
  },
  {
    label: '建议编制额',
    value: props.report.summary?.recommendedTotal || '—',
    hint: '含业务增长预留',
    color: 'var(--info)'
  }
])
</script>

<style scoped>
.budget-assistant-report {
  display: grid;
  gap: 12px;
  margin-top: 12px;
  color: #1f2937;
  animation: budgetReportIn 420ms var(--ease, ease) both;
}

.budget-report-head,
.budget-report-main,
.budget-report-detail-panel,
.budget-report-editor-panel,
.budget-report-action-panel,
.budget-report-summary-card {
  border: 1px solid #dbe4ee;
  border-radius: 4px;
  background: #fff;
  box-shadow: 0 1px 2px rgba(15, 23, 42, .04);
}

.budget-report-head {
  padding: 14px 16px;
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  border-left: 3px solid var(--theme-primary);
}

.budget-report-kicker,
.budget-report-head p,
.budget-report-section-head span,
.budget-report-action-panel span {
  color: #64748b;
  font-size: 12px;
  font-weight: 700;
}

.budget-report-head h3 {
  margin: 4px 0 4px;
  color: #0f172a;
  font-size: 17px;
  font-weight: 850;
  line-height: 1.3;
}

.budget-report-head p,
.budget-report-action-panel p {
  margin: 0;
}

.budget-report-badge {
  min-height: 28px;
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 0 10px;
  border-radius: 4px;
  background: var(--theme-primary-soft);
  color: var(--theme-primary-active);
  font-size: 12px;
  font-weight: 800;
  white-space: nowrap;
}

.budget-report-summary-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 10px;
}

.budget-report-summary-card {
  min-height: 86px;
  padding: 10px 12px;
  border-left: 3px solid var(--accent);
  display: grid;
  align-content: center;
  gap: 4px;
  animation: budgetReportItemIn 460ms var(--ease, ease) both;
  animation-delay: var(--delay, 0ms);
}

.budget-report-summary-card span,
.budget-report-summary-card small {
  color: #64748b;
  font-size: 11px;
  font-weight: 650;
}

.budget-report-summary-card strong {
  color: #0f172a;
  font-size: 18px;
  font-weight: 850;
  line-height: 1.1;
}

.budget-report-main {
  display: grid;
  grid-template-columns: minmax(260px, .9fr) minmax(0, 1.1fr);
  gap: 14px;
  padding: 14px;
}

.budget-report-chart-panel,
.budget-report-macro-panel {
  min-width: 0;
}

.budget-report-section-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 10px;
}

.budget-report-section-head strong,
.budget-report-action-panel strong {
  color: #111827;
  font-size: 14px;
  font-weight: 850;
}

.budget-report-chart-panel :deep(.donut-chart) {
  min-height: 224px;
}

.budget-report-chart-panel :deep(.donut-body) {
  height: 138px;
  margin-top: 8px;
}

.budget-report-insight-list {
  display: grid;
  gap: 9px;
  margin: 0;
  padding-left: 20px;
}

.budget-report-insight-list li {
  color: #334155;
  font-size: 13px;
  font-weight: 650;
  line-height: 1.55;
}

.budget-report-detail-panel {
  padding: 14px;
}

.budget-report-editor-panel {
  padding: 14px;
}

.budget-editor-table {
  display: grid;
  gap: 8px;
}

.budget-editor-row {
  display: grid;
  grid-template-columns: minmax(82px, .7fr) minmax(128px, .9fr) minmax(280px, 2fr);
  gap: 8px;
  align-items: center;
  min-width: 0;
}

.budget-editor-table.is-review .budget-editor-row {
  grid-template-columns:
    minmax(82px, .65fr)
    minmax(122px, .75fr)
    minmax(122px, .8fr)
    minmax(240px, 1.6fr)
    minmax(240px, 1.6fr);
}

.budget-editor-row.head {
  min-height: 34px;
  padding: 0 8px;
  border-radius: 4px;
  background: #f8fafc;
  color: #64748b;
  font-size: 12px;
  font-weight: 850;
}

.budget-editor-row:not(.head) {
  padding: 8px;
  border: 1px solid #edf1f6;
  border-radius: 4px;
  background: #fbfdff;
}

.budget-editor-row > strong {
  color: #0f172a;
  font-size: 13px;
  font-weight: 850;
}

.budget-editor-row label {
  min-width: 0;
  display: grid;
  gap: 3px;
}

.budget-editor-row label span {
  display: none;
}

.budget-editor-row input,
.budget-editor-row textarea {
  width: 100%;
  min-width: 0;
  border: 1px solid #dbe4ee;
  border-radius: 4px;
  background: #fff;
  color: #1f2937;
  font-size: 12px;
  font-weight: 700;
}

.budget-editor-row input {
  height: 32px;
  padding: 0 8px;
}

.budget-editor-row textarea {
  min-height: 42px;
  padding: 7px 8px;
  resize: vertical;
  line-height: 1.45;
}

.budget-editor-row input:focus,
.budget-editor-row textarea:focus {
  border-color: rgba(58, 124, 165, .46);
  outline: 3px solid var(--theme-focus-ring, rgba(58, 124, 165, .12));
}

.budget-editor-row input[readonly],
.budget-editor-row textarea[readonly] {
  background: #f8fafc;
  color: #475569;
  cursor: default;
}

.budget-editor-footer {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #edf1f6;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
}

.budget-editor-footer div {
  margin-right: auto;
  display: grid;
  gap: 2px;
}

.budget-editor-footer span,
.budget-editor-footer small {
  color: #64748b;
  font-size: 11px;
  font-weight: 700;
}

.budget-editor-footer strong {
  color: #0f172a;
  font-size: 17px;
  line-height: 1.2;
  font-weight: 900;
}

.budget-editor-primary,
.budget-editor-secondary {
  min-height: 32px;
  border-radius: 4px;
  padding: 0 12px;
  font-size: 12px;
  font-weight: 850;
}

.budget-editor-primary {
  border: 0;
  background: var(--theme-primary-active);
  color: #fff;
}

.budget-editor-primary.danger {
  background: #7f1d1d;
}

.budget-editor-secondary {
  border: 1px solid #d7e0ea;
  background: #fff;
  color: #334155;
}

.budget-report-expense-list {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 10px;
}

.budget-report-expense-card {
  min-width: 0;
  padding: 12px;
  border: 1px solid #e2e8f0;
  border-left: 3px solid var(--accent);
  border-radius: 4px;
  background: #fbfdff;
  animation: budgetReportItemIn 460ms var(--ease, ease) both;
  animation-delay: var(--delay, 0ms);
}

.budget-report-expense-card header,
.budget-report-expense-stats {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}

.budget-report-expense-card header {
  margin-bottom: 8px;
}

.budget-report-dot {
  width: 9px;
  height: 9px;
  border-radius: 3px;
  background: var(--accent);
  flex: 0 0 auto;
}

.budget-report-expense-card header strong {
  color: #0f172a;
  font-size: 14px;
  font-weight: 850;
}

.budget-report-expense-card header em {
  margin-left: auto;
  padding: 1px 7px;
  border-radius: 4px;
  font-size: 11px;
  font-style: normal;
  font-weight: 850;
}

.budget-report-expense-card header em.risk {
  background: rgba(127, 29, 29, .09);
  color: #7f1d1d;
}

.budget-report-expense-card header em.warn {
  background: rgba(245, 158, 11, .14);
  color: #b45309;
}

.budget-report-expense-card header em.stable {
  background: rgba(22, 163, 74, .1);
  color: #15803d;
}

.budget-report-expense-stats {
  flex-wrap: wrap;
  margin-bottom: 8px;
}

.budget-report-expense-stats span {
  min-height: 22px;
  display: inline-flex;
  align-items: center;
  padding: 0 7px;
  border-radius: 4px;
  background: #f1f5f9;
  color: #475569;
  font-size: 11px;
  font-weight: 750;
}

.budget-report-expense-card p,
.budget-report-expense-card li,
.budget-report-expense-card footer,
.budget-report-action-panel p {
  color: #334155;
  font-size: 12px;
  font-weight: 620;
  line-height: 1.55;
}

.budget-report-expense-card p {
  margin: 0 0 8px;
}

.budget-report-expense-card ul {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin: 0 0 8px;
  padding: 0;
  list-style: none;
}

.budget-report-expense-card li {
  padding: 2px 7px;
  border-radius: 4px;
  background: #fff;
  border: 1px solid #e2e8f0;
}

.budget-report-expense-card footer {
  padding-top: 8px;
  border-top: 1px solid #e2e8f0;
}

.budget-report-action-panel {
  padding: 14px 16px;
  display: flex;
  justify-content: space-between;
  gap: 14px;
  border-left: 3px solid var(--chart-amber);
}

.budget-report-action-panel div {
  display: grid;
  gap: 6px;
}

@keyframes budgetReportIn {
  from {
    opacity: 0;
    transform: translateY(8px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes budgetReportItemIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@media (max-width: 900px) {
  .budget-report-summary-grid,
  .budget-report-main,
  .budget-report-expense-list,
  .budget-editor-row {
    grid-template-columns: 1fr;
  }

  .budget-editor-row.head {
    display: none;
  }

  .budget-editor-row label span {
    display: block;
    color: #64748b;
    font-size: 11px;
    font-weight: 700;
  }

  .budget-editor-footer {
    align-items: stretch;
    flex-direction: column;
  }

  .budget-editor-footer div {
    margin-right: 0;
  }
}

@media (prefers-reduced-motion: reduce) {
  .budget-assistant-report,
  .budget-report-summary-card,
  .budget-report-expense-card {
    animation: none;
  }
}
</style>
