<template>
  <div class="sales-page">
    <section class="header-bar">
      <h1 class="header-title">促销效果分析</h1>
      <div class="header-actions">
        <el-upload action="" :auto-upload="false" :show-file-list="false" accept=".xlsx,.xls,.csv" :on-change="handleFileChange">
          <el-button size="small" icon="el-icon-upload2">销售数据</el-button>
        </el-upload>
        <el-upload action="" :auto-upload="false" :show-file-list="false" accept=".xlsx,.xls" :on-change="handleProductFileChange">
          <el-button size="small" icon="el-icon-folder-add">产品资料</el-button>
        </el-upload>
        <el-button size="small" type="primary" :loading="loading" icon="el-icon-data-analysis" @click="runAnalysis">新建分析</el-button>
        <el-button size="small" icon="el-icon-download" :disabled="!hasResults" @click="exportReport">导出报告</el-button>
      </div>
    </section>

    <section class="activity-bar">
      <button v-for="activity in activities" :key="activity.name" :class="{ active: activeActivity === activity.name }" @click="activeActivity = activity.name">
        <strong>{{ activity.name }}</strong>
        <span>{{ activity.date }}</span>
      </button>
      <button class="add" @click="dialogVisible = true"><i class="el-icon-plus"></i> 自定义活动</button>
    </section>

    <section class="chart-panel">
      <div class="chart-header">
        <h3>活动前后销量对比</h3>
        <p>{{ activeActivity }} · 基于上传销售数据自动评估</p>
      </div>
      <div ref="effectChart" class="chart"></div>
    </section>

    <section class="two-col">
      <div class="panel">
        <h3>ROI 分析</h3>
        <div class="roi-score">
          <strong>{{ roiValue }}</strong>
          <p>{{ roiLevel }}</p>
        </div>
        <div class="roi-details">
          <div><span>投入估算</span><b>{{ formatMoney(investment) }}</b></div>
          <div><span>增量产出</span><b>{{ formatMoney(incrementRevenue) }}</b></div>
        </div>
      </div>
      <div class="panel">
        <h3>增量效果</h3>
        <div class="increment-grid">
          <div><span>销量提升率</span><strong>{{ percent(effect.quantity_lift) }}</strong></div>
          <div><span>销售额提升率</span><strong>{{ percent(effect.revenue_lift) }}</strong></div>
          <div><span>促销占比</span><strong>{{ percent(effect.promo_ratio) }}</strong></div>
          <div><span>综合评分</span><strong>{{ score }}</strong></div>
        </div>
      </div>
    </section>

    <section class="panel">
      <div class="panel-head">
        <h3>详细数据对比</h3>
        <el-button type="text" icon="el-icon-view" @click="showDailyDetail">查看活动明细</el-button>
      </div>
      <el-table :data="detailRows" size="small">
        <el-table-column prop="name" label="指标名称" min-width="140" />
        <el-table-column prop="before" label="活动前" min-width="120" />
        <el-table-column prop="during" label="活动中" min-width="120" />
        <el-table-column prop="after" label="活动后" min-width="120" />
        <el-table-column prop="change" label="变化率" min-width="120">
          <template slot-scope="{ row }"><span :class="row.changeValue >= 0 ? 'positive' : 'negative'">{{ row.change }}</span></template>
        </el-table-column>
      </el-table>
    </section>

    <el-dialog title="新建促销活动分析" :visible.sync="dialogVisible" width="460px">
      <el-form label-position="top">
        <el-form-item label="活动名称"><el-input v-model="customActivity.name" /></el-form-item>
        <el-form-item label="活动日期"><el-date-picker v-model="customActivity.range" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" /></el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createActivity">创建</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { analyzeSaleEffect, analyzeSaleEffectWithFile, getSaleEffectResults, uploadProductFile } from '@/api/client'

export default {
  name: 'SaleEffectAnalysis',
  data() {
    return {
      chart: null,
      loading: false,
      file: null,
      productFile: null,
      activeActivity: '双 11 大促',
      activities: [
        { name: '双 11 大促', date: '11-01 至 11-11' },
        { name: '618 大促', date: '06-01 至 06-18' },
        { name: '新品首发', date: '03-15 至 03-21' },
        { name: '清仓特卖', date: '01-10 至 01-20' }
      ],
      results: {},
      dialogVisible: false,
      customActivity: { name: '', range: [] }
    }
  },
  computed: {
    hasResults() {
      return Object.keys(this.results || {}).length > 0
    },
    summary() {
      return this.results.summary || {}
    },
    effect() {
      return this.results.effect_evaluation || {}
    },
    customEffect() {
      return this.results.custom_activity || null
    },
    score() {
      return Number(this.effect.score || 0).toFixed(1)
    },
    roiValue() {
      const roi = this.investment ? this.incrementRevenue / this.investment : Number(this.effect.score || 0) / 30
      return Math.max(0, roi).toFixed(1)
    },
    roiLevel() {
      const roi = Number(this.roiValue)
      if (roi >= 3) return '投资回报率优秀'
      if (roi >= 1.5) return '投资回报率良好'
      return '需要优化促销投入'
    },
    incrementRevenue() {
      return Number(this.effect.incremental_revenue || this.summary.total_revenue * (Number(this.effect.revenue_lift || 0) / 100) || 0)
    },
    investment() {
      return Math.max(1, Number(this.summary.total_revenue || 0) * 0.05)
    },
    detailRows() {
      const qLift = Number(this.effect.quantity_lift || 0)
      const rLift = Number(this.effect.revenue_lift || 0)
      const baseQty = Number(this.summary.total_quantity || 0) / 30 || 2340
      const baseRevenue = Number(this.summary.total_revenue || 0) / 30 || 187200
      if (this.customEffect) {
        const before = this.customEffect.before || {}
        const during = this.customEffect.during || {}
        const after = this.customEffect.after || {}
        return [
          this.row('日均销量', before.quantity || 0, during.quantity || 0, after.quantity || 0, Number(this.customEffect.quantity_lift || 0), '件'),
          this.row('日均销售额', before.revenue || 0, during.revenue || 0, after.revenue || 0, Number(this.customEffect.revenue_lift || 0), '元'),
          this.row('促销占比', 0, Number(this.effect.promo_ratio || 0), Number(this.effect.promo_ratio || 0) * 0.6, Number(this.effect.promo_ratio || 0), '%'),
          this.row('综合评分', 60, Number(this.effect.score || 0), 70, Number(this.effect.score || 0) - 60, '分')
        ]
      }
      return [
        this.row('日均销量', baseQty, baseQty * (1 + qLift / 100), baseQty * 1.15, qLift, '件'),
        this.row('日均销售额', baseRevenue, baseRevenue * (1 + rLift / 100), baseRevenue * 1.12, rLift, '元'),
        this.row('促销占比', 0, Number(this.effect.promo_ratio || 0), Number(this.effect.promo_ratio || 0) * 0.6, Number(this.effect.promo_ratio || 0), '%'),
        this.row('综合评分', 60, Number(this.effect.score || 0), 70, Number(this.effect.score || 0) - 60, '分')
      ]
    }
  },
  mounted() {
    this.chart = echarts.init(this.$refs.effectChart)
    window.addEventListener('resize', this.resize)
    this.loadCachedResults()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resize)
    if (this.chart) this.chart.dispose()
  },
  methods: {
    handleFileChange(file) { this.file = file.raw },
    handleProductFileChange(file) { this.productFile = file.raw },
    async loadCachedResults() {
      try {
        const response = await getSaleEffectResults()
        if (response && response.success) this.results = response.data || {}
      } catch (e) {
        this.results = {}
      }
      this.$nextTick(this.renderChart)
    },
    async runAnalysis() {
      if (!this.file && !this.hasResults) {
        this.$modal.msgError('请先上传销售数据')
        return
      }
      this.loading = true
      try {
        if (this.productFile) await uploadProductFile(this.productFile)
        if (this.file) {
          const response = await analyzeSaleEffectWithFile(this.file, this.activityPayload())
          if (!response.success) throw new Error(response.message || '分析失败')
          this.results = response.data || {}
        } else if (this.hasResults && Object.keys(this.activityPayload()).length) {
          const response = await analyzeSaleEffect(this.activityPayload())
          if (!response.success) throw new Error(response.message || '分析失败')
          this.results = response.data || {}
        }
        this.renderChart()
        this.$modal.msgSuccess('促销效果分析完成')
      } catch (error) {
        this.$modal.msgError(error.message || '分析失败')
      } finally {
        this.loading = false
      }
    },
    renderChart() {
      if (!this.chart) return
      const rows = this.detailRows
      const qty = rows[0]
      const rev = rows[1]
      this.chart.setOption({
        tooltip: { trigger: 'axis' },
        legend: { top: 0 },
        grid: { left: 45, right: 24, bottom: 40, top: 45 },
        xAxis: { type: 'category', data: ['活动前', '活动中', '活动后'] },
        yAxis: { type: 'value' },
        series: [
          { name: '销量', type: 'bar', data: [qty.rawBefore, qty.rawDuring, qty.rawAfter], itemStyle: { color: '#f59e0b', borderRadius: [6, 6, 0, 0] } },
          { name: '销售额', type: 'bar', data: [rev.rawBefore, rev.rawDuring, rev.rawAfter], itemStyle: { color: '#667eea', borderRadius: [6, 6, 0, 0] } }
        ]
      })
    },
    row(name, before, during, after, change, unit) {
      const format = value => unit === '元' ? this.formatMoney(value) : `${Math.round(value).toLocaleString()}${unit}`
      return {
        name,
        rawBefore: before,
        rawDuring: during,
        rawAfter: after,
        before: format(before),
        during: format(during),
        after: format(after),
        changeValue: change,
        change: `${change >= 0 ? '+' : ''}${Number(change).toFixed(1)}%`
      }
    },
    percent(value) {
      return `${Number(value || 0).toFixed(1)}%`
    },
    formatMoney(value) {
      return `￥${Math.round(Number(value || 0)).toLocaleString()}`
    },
    createActivity() {
      if (!this.customActivity.name) return
      this.activities.push({ name: this.customActivity.name, date: '自定义周期' })
      this.activeActivity = this.customActivity.name
      this.dialogVisible = false
      if (this.file || this.hasResults) this.runAnalysis()
    },
    activityPayload() {
      const range = this.customActivity.range || []
      if (!range.length || this.activeActivity !== this.customActivity.name) return {}
      return {
        activity_range: {
          start: this.formatDate(range[0]),
          end: this.formatDate(range[1])
        }
      }
    },
    formatDate(value) {
      const date = new Date(value)
      if (Number.isNaN(date.getTime())) return ''
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    showDailyDetail() {
      this.$modal.msg('明细数据已在下方表格展示')
    },
    exportReport() {
      const blob = new Blob([JSON.stringify(this.results, null, 2)], { type: 'application/json;charset=utf-8' })
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `sale_effect_${Date.now()}.json`
      link.click()
      URL.revokeObjectURL(url)
    },
    resize() {
      if (this.chart) this.chart.resize()
    }
  }
}
</script>

<style scoped lang="scss">
.sales-page { padding: 20px; max-width: 1400px; margin: 0 auto; background: #f0f2f5; min-height: calc(100vh - 84px); }
.header-bar, .activity-bar, .chart-panel, .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; }
.activity-bar { display: flex; gap: 12px; padding: 20px 24px; margin-bottom: 20px; flex-wrap: wrap; }
.activity-bar button { border: 2px solid transparent; background: #f5f7fa; border-radius: 8px; padding: 10px 18px; cursor: pointer; color: #303133; }
.activity-bar button strong, .activity-bar button span { display: block; }
.activity-bar button span { font-size: 11px; opacity: .75; margin-top: 3px; }
.activity-bar button.active { color: white; background: linear-gradient(135deg,#667eea,#764ba2); }
.activity-bar button.add { border-style: dashed; }
.chart-panel, .panel { padding: 24px; margin-bottom: 20px; }
.chart-header { text-align: center; margin-bottom: 12px; }
.chart-header h3 { margin: 0 0 6px; font-size: 18px; }
.chart-header p { margin: 0; color: #909399; }
.chart { height: 350px; }
.two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
.panel h3 { margin: 0 0 20px; font-size: 16px; color: #303133; }
.roi-score { text-align: center; }
.roi-score strong { display: block; font-size: 48px; color: #667eea; }
.roi-score p { color: #909399; }
.roi-details { display: flex; justify-content: space-around; border-top: 1px solid #f0f0f0; padding-top: 16px; }
.roi-details div { text-align: center; }
.roi-details span { display: block; color: #909399; font-size: 12px; margin-bottom: 6px; }
.increment-grid { display: grid; grid-template-columns: repeat(2,1fr); gap: 15px; }
.increment-grid div { text-align: center; background: #f8f9fa; border-radius: 8px; padding: 20px; }
.increment-grid span { display: block; color: #909399; font-size: 12px; margin-bottom: 8px; }
.increment-grid strong { font-size: 24px; color: #303133; }
.panel-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
.panel-head h3 { margin: 0; }
.positive { color: #67c23a; font-weight: 600; }
.negative { color: #f56c6c; font-weight: 600; }
@media (max-width: 1100px) { .two-col { grid-template-columns: 1fr; } }
</style>
