<template>
  <div v-if="!enableDriver" class="subject-mode-hint">
    <el-empty description="当前为科目模式，请切换至驱动因子模式体验基于业务驱动的预算编制">
      <el-button type="primary" @click="switchToDriverMode">切换到驱动因子模式</el-button>
    </el-empty>
  </div>
  <div v-else>
    <!-- 模式切换条 -->
    <div style="display:flex;align-items:center;gap:12px;margin-bottom:16px;padding:12px 16px;background:#f0f9ff;border-radius:8px;border:1px solid #b3d8ff;">
      <span style="font-weight:600;color:#409eff;">📊 驱动因子模式</span>
      <span style="font-size:12px;color:#909399;">按业务逻辑编预算 — 调因子→系统自动重算</span>
      <el-button size="small" style="margin-left:auto;" @click="switchToSubjectMode">切回科目模式</el-button>
    </div>

    <el-row :gutter="16">
      <!-- 左侧：行业包 + 因子输入 -->
      <el-col :span="16">
        <!-- 行业选择 -->
        <el-card shadow="hover" style="margin-bottom:16px;">
          <template #header><span><strong>行业驱动因子包</strong> <span style="font-size:12px;color:#999;">选择行业后加载预设模板</span></span></template>
          <div style="display:flex;gap:12px;flex-wrap:wrap;">
            <div v-for="ind in industries" :key="ind.key"
              :class="['industry-card', { selected: selectedIndustry === ind.key }]"
              @click="onIndustrySelect(ind.key)"
              style="flex:1;min-width:140px;border:2px solid #e8e8e8;border-radius:10px;padding:14px;cursor:pointer;text-align:center;transition:all .2s;">
              <div style="font-size:28px;margin-bottom:6px;">{{ ind.icon }}</div>
              <div style="font-weight:600;font-size:14px;">{{ ind.label }}</div>
            </div>
          </div>

          <!-- 模板切换（选择后显示） -->
          <div v-if="templates.length > 0" style="margin-top:16px;display:flex;gap:8px;flex-wrap:wrap;">
            <span style="font-size:13px;color:#909399;line-height:32px;margin-right:4px;">预算模板：</span>
            <el-tag v-for="tpl in templates" :key="tpl.name"
              :type="selectedTemplate?.name === tpl.name ? 'primary' : 'info'"
              effect="plain"
              style="cursor:pointer;"
              @click="onTemplateSelect(tpl)">
              {{ tpl.category === 'revenue' ? '💰 ' : '💸 ' }}{{ tpl.name }}
            </el-tag>
          </div>

          <!-- 手动输入公式区 -->
          <div v-if="!selectedTemplate" style="margin-top:12px;">
            <el-alert title="请先选择行业包和预算模板，或自行输入公式" type="info" show-icon :closable="false" />
          </div>
        </el-card>

        <!-- 因子输入表单 -->
        <el-card v-if="selectedTemplate" shadow="hover" style="margin-bottom:16px;">
          <template #header>
            <div style="display:flex;justify-content:space-between;align-items:center;">
              <span><strong>📝 {{ selectedTemplate.name }}</strong></span>
              <el-tag type="success" effect="plain">{{ selectedTemplate.formula_desc }}</el-tag>
            </div>
          </template>

          <el-form label-width="160px" size="default">
            <el-form-item v-for="fd in selectedTemplate.factors" :key="fd.key" :label="fd.label">
              <div style="display:flex;align-items:center;gap:8px;width:100%;">
                <el-input-number
                  v-model="factorValues[fd.key]"
                  :default-value="fd.default"
                  :min="0"
                  :step="fd.type === 'percent' ? 1 : 100"
                  :precision="fd.type === 'percent' ? 0 : 0"
                  controls-position="right"
                  style="width:200px;"
                  @change="onFactorChange"
                />
                <span style="color:#909399;font-size:13px;">{{ fd.unit }}</span>
                <el-tag v-if="fd.type === 'percent'" size="small" type="warning" effect="plain">百分比</el-tag>
              </div>
            </el-form-item>
          </el-form>

          <div style="display:flex;gap:12px;margin-top:12px;">
            <el-button type="primary" size="large" @click="doCalculate" :loading="calculating" style="flex:1;">
              🧮 计算预算 — {{ selectedTemplate.name }}
            </el-button>
          </div>

          <!-- 计算结果 -->
          <div v-if="calculationResult !== null" style="margin-top:16px;padding:16px;background:#f0f9ff;border-radius:8px;border:1px solid #b3d8ff;">
            <div style="display:flex;align-items:center;justify-content:space-between;">
              <div>
                <div style="font-size:13px;color:#909399;">{{ selectedTemplate.formula_desc }}</div>
                <div style="font-size:32px;font-weight:700;color:#409eff;margin-top:4px;">
                  {{ formatMoney(calculationResult) }}
                  <span style="font-size:14px;font-weight:400;color:#999;"> 元</span>
                </div>
              </div>
              <div style="text-align:right;">
                <div style="font-size:12px;color:#999;">驱动因子详情</div>
                <div style="font-size:13px;margin-top:4px;">
                  <span v-for="(val, key) in factorValues" :key="key" style="margin:0 4px;background:#e6f7ff;padding:2px 8px;border-radius:12px;white-space:nowrap;display:inline-block;">
                    {{ getFactorLabel(key) }}: {{ val }}{{ getFactorUnit(key) }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 计算历史 -->
        <el-card v-if="history.length > 0" shadow="hover">
          <template #header><span>📋 最近计算记录</span></template>
          <el-table :data="history.slice(0, 5)" border stripe size="small" style="width:100%;">
            <el-table-column prop="name" label="预算项" min-width="140" />
            <el-table-column prop="calculated_value" label="结果" width="140">
              <template #default="{ row }">{{ formatMoney(row.calculated_value) }}</template>
            </el-table-column>
            <el-table-column prop="period" label="期间" width="90" />
            <el-table-column prop="created_at" label="时间" width="150" />
          </el-table>
        </el-card>
      </el-col>

      <!-- 右侧：敏感性分析 -->
      <el-col :span="8">
        <el-card v-if="sensitivityData.length > 0" shadow="hover">
          <template #header>
            <div style="display:flex;justify-content:space-between;align-items:center;">
              <span><strong>🎯 敏感性分析</strong></span>
              <el-tag size="small" type="warning">调任意因子→自动重算</el-tag>
            </div>
          </template>

          <div style="margin-bottom:12px;font-size:13px;color:#606266;">
            基准预算：<strong style="color:#409eff;font-size:18px;">{{ formatMoney(baseSensitivityValue) }}</strong> 元
          </div>

          <div v-for="s in sensitivityData" :key="s.factor_key" style="margin-bottom:20px;border:1px solid #ebeef5;border-radius:8px;padding:12px;">
            <div style="font-weight:600;font-size:13px;margin-bottom:8px;">
              {{ s.factor_label }} <span style="font-weight:400;color:#999;">(基准: {{ s.base_value }}{{ s.unit }})</span>
            </div>

            <!-- 弹性系数 -->
            <div style="margin-bottom:8px;display:flex;align-items:center;gap:8px;">
              <span style="font-size:12px;color:#909399;">弹性系数：</span>
              <el-tag size="small" :type="Math.abs(s.elasticity || 0) > 1 ? 'danger' : 'success'">
                {{ s.elasticity != null ? s.elasticity.toFixed(2) : '--' }}
              </el-tag>
            </div>

            <!-- 变动条 -->
            <div v-for="v in s.variations" :key="v.change_pct" style="display:flex;align-items:center;gap:8px;margin-bottom:6px;">
              <div style="width:60px;font-size:12px;color:#909399;text-align:right;">
                <span v-if="v.change_pct > 0" style="color:#f56c6c;">+{{ v.change_pct }}%</span>
                <span v-else style="color:#67c23a;">{{ v.change_pct }}%</span>
              </div>
              <div style="flex:1;height:18px;background:#f0f0f0;border-radius:4px;overflow:hidden;position:relative;">
                <div :style="{
                  height: '100%',
                  width: Math.min(Math.abs(v.delta_pct || 0) * 3, 100) + '%',
                  background: v.delta_pct > 0 ? '#f56c6c' : '#67c23a',
                  borderRadius: '4px',
                  transition: 'width .3s',
                  opacity: 0.7
                }"></div>
                <span style="position:absolute;right:4px;top:0;font-size:11px;line-height:18px;">
                  {{ formatMoney(v.budget_result) }}
                </span>
              </div>
              <div style="width:70px;font-size:11px;text-align:right;">
                <span :style="{color: v.delta_pct > 0 ? '#f56c6c' : v.delta_pct < 0 ? '#67c23a' : '#999'}">
                  {{ v.delta > 0 ? '+' : '' }}{{ formatMoney(v.delta) }}
                </span>
              </div>
            </div>
          </div>

          <el-alert
            title="提示：调整左侧任意因子数值，点击「计算预算」后自动更新敏感性分析"
            type="info"
            show-icon
            :closable="false"
            style="margin-top:8px;"
          />
        </el-card>

        <el-card v-else shadow="hover" style="margin-bottom:16px;">
          <template #header><span><strong>🎯 敏感性分析</strong></span></template>
          <el-empty description="请先选择行业模板并计算预算" :image-size="60" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

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

const enableDriver = ref(false)
const loading = ref(false)
const calculating = ref(false)
const selectedIndustry = ref('general')
const selectedTemplate = ref<any>(null)
const industries = ref<any[]>([])
const templates = ref<any[]>([])
const factorValues = reactive<Record<string, number>>({})
const calculationResult = ref<number | null>(null)
const sensitivityData = ref<any[]>([])
const baseSensitivityValue = ref(0)
const history = ref<any[]>([])

// 加载模式
async function loadMode() {
  try {
    const r: any = await driverBudgetApi.getMode()
    enableDriver.value = r.mode === 'driver'
  } catch {
    enableDriver.value = false
  }
}

async function switchToDriverMode() {
  try {
    await driverBudgetApi.setMode({ mode: 'driver' })
    enableDriver.value = true
    ElMessage.success('已切换到驱动因子模式')
    loadIndustries()
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.detail || '切换失败')
  }
}

async function switchToSubjectMode() {
  try {
    await driverBudgetApi.setMode({ mode: 'subject' })
    enableDriver.value = false
    ElMessage.success('已切换到科目模式')
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.detail || '切换失败')
  }
}

// 加载行业包
async function loadIndustries() {
  try {
    const r: any = await driverBudgetApi.getIndustries()
    industries.value = r.data || []
    if (industries.value.length > 0) {
      selectedIndustry.value = industries.value[0].key
      loadTemplates()
    }
  } catch {
    industries.value = [
      { key: 'general', label: '通用模板', icon: '📦' },
      { key: 'trade', label: '贸易经销版', icon: '🏪' },
      { key: 'it', label: 'IT服务版', icon: '💻' },
    ]
    loadTemplates()
  }
}

// 加载模板
async function loadTemplates() {
  templates.value = []
  selectedTemplate.value = null
  try {
    const r: any = await driverBudgetApi.getTemplates({ industry: selectedIndustry.value })
    templates.value = r.data || []
    if (templates.value.length > 0) {
      onTemplateSelect(templates.value[0])
    }
  } catch {
    templates.value = []
  }
}

function onIndustrySelect(key: string) {
  selectedIndustry.value = key
  calculationResult.value = null
  sensitivityData.value = []
  loadTemplates()
}

function onTemplateSelect(tpl: any) {
  selectedTemplate.value = tpl
  calculationResult.value = null
  sensitivityData.value = []

  // 初始化因子值
  Object.keys(factorValues).forEach(k => delete factorValues[k])
  for (const fd of tpl.factors) {
    factorValues[fd.key] = fd.default ?? 0
  }
}

function getFactorLabel(key: string): string {
  if (!selectedTemplate.value) return key
  const fd = selectedTemplate.value.factors.find((f: any) => f.key === key)
  return fd?.label || key
}

function getFactorUnit(key: string): string {
  if (!selectedTemplate.value) return ''
  const fd = selectedTemplate.value.factors.find((f: any) => f.key === key)
  return fd?.unit || ''
}

function onFactorChange() {
  // 实时预览不自动计算
}

async function doCalculate() {
  if (!selectedTemplate.value) return
  calculating.value = true

  try {
    const factorsObj: Record<string, number> = {}
    for (const key of Object.keys(factorValues)) {
      factorsObj[key] = factorValues[key]
    }

    // 主计算
    const calcResult: any = await driverBudgetApi.calculate({
      template_id: null,
      name: selectedTemplate.value.name,
      industry: selectedIndustry.value,
      formula_text: selectedTemplate.value.formula_text,
      formula_desc: selectedTemplate.value.formula_desc,
      factor_defs: selectedTemplate.value.factors,
      factors: factorsObj,
      period: `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`,
    })
    calculationResult.value = calcResult.calculated_value

    // 敏感性分析
    const sensResult: any = await driverBudgetApi.sensitivity({
      factors: factorsObj,
      formula_text: selectedTemplate.value.formula_text,
      factor_defs: selectedTemplate.value.factors,
    })
    sensitivityData.value = sensResult.sensitivity || []
    baseSensitivityValue.value = sensResult.base_value

    ElMessage.success(`预算计算结果：${formatMoney(calcResult.calculated_value)} 元`)
    loadHistory()
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.detail || e?.message || '计算失败')
  }
  calculating.value = false
}

// 加载历史
async function loadHistory() {
  try {
    const r: any = await driverBudgetApi.getHistory()
    history.value = r.data || []
  } catch {
    history.value = []
  }
}

function formatMoney(v: any): string {
  if (v === null || v === undefined) return '--'
  const n = Number(v)
  if (Math.abs(n) >= 10000) {
    return (n / 10000).toFixed(2) + '万'
  }
  return n.toLocaleString('zh-CN')
}

onMounted(() => {
  loadMode()
})
</script>

<style scoped>
.industry-card {
  transition: all 0.2s;
}
.industry-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64,158,255,0.15);
}
.industry-card.selected {
  border-color: #409eff;
  background: #ecf5ff;
  box-shadow: 0 2px 8px rgba(64,158,255,0.2);
}
:deep(.el-form-item) {
  margin-bottom: 12px;
}
.subject-mode-hint {
  padding: 60px 0;
}
</style>
