<template>
  <div class="app-container">
    <div class="page-header">
      <div>
        <h2><i class="el-icon-data-analysis"></i> SKU生命周期整体看板</h2>
        <p class="page-desc">从订单表和产品表直接统计生命周期概览，不依赖 Python 分析接口</p>
      </div>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small"
          clearable
        />
        <el-button size="small" type="primary" :loading="loading" @click="fetchOverview">刷新数据</el-button>
        <el-button size="small" type="success" :disabled="!hasData" @click="exportResults">导出分析</el-button>
      </div>
    </div>

    <el-alert
      v-if="error"
      :title="error"
      type="error"
      show-icon
      class="mb-20"
    />

    <el-alert
      v-if="generatedAt"
      :title="`数据更新时间：${generatedAt}`"
      type="info"
      show-icon
      class="mb-20"
    />

    <el-row :gutter="20" class="mb-20">
      <el-col v-for="item in statCards" :key="item.label" :xs="24" :sm="12" :md="8" :lg="4">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-info">
              <p class="stat-label">{{ item.label }}</p>
              <p class="stat-value">{{ item.value }}</p>
              <p class="stat-desc" :class="item.descClass">{{ item.desc }}</p>
            </div>
            <div class="stat-icon" :class="item.iconClass">
              <i :class="item.icon"></i>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mb-20">
      <el-col :xs="24" :md="12">
        <el-card>
          <div slot="header">
            <span><i class="el-icon-pie-chart"></i> SKU生命周期阶段分布</span>
            <span class="header-desc">按 SKU 数量占比</span>
          </div>
          <div ref="stageDistributionChart" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-card>
          <div slot="header">
            <span><i class="el-icon-data-line"></i> 各阶段关键指标对比</span>
            <span class="header-desc">销售额/销量</span>
          </div>
          <div ref="stageMetricsChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mb-20">
      <el-col :xs="24" :md="12">
        <el-card>
          <div slot="header">
            <span><i class="el-icon-s-marketing"></i> 阶段平均时长（天）</span>
            <span class="header-desc">按阶段区间统计</span>
          </div>
          <div ref="avgDurationChart" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-card>
          <div slot="header">
            <span><i class="el-icon-s-data"></i> 阶段转化漏斗</span>
            <span class="header-desc">引入→成长→成熟→衰退</span>
          </div>
          <div ref="funnelChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-card>
      <div slot="header">
        <span><i class="el-icon-document"></i> SKU生命周期明细</span>
        <span class="header-desc">展示前 100 条</span>
      </div>
      <el-table :data="displaySkuList" border stripe height="420">
        <el-table-column prop="sku" label="SKU" min-width="140" />
        <el-table-column prop="productName" label="商品名称" min-width="220" show-overflow-tooltip />
        <el-table-column prop="currentStage" label="当前阶段" min-width="100">
          <template slot-scope="scope">
            <el-tag :type="stageTagType(scope.row.currentStage)" size="small">
              {{ scope.row.currentStage }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalQuantity" label="总销量" min-width="100" sortable />
        <el-table-column prop="totalRevenue" label="总销售额" min-width="120" sortable>
          <template slot-scope="scope">{{ formatCurrency(scope.row.totalRevenue) }}</template>
        </el-table-column>
        <el-table-column prop="lifecycleDays" label="周期天数" min-width="100" sortable />
        <el-table-column prop="complete" label="完整周期" min-width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.complete ? 'success' : 'info'" size="small">
              {{ scope.row.complete ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getLifecycleDatabaseOverview } from '@/api/lifecycleDatabase'
require('echarts/theme/macarons')

const CACHE_KEY = 'lifecycle_database_overview_cache'

function loadCachedOverview() {
  try {
    const raw = localStorage.getItem(CACHE_KEY)
    return raw ? JSON.parse(raw) : {}
  } catch (e) {
    return {}
  }
}

export default {
  name: 'LifecycleOverviewDatabase',
  data() {
    return {
      loading: false,
      error: '',
      dateRange: [],
      overview: loadCachedOverview(),
      stageDistributionChart: null,
      stageMetricsChart: null,
      avgDurationChart: null,
      funnelChart: null
    }
  },
  computed: {
    hasData() {
      return !!this.overview && Object.keys(this.overview).length > 0
    },
    summary() {
      return (this.overview && this.overview.summary) || {}
    },
    generatedAt() {
      return this.overview && this.overview.generatedAt
    },
    displaySkuList() {
      const list = (this.overview && this.overview.skuList) || []
      return list.slice(0, 100)
    },
    statCards() {
      return [
        { label: '订单总数（估）', value: this.summary.orderCount || 0, desc: '按销量汇总', icon: 'el-icon-s-order', iconClass: 'stat-icon-purple' },
        { label: 'SKU总数', value: this.summary.skuCount || 0, desc: '数据库 SKU', icon: 'el-icon-box', iconClass: 'stat-icon-blue' },
        { label: '商品总数', value: this.summary.productCount || 0, desc: '按商品名称去重', icon: 'el-icon-s-goods', iconClass: 'stat-icon-teal' },
        { label: '完整生命周期SKU', value: this.summary.completeCount || 0, desc: `完整占比 ${this.summary.completeRatio || 0}%`, descClass: 'stat-desc-success', icon: 'el-icon-success', iconClass: 'stat-icon-green' },
        { label: '平均生命周期时长（天）', value: this.summary.avgLifecycleDays || 0, desc: '仅计算完整 SKU', icon: 'el-icon-time', iconClass: 'stat-icon-yellow' },
        { label: '数据不足SKU', value: this.summary.insufficientCount || 0, desc: '周期或销售记录不足', icon: 'el-icon-warning', iconClass: 'stat-icon-red' }
      ]
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
      if (this.hasData) {
        this.renderCharts()
      }
      this.fetchOverview()
    })
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    this.destroyCharts()
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    fetchOverview() {
      const params = {}
      if (this.dateRange && this.dateRange.length === 2) {
        params.startDate = this.dateRange[0]
        params.endDate = this.dateRange[1]
      }

      this.loading = true
      this.error = ''
      getLifecycleDatabaseOverview(params).then(response => {
        this.overview = response.data || {}
        this.persistOverview()
        this.$nextTick(() => {
          this.renderCharts()
        })
      }).catch(error => {
        this.error = (error && error.message) || '获取生命周期数据库总览失败'
      }).finally(() => {
        this.loading = false
      })
    },
    persistOverview() {
      try {
        localStorage.setItem(CACHE_KEY, JSON.stringify(this.overview || {}))
      } catch (e) {}
    },
    initCharts() {
      if (this.$refs.stageDistributionChart) {
        this.stageDistributionChart = echarts.init(this.$refs.stageDistributionChart, 'macarons')
      }
      if (this.$refs.stageMetricsChart) {
        this.stageMetricsChart = echarts.init(this.$refs.stageMetricsChart, 'macarons')
      }
      if (this.$refs.avgDurationChart) {
        this.avgDurationChart = echarts.init(this.$refs.avgDurationChart, 'macarons')
      }
      if (this.$refs.funnelChart) {
        this.funnelChart = echarts.init(this.$refs.funnelChart, 'macarons')
      }
    },
    renderCharts() {
      this.renderStageDistribution()
      this.renderStageMetrics()
      this.renderAvgDuration()
      this.renderFunnel()
    },
    renderStageDistribution() {
      const data = (this.overview && this.overview.stageDistribution) || []
      if (!this.stageDistributionChart) return
      this.stageDistributionChart.setOption({
        tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
        legend: { orient: 'vertical', left: 'left' },
        series: [{
          name: '阶段分布',
          type: 'pie',
          radius: ['40%', '70%'],
          data,
          label: { formatter: '{b}: {c}\n({d}%)' },
          itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 }
        }]
      })
    },
    renderStageMetrics() {
      const data = (this.overview && this.overview.stageMetrics) || {}
      const labels = data.labels || []
      if (!this.stageMetricsChart) return
      this.stageMetricsChart.setOption({
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        legend: { data: ['销售额(总计)', '销量(总计)'] },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: { type: 'category', data: labels },
        yAxis: [
          { type: 'value', name: '销售额' },
          { type: 'value', name: '销量' }
        ],
        series: [
          { name: '销售额(总计)', type: 'bar', data: data.revenue || [], itemStyle: { color: 'rgba(59,130,246,0.7)' } },
          { name: '销量(总计)', type: 'bar', yAxisIndex: 1, data: data.quantity || [], itemStyle: { color: 'rgba(100,116,139,0.7)' } }
        ]
      })
    },
    renderAvgDuration() {
      const data = (this.overview && this.overview.avgDuration) || {}
      if (!this.avgDurationChart) return
      this.avgDurationChart.setOption({
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: { type: 'category', data: data.labels || [] },
        yAxis: { type: 'value', name: '天数' },
        series: [{
          name: '平均持续天数',
          type: 'bar',
          data: data.values || [],
          label: { show: true, position: 'top' },
          itemStyle: { color: 'rgba(245,158,11,0.7)' }
        }]
      })
    },
    renderFunnel() {
      const data = (this.overview && this.overview.funnel) || {}
      if (!this.funnelChart) return
      this.funnelChart.setOption({
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: { type: 'value', name: '转化率(%)' },
        yAxis: { type: 'category', data: data.labels || [] },
        series: [{
          name: '转化率',
          type: 'bar',
          data: data.values || [],
          label: { show: true, position: 'right', formatter: '{c}%' },
          itemStyle: { color: 'rgba(59,130,246,0.7)' }
        }]
      })
    },
    handleResize() {
      ;[this.stageDistributionChart, this.stageMetricsChart, this.avgDurationChart, this.funnelChart].forEach(chart => {
        if (chart) chart.resize()
      })
    },
    destroyCharts() {
      ;[this.stageDistributionChart, this.stageMetricsChart, this.avgDurationChart, this.funnelChart].forEach(chart => {
        if (chart) chart.dispose()
      })
      this.stageDistributionChart = null
      this.stageMetricsChart = null
      this.avgDurationChart = null
      this.funnelChart = null
    },
    stageTagType(stage) {
      const map = {
        引入期: 'info',
        成长期: 'success',
        成熟期: 'warning',
        衰退期: 'danger',
        数据不足: ''
      }
      return map[stage] || ''
    },
    formatCurrency(value) {
      const numberValue = Number(value)
      if (Number.isNaN(numberValue)) return '-'
      return `￥${numberValue.toFixed(2)}`
    },
    formatUploadDate(date) {
      const d = date instanceof Date ? date : new Date(date)
      if (Number.isNaN(d.getTime())) return ''
      const y = d.getFullYear()
      const m = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${y}-${m}-${day}`
    },
    exportResults() {
      if (!this.hasData) {
        this.$modal.msgError('暂无可导出的分析结果')
        return
      }
      const blob = new Blob([JSON.stringify(this.overview || {}, null, 2)], { type: 'application/json;charset=utf-8' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `sku_lifecycle_database_overview_${this.formatUploadDate(new Date())}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 20px;

  h2 {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 8px;

    i {
      margin-right: 8px;
      color: #409EFF;
    }
  }

  .page-desc {
    color: #909399;
    font-size: 14px;
    margin: 0;
  }
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
  justify-content: flex-end;
}

.mb-20 {
  margin-bottom: 20px;
}

.chart {
  height: 400px;
}

::v-deep .el-card {
  border-radius: 8px;
  border: 1px solid #e6eaf2;
  box-shadow: 0 1px 3px rgba(15, 23, 42, 0.06);
}

::v-deep .el-card__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eef2f7;

  .header-desc {
    font-size: 12px;
    color: #909399;
    font-weight: normal;
  }
}

.stat-card {
  .stat-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
  }

  .stat-info {
    flex: 1;
  }

  .stat-label {
    font-size: 12px;
    color: #909399;
    margin: 0 0 8px 0;
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }

  .stat-value {
    font-size: 28px;
    font-weight: bold;
    color: #303133;
    margin: 0 0 8px 0;
  }

  .stat-desc {
    font-size: 12px;
    color: #909399;
    margin: 0;

    &.stat-desc-success {
      color: #67C23A;
    }
  }

  .stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;

    &.stat-icon-purple {
      background: linear-gradient(135deg, #e0e7ff 0%, #c7d2fe 100%);
      color: #6366f1;
    }

    &.stat-icon-blue {
      background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
      color: #3b82f6;
    }

    &.stat-icon-teal {
      background: linear-gradient(135deg, #ccfbf1 0%, #99f6e4 100%);
      color: #14b8a6;
    }

    &.stat-icon-green {
      background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
      color: #10b981;
    }

    &.stat-icon-yellow {
      background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
      color: #f59e0b;
    }

    &.stat-icon-red {
      background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
      color: #ef4444;
    }
  }
}

@media (max-width: 767px) {
  .page-header {
    flex-direction: column;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }
}
</style>
