<template>
  <div class="sales-page">
    <section class="header-bar">
      <h1 class="header-title">特征重要性分析</h1>
      <div class="header-actions">
        <el-upload ref="upload" action="" :auto-upload="false" :show-file-list="false" accept=".xlsx,.xls,.csv" :on-change="handleFileChange">
          <el-button size="small" plain icon="el-icon-upload2">销售数据</el-button>
        </el-upload>
        <el-button size="small" type="success" :loading="loading" icon="el-icon-refresh" @click="startAnalysis">重新分析</el-button>
        <el-button size="small" type="primary" icon="el-icon-download" @click="exportModel">导出模型</el-button>
      </div>
    </section>

    <section class="settings-bar">
      <div class="setting-item">
        <label>目标变量</label>
        <el-select v-model="targetVar" size="small">
          <el-option label="销量" value="quantity" />
          <el-option label="销售额" value="revenue" />
        </el-select>
      </div>
      <div class="setting-item">
        <label>时间范围</label>
        <el-select v-model="timeRange" size="small">
          <el-option label="近 30 天" value="30" />
          <el-option label="近 60 天" value="60" />
          <el-option label="近 90 天" value="90" />
          <el-option label="全部" value="all" />
        </el-select>
      </div>
      <div class="setting-item">
        <label>模型类型</label>
        <el-select v-model="modelType" size="small">
          <el-option label="销售趋势模型" value="trend" />
          <el-option label="促销敏感模型" value="promo" />
          <el-option label="线性回归" value="linear" />
        </el-select>
      </div>
      <span class="file-hint">{{ fileName || '可上传销售数据刷新特征权重' }}</span>
    </section>

    <section class="panel">
      <h3>特征重要性（贡献度）</h3>
      <div class="feature-list">
        <div
          v-for="feature in normalizedFeatures"
          :key="feature.name"
          class="feature-item"
          :class="{ active: selectedFeature.name === feature.name }"
          @click="selectedFeature = feature"
        >
          <span class="feature-name">{{ feature.name }}</span>
          <div class="feature-bar-container">
            <div class="feature-bar" :class="feature.level" :style="{ width: feature.value + '%' }">
              <span>{{ feature.value }}%</span>
            </div>
          </div>
          <strong>{{ feature.value }}%</strong>
        </div>
      </div>
    </section>

    <section class="two-col">
      <div class="panel">
        <h3>特征相关性热力图</h3>
        <div class="heatmap">
          <div class="heat-row header-row">
            <span></span>
            <b v-for="feature in heatmapLabels" :key="feature">{{ feature }}</b>
          </div>
          <div v-for="row in heatmapMatrix" :key="row.name" class="heat-row">
            <span>{{ row.name }}</span>
            <button
              v-for="cell in row.values"
              :key="row.name + cell.name"
              :style="{ backgroundColor: heatColor(cell.value) }"
              :title="`${row.name} 与 ${cell.name}: ${cell.value}`"
            >
              {{ cell.value }}
            </button>
          </div>
        </div>
      </div>
      <div class="panel">
        <h3>特征详细分析</h3>
        <div class="feature-detail">
          <h2>{{ selectedFeature.name || '-' }}</h2>
          <div class="detail-row">
            <span>边际效应</span>
            <strong class="positive">+{{ Math.max(1, selectedFeature.value / 2).toFixed(1) }}%</strong>
          </div>
          <div class="detail-row">
            <span>建议区间</span>
            <em>{{ selectedFeature.range || '保持稳定投入' }}</em>
          </div>
          <p>{{ selectedFeature.description || '请选择一个特征查看其对销量预测的影响。' }}</p>
        </div>
      </div>
    </section>

    <section class="panel">
      <h3>AI 洞察与建议</h3>
      <div class="insights">
        <div v-for="item in insights" :key="item" class="insight-card">
          <i class="el-icon-magic-stick"></i>
          <p>{{ item }}</p>
          <el-button size="mini" type="text" @click="copyText(item)">复制建议</el-button>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import { analyzeSaleTrendWithFile, getSaleTrendResults } from '@/api/client'

export default {
  name: 'FeatureImportanceAnalysis',
  data() {
    return {
      loading: false,
      file: null,
      fileName: '',
      targetVar: 'quantity',
      timeRange: '90',
      modelType: 'trend',
      results: {},
      selectedFeature: {}
    }
  },
  computed: {
    featureImportance() {
      return this.results.feature_importance || {
        features: ['价格', '促销力度', '退款率', '季节性', '时间趋势', '品类影响', 'SKU影响'],
        importance: [15, 15, 10, 15, 20, 10, 15]
      }
    },
    normalizedFeatures() {
      const descriptions = {
        '价格': '价格变化会直接影响用户购买决策，建议结合毛利率设置动态价格区间。',
        '促销力度': '促销力度越高，销量通常越容易被拉动，但需要控制利润损耗。',
        '退款率': '退款率高会削弱销量预测稳定性，应重点排查质量和售后问题。',
        '季节性': '季节性决定周期波动，应提前规划旺季备货和预算。',
        '时间趋势': '长期趋势反映自然增长或衰退，适合作为基准预测因子。',
        '品类影响': '不同品类之间销量结构差异明显，需要分层预测。',
        'SKU影响': '头部 SKU 对预测结果贡献高，应优先保证数据质量。'
      }
      return (this.featureImportance.features || []).map((name, index) => {
        const value = Math.round(Number((this.featureImportance.importance || [])[index] || 0))
        return {
          name,
          value,
          level: value >= 20 ? 'high' : value >= 12 ? 'medium' : value >= 6 ? 'low' : 'minor',
          description: descriptions[name] || `${name} 对销量预测有 ${value}% 的贡献。`,
          range: value >= 15 ? '建议重点监控' : '维持常规监控'
        }
      }).sort((a, b) => b.value - a.value)
    },
    heatmapLabels() {
      return (this.featureImportance.features || []).slice(0, 7)
    },
    heatmapMatrix() {
      const matrix = this.featureImportance.correlation_matrix || []
      return this.heatmapLabels.map((name, rowIndex) => ({
        name,
        values: this.heatmapLabels.map((col, colIndex) => ({
          name: col,
          value: Number((((matrix[rowIndex] || [])[colIndex]) || (rowIndex === colIndex ? 1 : 0)).toFixed(2))
        }))
      }))
    },
    insights() {
      const top = this.normalizedFeatures[0] || { name: '时间趋势' }
      return [
        `${top.name} 是当前最主要驱动因素，建议优先保证该字段的数据完整性。`,
        '促销、价格和季节性建议进入同一套对照分析，避免单因子误判。',
        '对高贡献特征建立阈值告警，可以提升预测解释性和运营响应速度。'
      ]
    }
  },
  watch: {
    normalizedFeatures: {
      immediate: true,
      handler(list) {
        if (!this.selectedFeature.name && list.length) this.selectedFeature = list[0]
      }
    }
  },
  mounted() {
    this.loadCachedResults()
  },
  methods: {
    handleFileChange(file) {
      this.file = file.raw
      this.fileName = file.name
    },
    async loadCachedResults() {
      try {
        const response = await getSaleTrendResults()
        if (response && response.success) this.results = response.data || {}
      } catch (e) {
        this.results = {}
      }
    },
    async startAnalysis() {
      this.loading = true
      try {
        if (this.file) {
          const response = await analyzeSaleTrendWithFile(this.file)
          if (!response.success) throw new Error(response.message || '分析失败')
          this.results = response.data || {}
          this.selectedFeature = this.normalizedFeatures[0] || {}
          this.$modal.msgSuccess('特征分析完成')
        } else {
          await this.loadCachedResults()
          if (!Object.keys(this.results || {}).length) {
            this.$modal.msgWarning('暂无趋势分析缓存，请先上传销售数据')
            return
          }
          this.selectedFeature = this.normalizedFeatures[0] || {}
          this.$modal.msgSuccess('已加载缓存特征分析')
        }
      } catch (error) {
        this.$modal.msgError(error.message || '分析失败')
      } finally {
        this.loading = false
      }
    },
    heatColor(value) {
      if (value >= 0.8) return '#f97316'
      if (value >= 0.55) return '#22c55e'
      if (value >= 0.35) return '#3b82f6'
      return '#94a3b8'
    },
    copyText(text) {
      navigator.clipboard && navigator.clipboard.writeText(text)
      this.$modal.msgSuccess('已复制')
    },
    exportModel() {
      const blob = new Blob([JSON.stringify(this.results.feature_importance || {}, null, 2)], { type: 'application/json;charset=utf-8' })
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `feature_importance_${Date.now()}.json`
      link.click()
      URL.revokeObjectURL(url)
    }
  }
}
</script>

<style scoped lang="scss">
.sales-page { padding: 20px; max-width: 1400px; margin: 0 auto; background: #f0f2f5; min-height: calc(100vh - 84px); }
.header-bar, .settings-bar, .panel { background: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,.06); }
.header-bar { display: flex; justify-content: space-between; align-items: center; padding: 16px 24px; margin-bottom: 20px; gap: 16px; flex-wrap: wrap; }
.header-title { margin: 0; font-size: 20px; font-weight: 600; color: #303133; }
.header-actions { display: flex; gap: 10px; flex-wrap: wrap; }
.settings-bar { display: flex; gap: 15px; align-items: flex-end; padding: 20px 24px; margin-bottom: 20px; flex-wrap: wrap; }
.setting-item { display: flex; flex-direction: column; gap: 6px; min-width: 150px; }
.setting-item label { font-size: 12px; color: #606266; }
.file-hint { margin-left: auto; color: #67c23a; font-size: 13px; }
.panel { padding: 24px; margin-bottom: 20px; min-width: 0; }
.panel h3 { margin: 0 0 20px; font-size: 16px; color: #303133; }
.feature-list { display: flex; flex-direction: column; gap: 12px; }
.feature-item { display: flex; align-items: center; gap: 15px; padding: 10px 12px; border-radius: 6px; cursor: pointer; }
.feature-item:hover, .feature-item.active { background: #eef7fb; }
.feature-item.active { border-left: 3px solid #17a2b8; }
.feature-name { width: 120px; flex-shrink: 0; color: #606266; }
.feature-bar-container { flex: 1; height: 24px; background: #f0f2f5; border-radius: 12px; overflow: hidden; }
.feature-bar { height: 100%; color: white; display: flex; align-items: center; justify-content: flex-end; padding-right: 10px; border-radius: 12px; transition: width .3s; }
.feature-bar.high { background: linear-gradient(90deg,#667eea,#764ba2); }
.feature-bar.medium { background: linear-gradient(90deg,#409eff,#667eea); }
.feature-bar.low { background: linear-gradient(90deg,#67c23a,#85ce61); }
.feature-bar.minor { background: linear-gradient(90deg,#909399,#b4bccc); }
.two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
.heatmap { overflow: auto; }
.heat-row { display: grid; grid-template-columns: 80px repeat(7, 48px); gap: 4px; align-items: center; margin-bottom: 4px; }
.heat-row span, .heat-row b { font-size: 12px; color: #606266; text-align: right; padding-right: 6px; }
.heat-row b { text-align: center; padding: 0; }
.heat-row button { width: 48px; height: 40px; border: 0; color: white; border-radius: 4px; cursor: pointer; }
.feature-detail { background: #f8f9fa; border-radius: 8px; padding: 20px; }
.feature-detail h2 { margin: 0 0 18px; font-size: 20px; }
.detail-row { display: flex; justify-content: space-between; margin-bottom: 16px; color: #606266; }
.positive { color: #67c23a; }
.detail-row em { background: #67c23a; color: white; border-radius: 4px; padding: 4px 10px; font-style: normal; }
.feature-detail p { color: #606266; line-height: 1.7; }
.insights { display: grid; grid-template-columns: repeat(auto-fit,minmax(260px,1fr)); gap: 15px; }
.insight-card { background: linear-gradient(135deg,#fffbeb,#fef3c7); border-radius: 8px; padding: 18px; }
.insight-card i { font-size: 22px; color: #f59e0b; }
.insight-card p { line-height: 1.6; color: #606266; }
@media (max-width: 1100px) { .two-col { grid-template-columns: 1fr; } .file-hint { margin-left: 0; } }
</style>
