<template>
  <div>
    <h3>预测模拟</h3>

    <el-tabs v-model="activeTab" style="margin-top:16px;">
      <!-- Tab 1: CVP本量利分析（增强版） -->
      <el-tab-pane label="本量利分析" name="cvp">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-card>
              <template #header>
                <div style="display:flex;justify-content:space-between;align-items:center;">
                  <span>参数设置 — 酣客白酒</span>
                  <el-button size="small" @click="fillActualData">📋 一键填入当前实际数据</el-button>
                </div>
              </template>
              <el-form label-position="top">
                <el-form-item label="固定成本（万元）">
                  <el-slider v-model="cvpForm.fixed_cost" :min="100" :max="1000" :step="10" show-input />
                </el-form-item>
                <el-form-item label="变动成本率（%）">
                  <el-slider v-model="cvpForm.variable_cost_rate" :min="10" :max="90" :step="0.5" show-input />
                </el-form-item>
                <el-form-item label="销售单价（元/瓶）">
                  <el-input-number v-model="cvpForm.unit_price" :min="50" :max="999" style="width:100%;" />
                </el-form-item>
                <el-form-item label="当前销量（瓶）">
                  <el-input-number v-model="cvpForm.current_volume" :min="100" :max="100000" :step="100" style="width:100%;" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="doCvpDetailed" :loading="cvpLoading" style="width:100%;">分析</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
          <el-col :span="16">
            <el-card v-if="cvpResult.breakeven_revenue !== undefined">
              <template #header>分析结果</template>
              <el-row :gutter="12">
                <el-col :span="8"><div class="result-card"><div class="r-label">保本点（销售额）</div><div class="r-value red">{{ formatMoney(cvpResult.breakeven_revenue, 'wan') }} 万</div></div></el-col>
                <el-col :span="8"><div class="result-card"><div class="r-label">保本点（销售量）</div><div class="r-value red">{{ cvpResult.breakeven_units?.toLocaleString() }} 瓶</div></div></el-col>
                <el-col :span="8"><div class="result-card"><div class="r-label">边际贡献率</div><div class="r-value blue">{{ cvpResult.contribution_margin_rate }}%</div></div></el-col>
              </el-row>
              <el-row :gutter="12" style="margin-top:12px;">
                <el-col :span="8"><div class="result-card"><div class="r-label">当前销售收入</div><div class="r-value green">{{ formatMoney(cvpResult.current_revenue, 'wan') }} 万</div></div></el-col>
                <el-col :span="8"><div class="result-card"><div class="r-label">当前利润</div><div class="r-value" :class="cvpResult.current_profit >= 0 ? 'green' : 'red'">{{ formatMoney(cvpResult.current_profit, 'wan') }} 万</div></div></el-col>
                <el-col :span="8"><div class="result-card"><div class="r-label">安全边际率</div><div class="r-value" :class="cvpResult.safety_margin > 25 ? 'green' : cvpResult.safety_margin > 10 ? 'orange' : 'red'">{{ cvpResult.safety_margin }}%</div></div></el-col>
              </el-row>

              <!-- 改善方案 -->
              <el-card style="margin-top:12px;background:#f9f9f9;" size="small" v-if="cvpResult.scenarios?.length">
                <template #header>💡 改善方案推演</template>
                <el-table :data="cvpResult.scenarios" border stripe size="small">
                  <el-table-column prop="name" label="方案" min-width="160" />
                  <el-table-column prop="breakeven_revenue" label="保本点(万)" width="120" align="right">
                    <template #default="{ row }">{{ row.breakeven_revenue?.toFixed(1) }}</template>
                  </el-table-column>
                  <el-table-column prop="breakeven_units" label="保本销量(瓶)" width="120" align="right">
                    <template #default="{ row }">{{ row.breakeven_units?.toLocaleString() }}</template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-card>
            <el-empty v-else-if="!cvpLoading" description="调整参数后点击「分析」" style="padding:40px 0;" />
          </el-col>
        </el-row>

        <!-- 保本图 -->
        <el-card style="margin-top:16px;" v-if="cvpResult.chart_data?.length">
          <template #header>📈 保本点分析图（销售额 vs 总成本）</template>
          <div ref="cvpChartRef" style="height:360px;width:100%;"></div>
        </el-card>
      </el-tab-pane>

      <!-- Tab 2: 投资决策 -->
      <el-tab-pane label="投资决策" name="investment">
        <el-row :gutter="16">
          <el-col :span="10">
            <el-card>
              <template #header>输入参数</template>
              <el-form :model="invForm" label-width="140px">
                <el-form-item label="初始投资"><el-input-number v-model="invForm.initial_investment" :min="0" :precision="2" style="width:200px;" /></el-form-item>
                <el-form-item label="折现率(%)"><el-input-number v-model="invForm.discount_rate" :min="0" :max="100" :precision="1" style="width:200px;" /></el-form-item>
                <el-form-item label="现金流（每年）">
                  <div v-for="(cf, idx) in invForm.cash_flows" :key="idx" style="display:flex;gap:8px;margin-bottom:4px;">
                    <span style="line-height:32px;width:80px;">第{{ idx+1 }}年</span>
                    <el-input-number v-model="invForm.cash_flows[idx]" :min="0" :precision="2" style="width:150px;" />
                    <el-button v-if="invForm.cash_flows.length > 1" size="small" type="danger" @click="invForm.cash_flows.splice(idx, 1)">×</el-button>
                  </div>
                  <el-button size="small" @click="invForm.cash_flows.push(0)">+ 添加年份</el-button>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="doInvestment" :loading="invLoading">计算</el-button>
                  <el-button @click="fillInvExample">填充示例</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
          <el-col :span="14">
            <el-card v-if="invResult.npv_analysis">
              <template #header>分析结果</template>
              <el-row :gutter="12">
                <el-col :span="8"><div class="result-card"><div class="r-label">净现值 (NPV)</div><div class="r-value" :class="invResult.npv_analysis.npv > 0 ? 'green' : 'red'">{{ formatMoney(invResult.npv_analysis.npv) }}</div></div></el-col>
                <el-col :span="8"><div class="result-card"><div class="r-label">内部收益率 (IRR)</div><div class="r-value blue">{{ invResult.irr_analysis.irr }}%</div></div></el-col>
                <el-col :span="8"><div class="result-card"><div class="r-label">盈利指数 (PI)</div><div class="r-value purple">{{ invResult.npv_analysis.profitability_index }}</div></div></el-col>
              </el-row>
              <el-row :gutter="12" style="margin-top:12px;">
                <el-col :span="8"><div class="result-card"><div class="r-label">静态回收期</div><div class="r-value">{{ invResult.irr_analysis.payback_period || '--' }} 年</div></div></el-col>
                <el-col :span="8"><div class="result-card"><div class="r-label">动态回收期</div><div class="r-value">{{ invResult.irr_analysis.discounted_payback_period || '>N期' }} 年</div></div></el-col>
                <el-col :span="8"><div class="result-card"><div class="r-label">可行性</div><div class="r-value" :class="invResult.npv_analysis.is_viable ? 'green' : 'red'">{{ invResult.npv_analysis.is_viable ? '✅ 可行' : '❌ 不可行' }}</div></div></el-col>
              </el-row>
            </el-card>
            <el-empty v-else-if="!invLoading" description="输入参数后点击「计算」" style="padding:40px 0;" />
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- Tab 3: 敏感性分析 -->
      <el-tab-pane label="敏感性分析" name="sensitivity">
        <el-row :gutter="16">
          <el-col :span="10">
            <el-card>
              <template #header>输入参数</template>
              <el-form :model="sensForm" label-width="140px">
                <el-form-item label="基准收入"><el-input-number v-model="sensForm.base_revenue" :min="0" :precision="2" style="width:200px;" /></el-form-item>
                <el-form-item label="基准成本"><el-input-number v-model="sensForm.base_cost" :min="0" :precision="2" style="width:200px;" /></el-form-item>
                <el-form-item label="变动步长(%)"><el-input-number v-model="sensForm.step" :min="1" :max="50" style="width:200px;" /></el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="doSensitivity" :loading="sensLoading">计算</el-button>
                  <el-button @click="sensForm = { base_revenue: 1000000, base_cost: 700000, step: 5 }">填充示例</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
          <el-col :span="14">
            <el-card v-if="sensResult.base_revenue">
              <template #header>
                敏感性分析结果 — 基准利润：{{ formatMoney(sensResult.base_profit) }}
              </template>
              <el-table :data="sensResult.factors" border stripe size="small" style="width:100%;" max-height="400">
                <el-table-column prop="change_pct" label="变动%" width="70" align="center">
                  <template #default="{ row }"><span :style="{ color: row.change_pct > 0 ? '#f56c6c' : '#67c23a', fontWeight:600 }">{{ row.change_pct > 0 ? '+' : '' }}{{ row.change_pct }}%</span></template>
                </el-table-column>
                <el-table-column prop="revenue_change_profit" label="收入变动→利润" width="130" align="right"><template #default="{ row }">{{ formatMoney(row.revenue_change_profit) }}</template></el-table-column>
                <el-table-column prop="revenue_sensitivity" label="收入敏感度" width="100" align="right"><template #default="{ row }"><span :style="{ color: row.revenue_sensitivity < 0 ? '#f56c6c' : '#67c23a' }">{{ row.revenue_sensitivity > 0 ? '+' : '' }}{{ row.revenue_sensitivity }}%</span></template></el-table-column>
                <el-table-column prop="cost_change_profit" label="成本变动→利润" width="130" align="right"><template #default="{ row }">{{ formatMoney(row.cost_change_profit) }}</template></el-table-column>
                <el-table-column prop="cost_sensitivity" label="成本敏感度" width="100" align="right"><template #default="{ row }"><span :style="{ color: row.cost_sensitivity < 0 ? '#f56c6c' : '#67c23a' }">{{ row.cost_sensitivity > 0 ? '+' : '' }}{{ row.cost_sensitivity }}%</span></template></el-table-column>
              </el-table>
            </el-card>
            <el-empty v-else-if="!sensLoading" description="输入参数后点击「计算」" style="padding:40px 0;" />
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- Tab 4: 情景模拟 -->
      <el-tab-pane label="情景模拟" name="scenario">
        <el-row :gutter="16">
          <el-col :span="10">
            <el-card>
              <template #header>输入三个情景</template>
              <el-form label-width="120px">
                <div style="margin-bottom:12px;">
                  <el-tag type="success" size="small">乐观情景</el-tag>
                  <div style="display:flex;gap:8px;margin-top:4px;">
                    <el-input-number v-model="scenarioForm.optimistic.revenue" placeholder="收入" :min="0" :precision="2" style="width:150px;" /> 
                    <el-input-number v-model="scenarioForm.optimistic.cost" placeholder="成本" :min="0" :precision="2" style="width:150px;" />
                  </div>
                </div>
                <div style="margin-bottom:12px;">
                  <el-tag type="warning" size="small">中性情景</el-tag>
                  <div style="display:flex;gap:8px;margin-top:4px;">
                    <el-input-number v-model="scenarioForm.base.revenue" :min="0" :precision="2" style="width:150px;" />
                    <el-input-number v-model="scenarioForm.base.cost" :min="0" :precision="2" style="width:150px;" />
                  </div>
                </div>
                <div style="margin-bottom:12px;">
                  <el-tag type="danger" size="small">悲观情景</el-tag>
                  <div style="display:flex;gap:8px;margin-top:4px;">
                    <el-input-number v-model="scenarioForm.pessimistic.revenue" :min="0" :precision="2" style="width:150px;" />
                    <el-input-number v-model="scenarioForm.pessimistic.cost" :min="0" :precision="2" style="width:150px;" />
                  </div>
                </div>
                <el-button type="primary" @click="doScenario" :loading="scenarioLoading">模拟</el-button>
                <el-button @click="fillScenarioExample">填充示例</el-button>
              </el-form>
            </el-card>
          </el-col>
          <el-col :span="14">
            <el-card v-if="scenarioResult.scenarios">
              <template #header>
                模拟结果
                <span style="margin-left:12px;font-size:12px;color:#999;">
                  期望利润：{{ formatMoney(scenarioResult.expected_profit) }}
                  | 标准差：{{ formatMoney(scenarioResult.std_deviation) }}
                </span>
              </template>
              <el-table :data="scenarioResult.scenarios" border stripe size="small" style="width:100%;">
                <el-table-column prop="scenario" label="情景" width="80">
                  <template #default="{ row }">
                    <el-tag :type="row.scenario === '乐观' ? 'success' : row.scenario === '中性' ? 'warning' : 'danger'" size="small">{{ row.scenario }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="revenue" label="收入" width="100" align="right"><template #default="{ row }">{{ formatMoney(row.revenue) }}</template></el-table-column>
                <el-table-column prop="cost" label="成本" width="100" align="right"><template #default="{ row }">{{ formatMoney(row.cost) }}</template></el-table-column>
                <el-table-column prop="profit" label="利润" width="100" align="right">
                  <template #default="{ row }"><span :style="{ color: row.profit >= 0 ? '#67c23a' : '#f56c6c', fontWeight:600 }">{{ formatMoney(row.profit) }}</span></template>
                </el-table-column>
                <el-table-column prop="profit_margin" label="利润率" width="80" align="right"><template #default="{ row }">{{ row.profit_margin }}%</template></el-table-column>
                <el-table-column prop="deviation_from_base" label="偏差" width="100" align="right">
                  <template #default="{ row }"><span :style="{ color: row.deviation_from_base > 0 ? '#67c23a' : '#f56c6c' }">{{ row.deviation_from_base > 0 ? '+' : '' }}{{ formatMoney(row.deviation_from_base) }}</span></template>
                </el-table-column>
                <el-table-column prop="deviation_pct" label="偏差%" width="80" align="right"><template #default="{ row }">{{ row.deviation_pct }}%</template></el-table-column>
              </el-table>
            </el-card>
            <el-empty v-else-if="!scenarioLoading" description="输入三个情景后点击「模拟」" style="padding:40px 0;" />
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- Tab: 相关成本决策（CMA P2商业决策分析） -->
      <el-tab-pane label="相关成本决策" name="relevantDecision">
        <el-row :gutter="16">
          <el-col :span="24">
            <el-radio-group v-model="relDecisionType" style="margin-bottom:16px;">
              <el-radio-button value="make_or_buy">自制 vs 外购</el-radio-button>
              <el-radio-button value="special_order">特殊订单</el-radio-button>
              <el-radio-button value="product_mix">产品组合(约束理论)</el-radio-button>
            </el-radio-group>
          </el-col>
        </el-row>

        <!-- 自制vs外购 -->
        <el-row v-if="relDecisionType === 'make_or_buy'" :gutter="16">
          <el-col :span="10">
            <el-card>
              <template #header>输入参数</template>
              <el-form label-width="140px" size="small">
                <el-form-item label="需求量(件)"><el-input-number v-model="makeBuy.demand" :min="0" style="width:200px;" /></el-form-item>
                <el-form-item label="自制单位变动成本"><el-input-number v-model="makeBuy.make_variable_cost" :min="0" style="width:200px;" /></el-form-item>
                <el-form-item label="自制新增固定成本"><el-input-number v-model="makeBuy.make_fixed_cost" :min="0" style="width:200px;" /></el-form-item>
                <el-form-item label="外购单价"><el-input-number v-model="makeBuy.buy_price" :min="0" style="width:200px;" /></el-form-item>
                <el-button type="primary" size="small" @click="runRelevantDecision">计算决策</el-button>
              </el-form>
            </el-card>
          </el-col>
          <el-col :span="14">
            <el-card v-if="relResult">
              <template #header>决策结果</template>
              <el-alert :title="'建议：' + relResult.recommendation" :type="relResult.recommendation === '自制' ? 'primary' : 'warning'" :description="relResult.reason" show-icon :closable="false" style="margin-bottom:12px;" />
              <el-descriptions :column="2" border size="small">
                <el-descriptions-item label="自制总成本">{{ formatRelNum(relResult.make_total_cost) }}</el-descriptions-item>
                <el-descriptions-item label="外购总成本">{{ formatRelNum(relResult.buy_total_cost) }}</el-descriptions-item>
                <el-descriptions-item label="单位自制成本">{{ formatRelNum(relResult.unit_make_cost) }}</el-descriptions-item>
                <el-descriptions-item label="外购单价">{{ formatRelNum(relResult.unit_buy_price) }}</el-descriptions-item>
                <el-descriptions-item label="无差别点" :span="2">{{ relResult.indifferent_point != null ? formatRelNum(relResult.indifferent_point) + '件' : '—' }}</el-descriptions-item>
              </el-descriptions>
              <el-text size="small" type="info" style="margin-top:8px;display:block;">{{ relResult.notes }}</el-text>
            </el-card>
          </el-col>
        </el-row>

        <!-- 特殊订单 -->
        <el-row v-if="relDecisionType === 'special_order'" :gutter="16">
          <el-col :span="10">
            <el-card>
              <template #header>输入参数</template>
              <el-form label-width="140px" size="small">
                <el-form-item label="正常售价"><el-input-number v-model="specialOrder.normal_price" :min="0" style="width:200px;" /></el-form-item>
                <el-form-item label="特殊订单价"><el-input-number v-model="specialOrder.special_price" :min="0" style="width:200px;" /></el-form-item>
                <el-form-item label="单位变动成本"><el-input-number v-model="specialOrder.variable_cost" :min="0" style="width:200px;" /></el-form-item>
                <el-form-item label="订单数量"><el-input-number v-model="specialOrder.order_qty" :min="0" style="width:200px;" /></el-form-item>
                <el-form-item label="产能占用%"><el-input-number v-model="specialOrder.capacity_used" :min="0" :max="100" style="width:200px;" /></el-form-item>
                <el-form-item label="额外固定成本"><el-input-number v-model="specialOrder.extra_fixed_cost" :min="0" style="width:200px;" /></el-form-item>
                <el-button type="primary" size="small" @click="runRelevantDecision">计算决策</el-button>
              </el-form>
            </el-card>
          </el-col>
          <el-col :span="14">
            <el-card v-if="relResult">
              <template #header>决策结果</template>
              <el-alert :title="'建议：' + relResult.recommendation" :type="relResult.recommendation === '接受' ? 'success' : 'danger'" :description="relResult.reason" show-icon :closable="false" style="margin-bottom:12px;" />
              <el-descriptions :column="2" border size="small">
                <el-descriptions-item label="单位贡献">{{ formatRelNum(relResult.unit_contribution) }}</el-descriptions-item>
                <el-descriptions-item label="总贡献">{{ formatRelNum(relResult.total_contribution) }}</el-descriptions-item>
                <el-descriptions-item label="产能占用">{{ relResult.capacity_used_pct }}%</el-descriptions-item>
                <el-descriptions-item label="额外固定成本">{{ formatRelNum(relResult.extra_fixed_cost) }}</el-descriptions-item>
              </el-descriptions>
              <el-text size="small" type="info" style="margin-top:8px;display:block;">{{ relResult.notes }}</el-text>
            </el-card>
          </el-col>
        </el-row>

        <!-- 产品组合 -->
        <el-row v-if="relDecisionType === 'product_mix'" :gutter="16">
          <el-col :span="12">
            <el-card>
              <template #header>产品参数（价格/变动成本/约束资源消耗/需求）</template>
              <div v-for="(p, idx) in productMix.products" :key="idx" style="display:flex;gap:8px;margin-bottom:8px;align-items:center;">
                <el-input v-model="p.name" placeholder="产品名" style="width:100px;" size="small" />
                <el-input-number v-model="p.price" :min="0" placeholder="价格" style="width:110px;" size="small" />
                <el-input-number v-model="p.var_cost" :min="0" placeholder="变动成本" style="width:110px;" size="small" />
                <el-input-number v-model="p.constraint_usage" :min="0.1" placeholder="约束消耗" style="width:100px;" size="small" />
                <el-input-number v-model="p.demand" :min="0" placeholder="需求" style="width:90px;" size="small" />
              </div>
              <el-button size="small" @click="productMix.products.push({ name: '新产品', price: 100, var_cost: 60, constraint_usage: 1, demand: 100 })">+ 添加产品</el-button>
              <el-button size="small" type="primary" @click="runRelevantDecision" style="margin-left:8px;">计算决策</el-button>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card v-if="relResult">
              <template #header>决策结果</template>
              <el-alert :title="relResult.recommendation" type="success" :closable="false" style="margin-bottom:12px;" />
              <el-table :data="relResult.ranking" border stripe size="small">
                <el-table-column prop="name" label="产品" />
                <el-table-column prop="unit_contribution" label="单位贡献" />
                <el-table-column prop="constraint_usage" label="约束消耗" />
                <el-table-column prop="contribution_per_constraint" label="单位约束贡献" />
                <el-table-column prop="demand" label="需求" />
              </el-table>
              <el-text size="small" type="info" style="margin-top:8px;display:block;">{{ relResult.notes }}</el-text>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- Tab 5: 现金流预测（AI事前预警） -->
      <el-tab-pane label="现金流预测" name="cashFlow">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-card>
              <template #header>预测参数</template>
              <el-form label-position="top">
                <el-form-item label="企业实体">
                  <el-select v-model="cfEntityId" style="width:100%;">
                    <el-option label="陕西酣客（白酒经销）" :value="1" />
                    <el-option label="陕西博海科技（IT服务）" :value="2" />
                  </el-select>
                </el-form-item>
                <el-form-item label="当前现金余额（万元）">
                  <el-input-number v-model="cfCurrentCash" :min="0" :precision="1" style="width:100%;" />
                </el-form-item>
                <el-form-item label="预测天数">
                  <el-select v-model="cfDays" style="width:100%;">
                    <el-option label="未来7天" :value="7" />
                    <el-option label="未来15天" :value="15" />
                    <el-option label="未来30天" :value="30" />
                    <el-option label="未来60天" :value="60" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="doCashForecast" :loading="cfLoading" style="width:100%;">🔮 开始预测</el-button>
                </el-form-item>
              </el-form>
            </el-card>
            <!-- 趋势指标 -->
            <el-card style="margin-top:12px;" v-if="cfResult.trends">
              <template #header>📊 趋势指标</template>
              <div class="trend-item"><span class="t-label">经营现金流趋势</span><span class="t-value" :class="cfResult.trends.operating_cash_flow_trend_pct >= 0 ? 'green' : 'red'">{{ cfResult.trends.operating_cash_flow_trend_pct }}%</span></div>
              <div class="trend-item"><span class="t-label">应收账款趋势</span><span class="t-value" :class="cfResult.trends.receivables_trend_pct >= 0 ? 'red' : 'green'">{{ cfResult.trends.receivables_trend_pct }}%</span></div>
              <div class="trend-item"><span class="t-label">应付账款趋势</span><span class="t-value" :class="cfResult.trends.payables_trend_pct >= 0 ? 'green' : 'red'">{{ cfResult.trends.payables_trend_pct }}%</span></div>
            </el-card>
          </el-col>
          <el-col :span="18">
            <!-- 预测折线图 -->
            <el-card v-if="cfResult.forecast?.length">
              <template #header>
                <div style="display:flex;justify-content:space-between;align-items:center;">
                  <span>📈 现金流预测 — 未来{{ cfDays }}天</span>
                  <span>
                    <span style="font-size:12px;color:#909399;">基准现金：</span>
                    <strong>{{ cfResult.base_cash }}万</strong>
                    <span style="margin-left:12px;font-size:12px;color:#909399;">最低点：</span>
                    <strong :style="{color: cfResult.min_cash < 10 ? '#f56c6c' : cfResult.min_cash < 20 ? '#e6a23c' : '#67c23a'}">{{ cfResult.min_cash }}万</strong>
                    <span style="margin-left:4px;font-size:12px;color:#909399;">（{{ cfResult.min_cash_date }}）</span>
                  </span>
                </div>
              </template>
              <div ref="cfChartRef" style="height:380px;width:100%;"></div>
            </el-card>
            <el-empty v-else-if="!cfLoading" description="设置参数后点击「开始预测」" style="padding:60px 0;" />

            <!-- 预警建议 -->
            <el-card style="margin-top:16px;" v-if="cfResult.suggestions?.length">
              <template #header>💡 预警建议</template>
              <div v-for="(sug, idx) in cfResult.suggestions" :key="idx" style="margin-bottom:12px;">
                <el-alert
                  :title="sug.message"
                  :type="sug.type === 'critical' ? 'error' : 'warning'"
                  :closable="false"
                  show-icon
                  style="margin-bottom:8px;"
                />
                <el-tag v-for="(act, aidx) in sug.actions" :key="aidx" style="margin:2px 4px 2px 0;" size="small" effect="plain">
                  ✅ {{ act }}
                </el-tag>
              </div>
            </el-card>

            <!-- 每日预测明细表 -->
            <el-card style="margin-top:16px;" v-if="cfResult.forecast?.length">
              <template #header>
                <span>📋 每日预测明细</span>
                <span style="margin-left:12px;font-size:12px;color:#999;">（共{{ cfResult.forecast.length }}天）</span>
              </template>
              <el-table :data="cfResult.forecast" border stripe size="small" max-height="300" style="width:100%;">
                <el-table-column prop="date" label="日期" width="110" />
                <el-table-column prop="predicted_cash" label="预测现金(万)" width="130" align="right">
                  <template #default="{ row }">
                    <span :style="{ color: row.predicted_cash < 10 ? '#f56c6c' : row.predicted_cash < 20 ? '#e6a23c' : '#67c23a', fontWeight:600 }">{{ row.predicted_cash?.toFixed(2) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="lower_bound" label="下界(万)" width="110" align="right">
                  <template #default="{ row }">{{ row.lower_bound?.toFixed(2) }}</template>
                </el-table-column>
                <el-table-column prop="upper_bound" label="上界(万)" width="110" align="right">
                  <template #default="{ row }">{{ row.upper_bound?.toFixed(2) }}</template>
                </el-table-column>
                <el-table-column prop="alert_status" label="状态" width="80" align="center">
                  <template #default="{ row }">
                    <el-tag :type="row.alert_status === 'red' ? 'danger' : row.alert_status === 'yellow' ? 'warning' : 'success'" size="small">
                      {{ row.alert_status === 'red' ? '🔴预警' : row.alert_status === 'yellow' ? '🟡关注' : '🟢安全' }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- Tab 6: KPI智能预测（预测性成本智能） -->
      <el-tab-pane label="KPI智能预测" name="kpiForecast">
        <CostIntelligence />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { predictApi } from '../api/index'
import CostIntelligence from './CostIntelligence.vue'

const activeTab = ref('cvp')

function formatMoney(v: any, mode?: string) {
  if (v === null || v === undefined) return '--'
  if (mode === 'wan') return Number(v).toLocaleString('zh-CN', { minimumFractionDigits: 1, maximumFractionDigits: 1 })
  return Number(v).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}
function safetyColor(r: number) { return r > 25 ? 'green' : r > 10 ? 'orange' : 'red' }

// ── CVP本量利分析（增强版） ──
const cvpLoading = ref(false)
const cvpForm = ref({ fixed_cost: 617, variable_cost_rate: 48.62, unit_price: 228, current_volume: 5300 })
const cvpResult = ref<any>({})
const cvpChartRef = ref<HTMLElement | null>(null)
let cvpChart: any = null

function fillActualData() {
  cvpForm.value = { fixed_cost: 617, variable_cost_rate: 48.62, unit_price: 228, current_volume: 5300 }
  doCvpDetailed()
}

async function doCvpDetailed() {
  cvpLoading.value = true
  try {
    const payload = {
      fixed_cost: cvpForm.value.fixed_cost,
      variable_cost_rate: cvpForm.value.variable_cost_rate / 100,
      unit_price: cvpForm.value.unit_price,
      current_volume: cvpForm.value.current_volume,
    }
    cvpResult.value = await predictApi.cvpDetailed(payload) as any
    // 渲染保本图
    nextTick(() => renderCvpChart())
  } catch { ElMessage.error('CVP分析失败') }
  cvpLoading.value = false
}

function renderCvpChart() {
  if (!cvpChartRef.value || !cvpResult.value.chart_data) return
  import('echarts').then(echarts => {
    if (cvpChart) cvpChart.dispose()
    cvpChart = echarts.init(cvpChartRef.value!)
    const chartData = cvpResult.value.chart_data
    const volumes = chartData.map((d: any) => d.volume)
    const revenues = chartData.map((d: any) => d.revenue)
    const costs = chartData.map((d: any) => d.total_cost)
    const bepVol = cvpResult.value.breakeven_units || 0
    const bepRev = cvpResult.value.breakeven_revenue || 0

    cvpChart.setOption({
      grid: { left: 60, right: 30, top: 20, bottom: 40 },
      xAxis: { type: 'category', name: '销量（瓶）', data: volumes, axisLabel: { rotate: 45, fontSize: 10 } },
      yAxis: { type: 'value', name: '金额（万元）' },
      series: [
        {
          name: '总收入', type: 'line', data: revenues,
          smooth: true, lineStyle: { width: 2, color: '#409eff' },
          areaStyle: { color: 'rgba(64,158,255,0.05)' },
          symbol: 'none',
        },
        {
          name: '总成本', type: 'line', data: costs,
          smooth: true, lineStyle: { width: 2, color: '#f56c6c' },
          areaStyle: { color: 'rgba(245,108,108,0.05)' },
          symbol: 'none',
        },
        ...(bepVol > 0 ? [{
          name: '保本点', type: 'scatter',
          data: [[bepVol, bepRev]],
          symbolSize: 14,
          itemStyle: { color: '#e6a23c', borderColor: '#fff', borderWidth: 2 },
          label: { show: true, formatter: `保本点\n${bepRev.toFixed(1)}万`, position: 'right', fontSize: 11, fontWeight: 600, color: '#e6a23c' },
        }] : []),
      ],
      tooltip: { trigger: 'axis' },
      legend: { bottom: 0, icon: 'circle', itemWidth: 8, itemHeight: 8 },
    })
  })
}

// ── 投资决策 ──
const invLoading = ref(false)
const invForm = ref({ initial_investment: 100000, discount_rate: 10, cash_flows: [30000, 40000, 50000, 40000] })
const invResult = ref<any>({})

function fillInvExample() {
  invForm.value = { initial_investment: 100000, discount_rate: 10, cash_flows: [30000, 40000, 50000, 40000] }
}

async function doInvestment() {
  invLoading.value = true
  try {
    invResult.value = await predictApi.investment(invForm.value) as any
  } catch { ElMessage.error('投资决策计算失败') }
  invLoading.value = false
}

// ── 敏感性 ──
const sensLoading = ref(false)
const sensForm = ref({ base_revenue: 1000000, base_cost: 700000, step: 5 })
const sensResult = ref<any>({})

async function doSensitivity() {
  sensLoading.value = true
  try {
    sensResult.value = await predictApi.sensitivity(sensForm.value) as any
  } catch { ElMessage.error('敏感性分析失败') }
  sensLoading.value = false
}

// ── 情景 ──
const scenarioLoading = ref(false)
const scenarioForm = ref({
  optimistic: { revenue: 130, cost: 90 },
  base: { revenue: 100, cost: 100 },
  pessimistic: { revenue: 80, cost: 110 },
})
const scenarioResult = ref<any>({})

// ── 相关成本决策（CMA P2商业决策分析） ──
const relDecisionType = ref('make_or_buy')
const relResult = ref<any>(null)
const makeBuy = ref({ demand: 10000, make_variable_cost: 80, make_fixed_cost: 50000, buy_price: 90 })
const specialOrder = ref({ normal_price: 150, special_price: 120, variable_cost: 95, order_qty: 1000, capacity_used: 60, extra_fixed_cost: 0 })
const productMix = ref({ products: [
  { name: 'A产品', price: 100, var_cost: 60, constraint_usage: 2, demand: 1000 },
  { name: 'B产品', price: 150, var_cost: 100, constraint_usage: 1, demand: 800 },
  { name: 'C产品', price: 200, var_cost: 150, constraint_usage: 3, demand: 500 },
]})

function formatRelNum(v: any) {
  if (v === null || v === undefined) return '--'
  return Number(v).toLocaleString('zh-CN', { maximumFractionDigits: 2 })
}

async function runRelevantDecision() {
  try {
    let payload: any = { type: relDecisionType.value }
    if (relDecisionType.value === 'make_or_buy') payload = { ...payload, ...makeBuy.value }
    else if (relDecisionType.value === 'special_order') payload = { ...payload, ...specialOrder.value }
    else payload = { ...payload, products: productMix.value.products }
    relResult.value = await predictApi.relevantDecision(payload) as any
  } catch (e: any) {
    relResult.value = null
    ElMessage.error(e?.response?.data?.detail || e?.message || '决策计算失败')
  }
}

function fillScenarioExample() {
  scenarioForm.value = {
    optimistic: { revenue: 130, cost: 90 },
    base: { revenue: 100, cost: 100 },
    pessimistic: { revenue: 80, cost: 110 },
  }
}

async function doScenario() {
  scenarioLoading.value = true
  try {
    scenarioResult.value = await predictApi.scenario(scenarioForm.value) as any
  } catch { ElMessage.error('情景模拟失败') }
  scenarioLoading.value = false
}

// ── 现金流预测（AI事前预警） ──
const cfLoading = ref(false)
const cfEntityId = ref(Number(localStorage.getItem('cma_entity_id') || 1))

// 监听企业切换
window.addEventListener('storage', (e) => {
  if (e.key === 'cma_entity_id') cfEntityId.value = Number(e.newValue || 1)
})
const cfCurrentCash = ref(30)
const cfDays = ref(30)
const cfResult = ref<any>({})
const cfChartRef = ref<HTMLElement | null>(null)
let cfChart: any = null

async function doCashForecast() {
  cfLoading.value = true
  try {
    const payload = {
      entity_id: cfEntityId.value,
      days: cfDays.value,
      current_cash: cfCurrentCash.value,
    }
    cfResult.value = await predictApi.cashForecast(payload) as any
    nextTick(() => renderCfChart())
  } catch (e: any) {
    ElMessage.error('现金流预测失败: ' + (e?.message || ''))
  }
  cfLoading.value = false
}

function renderCfChart() {
  if (!cfChartRef.value || !cfResult.value.forecast?.length) return
  import('echarts').then(echarts => {
    if (cfChart) cfChart.dispose()
    cfChart = echarts.init(cfChartRef.value!)

    const forecast = cfResult.value.forecast
    const dates = forecast.map((d: any) => d.date.slice(5))
    const predicted = forecast.map((d: any) => d.predicted_cash)
    const lower = forecast.map((d: any) => d.lower_bound)
    const upper = forecast.map((d: any) => d.upper_bound)

    // 标记预警点
    const alertData: any[] = []
    const markAreas: any[] = []
    let lastStatus: string | null = null
    const alertRanges: { startIdx: number, endIdx: number, color: string }[] = []
    let currentRange: { startIdx: number, color: string } | null = null

    forecast.forEach((d: any, idx: number) => {
      if (d.alert_status !== 'green') {
        if (!currentRange) {
          currentRange = { startIdx: idx, color: d.alert_status === 'red' ? '#f56c6c' : '#e6a23c' }
        }
        if (d.alert_status === 'red') {
          alertData.push({
            name: d.date,
            coord: [idx, d.predicted_cash],
            itemStyle: { color: '#f56c6c' },
            symbol: 'pin',
            symbolSize: 30,
            label: { show: true, formatter: '🔴', fontSize: 16 }
          })
        }
      } else if (currentRange) {
        alertRanges.push({ startIdx: currentRange.startIdx, endIdx: idx - 1, color: currentRange.color })
        currentRange = null
      }
    })
    if (currentRange) {
      alertRanges.push({ startIdx: currentRange.startIdx, endIdx: forecast.length - 1, color: currentRange.color })
    }

    cfChart.setOption({
      grid: { left: 60, right: 30, top: 20, bottom: 40 },
      xAxis: { type: 'category', data: dates, axisLabel: { rotate: 45, fontSize: 10 } },
      yAxis: { type: 'value', name: '现金余额（万元）', min: 0 },
      series: [
        {
          name: '现金余额',
          type: 'line',
          data: predicted,
          smooth: true,
          lineStyle: { width: 2, color: '#409eff' },
          itemStyle: { color: '#409eff' },
          symbol: 'circle',
          symbolSize: 4,
          areaStyle: {
            color: {
              type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(64,158,255,0.25)' },
                { offset: 1, color: 'rgba(64,158,255,0.02)' },
              ]
            }
          },
          markArea: {
            silent: true,
            data: alertRanges.map(r => [{
              xAxis: r.startIdx,
              itemStyle: { color: r.color, opacity: 0.1 }
            }, {
              xAxis: r.endIdx
            }])
          },
          markPoint: { data: alertData },
        },
        {
          name: '置信区间上界',
          type: 'line',
          data: upper,
          smooth: true,
          lineStyle: { width: 1, color: '#909399', type: 'dashed' },
          symbol: 'none',
        },
        {
          name: '置信区间下界',
          type: 'line',
          data: lower,
          smooth: true,
          lineStyle: { width: 1, color: '#909399', type: 'dashed' },
          symbol: 'none',
          areaStyle: { color: 'rgba(144,147,153,0.05)' },
        },
      ],
      tooltip: {
        trigger: 'axis',
        formatter: function(params: any) {
          const idx = params[0]?.dataIndex
          const d = forecast[idx]
          if (!d) return ''
          const statusLabel = d.alert_status === 'red' ? '🔴预警' : d.alert_status === 'yellow' ? '🟡关注' : '🟢安全'
          return `<strong>${d.date}</strong><br/>现金余额: <strong>${d.predicted_cash.toFixed(2)}万</strong><br/>置信区间: ${d.lower_bound.toFixed(2)} ~ ${d.upper_bound.toFixed(2)}万<br/>状态: ${statusLabel}`
        }
      },
      legend: { bottom: 0, icon: 'circle', itemWidth: 8, itemHeight: 8 },
    })
  })
}

</script>

<style scoped>
.result-card { background: #f5f7fa; border-radius: 8px; padding: 16px; text-align: center; }
.r-label { font-size: 12px; color: #909399; margin-bottom: 6px; }
.r-value { font-size: 22px; font-weight: bold; color: #303133; }
.r-value.green { color: #67c23a; }
.r-value.blue { color: #409eff; }
.r-value.orange { color: #e6a23c; }
.r-value.red { color: #f56c6c; }
.r-value.purple { color: #8b5cf6; }
.trend-item { display:flex; justify-content:space-between; align-items:center; padding:6px 0; border-bottom:1px solid #f0f0f0; }
.trend-item:last-child { border-bottom:none; }
.t-label { font-size:13px; color:#606266; }
.t-value { font-weight:600; font-size:14px; }
.t-value.green { color:#67c23a; }
.t-value.red { color:#f56c6c; }
</style>
