<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2><i class="el-icon-s-data"></i> 销售整体看板</h2>
      <p class="page-desc">全局销售数据概览，包含关键指标和趋势分析</p>
    </div>

    <!-- 文件上传区域 -->
    <el-card class="mb-20">
      <div slot="header">
        <span><i class="el-icon-upload"></i> 数据文件上传</span>
      </div>
      <el-upload
        ref="upload"
        class="toolbar-upload"
        :limit="1"
        accept=".xlsx,.xls,.csv"
        :http-request="customUpload"
        :disabled="upload.isUploading"
        :on-change="handleFileChange"
        :before-upload="beforeUpload"
        :auto-upload="false"
        :show-file-list="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" /> 是否覆盖已上传的文件
          <div>只能上传xlsx/xls/csv文件，且不超过500MB</div>
        </div>
      </el-upload>
      <div style="margin-top: 15px">
        <el-button :loading="upload.isUploading" type="primary" @click="submitUpload">立即上传并分析</el-button>
        <el-button type="success" :disabled="!hasResults" @click="exportResults">导出分析</el-button>
        <el-button @click="resetUpload">重置</el-button>
      </div>
    </el-card>

    <!-- 视图选择区域 -->
    <el-card v-if="results.summary" class="mb-20">
      <div slot="header">
        <span><i class="el-icon-s-operation"></i> 数据视图选择</span>
      </div>
      <div class="view-selector">
        <el-radio-group v-model="selectedView" @change="handleViewChange">
          <el-radio-button label="overall">总体概览</el-radio-button>
          <el-radio-button label="category">按品类查看</el-radio-button>
          <el-radio-button label="sku">按SKU查看</el-radio-button>
        </el-radio-group>
        
        <!-- 品类选择 -->
        <el-select v-if="selectedView === 'category' && results.category_list && results.category_list.length > 0" 
                   v-model="selectedCategory" 
                   placeholder="选择品类" 
                   @change="handleCategoryChange"
                   style="margin-left: 10px; width: 200px;">
          <el-option v-for="category in results.category_list" 
                     :key="category" 
                     :label="category" 
                     :value="category" />
        </el-select>
        
        <!-- SKU选择 -->
        <el-select v-if="(selectedView === 'sku' || selectedView === 'category') && getAvailableSkus().length > 0" 
                   v-model="selectedSku" 
                   placeholder="选择SKU" 
                   @change="handleSkuChange"
                   style="margin-left: 10px; width: 200px;">
          <el-option v-for="sku in getAvailableSkus()" 
                     :key="sku" 
                     :label="sku" 
                     :value="sku" />
        </el-select>
      </div>
    </el-card>

    <!-- 关键指标卡片 -->
    <el-row :gutter="20" class="mb-20">
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-info">
              <p class="stat-label">当前总销量</p>
              <p class="stat-value">{{ totalSales }}</p>
              <p class="stat-desc" :class="salesGrowthRate >= 0 ? 'stat-desc-success' : 'stat-desc-error'">
                增长率 {{ salesGrowthRate >= 0 ? '+' : '' }}{{ salesGrowthRate }}%
              </p>
            </div>
            <div class="stat-icon stat-icon-blue">
              <i class="el-icon-s-order"></i>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-info">
              <p class="stat-label">平均价格</p>
              <p class="stat-value">¥{{ avgPrice.toFixed(2) }}</p>
              <p class="stat-desc" :class="priceChange >= 0 ? 'stat-desc-success' : 'stat-desc-error'">
                变化 {{ priceChange >= 0 ? '+' : '' }}{{ priceChange.toFixed(2) }}%
              </p>
            </div>
            <div class="stat-icon stat-icon-green">
              <i class="el-icon-s-finance"></i>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-info">
              <p class="stat-label">平均促销力度</p>
              <p class="stat-value">{{ avgPromotion.toFixed(2) }}%</p>
              <p class="stat-desc" :class="promotionChange >= 0 ? 'stat-desc-success' : 'stat-desc-error'">
                变化 {{ promotionChange >= 0 ? '+' : '' }}{{ promotionChange.toFixed(2) }}%
              </p>
            </div>
            <div class="stat-icon stat-icon-yellow">
              <i class="el-icon-s-marketing"></i>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-info">
              <p class="stat-label">异常数据检测率</p>
              <p class="stat-value">{{ anomalyDetectionRate.toFixed(2) }}%</p>
              <p class="stat-desc">基于销售数据异常模式分析</p>
            </div>
            <div class="stat-icon stat-icon-red">
              <i class="el-icon-warning-outline"></i>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 趋势图表 -->
    <el-row :gutter="20" class="mb-20">
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card>
          <div slot="header">
            <span><i class="el-icon-data-line"></i> 平均价格变化趋势</span>
            <span class="header-desc">按时间段统计</span>
          </div>
          <div ref="priceTrendChart" style="height: 400px"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card>
          <div slot="header">
            <span><i class="el-icon-data-line"></i> 平均促销力度变化趋势</span>
            <span class="header-desc">按时间段统计</span>
          </div>
          <div ref="promotionTrendChart" style="height: 400px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 销量与异常检测图表 -->
    <el-row :gutter="20" class="mb-20">
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card>
          <div slot="header">
            <span><i class="el-icon-s-order"></i> 销量趋势</span>
            <span class="header-desc">按时间段统计</span>
          </div>
          <div ref="salesTrendChart" style="height: 400px"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card>
          <div slot="header">
            <span><i class="el-icon-warning"></i> 异常数据检测</span>
            <span class="header-desc">异常数据分布</span>
          </div>
          <div ref="anomalyDetectionChart" style="height: 400px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 异常数据详情 -->
    <el-card v-if="results.anomalies && results.anomalies.anomaly_count > 0" class="mb-20">
      <div slot="header">
        <span><i class="el-icon-warning-outline"></i> 异常数据详情</span>
        <span class="header-desc">共检测到 {{ results.anomalies.anomaly_count }} 个异常，异常率 {{ results.anomalies.anomaly_rate.toFixed(2) }}%</span>
      </div>
      <el-table :data="anomalyData" style="width: 100%">
        <el-table-column prop="date" label="日期" width="120">
          <template slot-scope="scope">
            {{ scope.row.date || 'N/A' }}
          </template>
        </el-table-column>
        <el-table-column prop="sku" label="SKU" width="180">
          <template slot-scope="scope">
            {{ scope.row.sku || 'N/A' }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="异常类型" width="120">
          <template slot-scope="scope">
            <el-tag :type="getAnomalyTypeTag(scope.row.type)">
              {{ getAnomalyTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="异常原因" min-width="300">
          <template slot-scope="scope">
            <span class="anomaly-reason">{{ scope.row.reason }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="value" label="实际值" width="100">
          <template slot-scope="scope">
            {{ scope.row.value.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="expected" label="预期值" width="100">
          <template slot-scope="scope">
            {{ scope.row.expected.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="deviation" label="偏差程度" width="100">
          <template slot-scope="scope">
            <el-progress 
              :percentage="Math.min(scope.row.deviation * 20, 100)" 
              :color="getDeviationColor(scope.row.deviation)"
              :stroke-width="10"
            />
            <span class="deviation-value">{{ scope.row.deviation.toFixed(2) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { analyzeSaleOverviewWithFile, getSaleOverviewResults } from '@/api/client'
import { getToken } from '@/utils/auth'
import * as echarts from 'echarts'
require('echarts/theme/macarons')

export default {
  name: 'SalesOverview',
  data() {
    return {
      // 图表实例
      priceTrendChart: null,
      promotionTrendChart: null,
      salesTrendChart: null,
      anomalyDetectionChart: null,
      // 数据
      results: {},
      // 计算属性数据
      totalSales: 0,
      salesGrowthRate: 0,
      avgPrice: 0,
      priceChange: 0,
      avgPromotion: 0,
      promotionChange: 0,
      anomalyDetectionRate: 0,
      // 趋势数据
      timeSeries: [],
      priceSeries: [],
      promotionSeries: [],
      salesSeries: [],
      anomalySeries: [],
      // 视图选择相关
      selectedView: 'overall',
      selectedCategory: '',
      selectedSku: '',
      // 文件上传相关
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的文件
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_PYTHON_API + '/api/sale-overview/upload',
        // 文件名称
        fileName: '',
        // 已选择文件名称
        pendingFileName: '',
        // 是否忽略文件选择改变
        ignoreFileChange: false,
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
    })
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.priceTrendChart) {
      this.priceTrendChart.dispose()
    }
    if (this.promotionTrendChart) {
      this.promotionTrendChart.dispose()
    }
    if (this.salesTrendChart) {
      this.salesTrendChart.dispose()
    }
    if (this.anomalyDetectionChart) {
      this.anomalyDetectionChart.dispose()
    }
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    /** 文件上传前的校验 */
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                      file.type === 'application/vnd.ms-excel' ||
                      file.type === 'text/csv' ||
                      file.name.endsWith('.xlsx') ||
                      file.name.endsWith('.xls') ||
                      file.name.endsWith('.csv')
      const isLt500M = file.size / 1024 / 1024 < 500

      if (!isExcel) {
        this.$modal.msgError('上传文件只能是 xlsx/xls/csv 格式!')
        return false
      }
      if (!isLt500M) {
        this.$modal.msgError('上传文件大小不能超过 500MB!')
        return false
      }
      return true
    },
    /** 文件选择改变处理 */
    handleFileChange(file, fileList) {
      if (this.upload.ignoreChange) return
      if (!fileList || fileList.length === 0) return
      if (!file || !file.raw) return

      this.upload.pendingFileName = file.name
      this.upload.fileName = ''
    },
    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    /** 自定义上传方法 */
    customUpload(options) {
      const file = options.file
      this.upload.isUploading = true
      analyzeSaleOverviewWithFile(file).then(response => {
        this.upload.isUploading = false
        if (response && response.success) {
          this.$modal.msgSuccess('文件上传并分析成功')
          this.results = response.data || {}
          this.calculateMetrics()
          this.$nextTick(() => {
            this.renderCharts()
          })
          options.onSuccess(response)
        } else {
          const message = (response && response.message) || '分析失败'
          this.$modal.msgError(message)
          options.onError(new Error(message))
        }
        if (this.$refs.upload) {
          this.upload.ignoreFileChange = true
          this.$refs.upload.clearFiles()
          this.$nextTick(() => {
            this.upload.ignoreFileChange = false
          })
        }
      }).catch(error => {
        this.upload.isUploading = false
        const errorMsg = (error && error.response && error.response.data && error.response.data.message) || error.message || '文件上传失败，请重试'
        this.$modal.msgError(errorMsg)
        options.onError(error)
      })
    },
    /** 提交上传文件 */
    submitUpload() {
      const fileList = this.$refs.upload.uploadFiles
      if (!fileList || fileList.length === 0) {
        this.$modal.msgError('请选择要上传的文件')
        return
      }
      this.$refs.upload.submit()
    },
    /** 重置上传 */
    resetUpload() {
      this.$refs.upload.clearFiles()
    },
    /** 获取销售分析结果 */
    getList() {
      getSaleOverviewResults().then(response => {
        if (response && response.success && response.data) {
          this.results = response.data || {}
          this.calculateMetrics()
          this.$nextTick(() => {
            this.renderCharts()
          })
        }
      }).catch(() => {
        this.results = {}
      })
    },
    /** 计算关键指标 */
    calculateMetrics() {
      if (!this.results.summary) {
        return
      }
      
      // 根据选择的视图计算指标
      switch (this.selectedView) {
        case 'overall':
          this.calculateOverallMetrics()
          break
        case 'category':
          this.calculateCategoryMetrics()
          break
        case 'sku':
          this.calculateSkuMetrics()
          break
        default:
          this.calculateOverallMetrics()
      }
    },
    
    /** 计算总体指标 */
    calculateOverallMetrics() {
      if (this.results.summary) {
        this.totalSales = this.results.summary.total_quantity || 0
        this.avgPrice = this.results.summary.total_revenue / this.results.summary.total_quantity || 0
        
        // 模拟增长率和变化率数据
        this.salesGrowthRate = 12.5
        this.priceChange = -2.3
        this.avgPromotion = 15.8
        this.promotionChange = 3.2
        this.anomalyDetectionRate = 5.7
        
        // 模拟趋势数据
        this.timeSeries = ['1月', '2月', '3月', '4月', '5月', '6月']
        this.priceSeries = [95.2, 92.8, 90.5, 88.9, 90.2, 89.6]
        this.promotionSeries = [12.5, 13.2, 14.8, 15.5, 16.2, 15.8]
        this.salesSeries = [8500, 9200, 10500, 11200, 11800, 12580]
        this.anomalySeries = [4.2, 3.8, 5.1, 6.5, 7.2, 5.7]
      }
    },
    
    /** 计算品类指标 */
    calculateCategoryMetrics() {
      if (this.selectedCategory && this.results.categories && this.results.categories[this.selectedCategory]) {
        const categoryData = this.results.categories[this.selectedCategory]
        this.totalSales = categoryData.total_quantity || 0
        this.avgPrice = categoryData.avg_price || 0
        
        // 模拟增长率和变化率数据
        this.salesGrowthRate = 15.2
        this.priceChange = 1.8
        this.avgPromotion = 18.5
        this.promotionChange = 2.5
        this.anomalyDetectionRate = 4.8
        
        // 使用品类的趋势数据
        this.timeSeries = categoryData.date_series || ['1月', '2月', '3月', '4月', '5月', '6月']
        this.priceSeries = categoryData.price_series || [90.2, 91.5, 92.8, 93.1, 92.5, 91.8]
        this.salesSeries = categoryData.quantity_series || [7500, 8200, 9100, 9800, 10500, 11200]
        this.promotionSeries = [16.5, 17.2, 18.1, 19.0, 18.8, 18.5]
        this.anomalySeries = [3.8, 4.2, 4.5, 5.1, 4.9, 4.8]
      } else {
        // 默认选择第一个品类
        if (this.results.category_list && this.results.category_list.length > 0) {
          this.selectedCategory = this.results.category_list[0]
          this.calculateCategoryMetrics()
        } else {
          this.calculateOverallMetrics()
        }
      }
    },
    
    /** 计算SKU指标 */
    calculateSkuMetrics() {
      if (this.selectedSku && this.results.data && this.results.data[this.selectedSku]) {
        const skuData = this.results.data[this.selectedSku]
        this.totalSales = skuData.total_quantity || 0
        this.avgPrice = skuData.avg_price || 0
        
        // 模拟增长率和变化率数据
        this.salesGrowthRate = 22.8
        this.priceChange = -0.5
        this.avgPromotion = 22.5
        this.promotionChange = 3.8
        this.anomalyDetectionRate = 3.2
        
        // 使用SKU的趋势数据
        this.timeSeries = skuData.date_series || ['1月', '2月', '3月', '4月', '5月', '6月']
        this.priceSeries = skuData.price_series || [85.2, 84.8, 85.1, 84.9, 84.7, 84.5]
        this.salesSeries = skuData.quantity_series || [1200, 1350, 1500, 1650, 1800, 1950]
        this.promotionSeries = [20.5, 21.2, 21.8, 22.5, 23.0, 22.5]
        this.anomalySeries = [2.8, 3.1, 3.3, 3.5, 3.2, 3.0]
      } else {
        // 默认选择第一个SKU
        if (this.results.sku_list && this.results.sku_list.length > 0) {
          this.selectedSku = this.results.sku_list[0]
          this.calculateSkuMetrics()
        } else {
          this.calculateOverallMetrics()
        }
      }
    },
    
    /** 处理视图变化 */
    handleViewChange() {
      this.calculateMetrics()
      this.renderCharts()
    },
    
    /** 处理品类变化 */
    handleCategoryChange() {
      // Reset selected SKU and select first available in new category
      const availableSkus = this.getAvailableSkus()
      if (availableSkus.length > 0) {
        this.selectedSku = availableSkus[0]
      } else {
        this.selectedSku = ''
      }
      this.calculateMetrics()
      this.renderCharts()
    },
    
    /** 处理SKU变化 */
    handleSkuChange() {
      this.calculateMetrics()
      this.renderCharts()
    },
    
    /** 获取可用的SKU列表 */
    getAvailableSkus() {
      if (this.selectedView === 'category' && this.selectedCategory && this.results.category_skus) {
        return this.results.category_skus[this.selectedCategory] || []
      } else {
        return this.results.sku_list || []
      }
    },
    
    /** 获取异常类型标签 */
    getAnomalyTypeTag(type) {
      switch (type) {
        case 'quantity_spike':
        case 'sku_price_spike':
          return 'warning'
        case 'quantity_drop':
        case 'sku_price_drop':
          return 'danger'
        case 'price_spike':
          return 'info'
        case 'price_drop':
          return 'success'
        default:
          return 'primary'
      }
    },
    
    /** 获取异常类型名称 */
    getAnomalyTypeName(type) {
      switch (type) {
        case 'quantity_spike':
          return '销量激增'
        case 'quantity_drop':
          return '销量骤降'
        case 'price_spike':
          return '价格上涨'
        case 'price_drop':
          return '价格下降'
        case 'sku_price_spike':
          return 'SKU涨价'
        case 'sku_price_drop':
          return 'SKU降价'
        default:
          return '异常'
      }
    },
    
    /** 获取偏差程度颜色 */
    getDeviationColor(deviation) {
      if (deviation > 3) {
        return '#ff4d4f'
      } else if (deviation > 2.5) {
        return '#fa8c16'
      } else if (deviation > 2) {
        return '#faad14'
      } else {
        return '#52c41a'
      }
    },
    /** 初始化图表 */
    initCharts() {
      if (this.$refs.priceTrendChart) {
        this.priceTrendChart = echarts.init(this.$refs.priceTrendChart, 'macarons')
        }
      if (this.$refs.promotionTrendChart) {
        this.promotionTrendChart = echarts.init(this.$refs.promotionTrendChart, 'macarons')
      }
      if (this.$refs.salesTrendChart) {
        this.salesTrendChart = echarts.init(this.$refs.salesTrendChart, 'macarons')
      }
      if (this.$refs.anomalyDetectionChart) {
        this.anomalyDetectionChart = echarts.init(this.$refs.anomalyDetectionChart, 'macarons')
      }
    },
    /** 渲染所有图表 */
    renderCharts() {
      // 1. 平均价格变化趋势
      this.renderPriceTrend()
      
      // 2. 平均促销力度变化趋势
      this.renderPromotionTrend()
      
      // 3. 销量趋势
      this.renderSalesTrend()
      
      // 4. 异常数据检测
      this.renderAnomalyDetection()
    },
    /** 渲染平均价格变化趋势图表 */
    renderPriceTrend() {
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['平均价格']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.timeSeries
        },
        yAxis: {
          type: 'value',
          name: '价格 (¥)'
        },
        series: [
          {
            name: '平均价格',
            type: 'line',
            stack: 'Total',
            smooth: true,
            lineStyle: {
              width: 3
            },
            areaStyle: {
              opacity: 0.3
            },
            data: this.priceSeries,
            itemStyle: {
              color: '#10b981'
            }
          }
        ]
      }

      if (this.priceTrendChart) {
        this.priceTrendChart.setOption(option)
      }
    },
    /** 渲染平均促销力度变化趋势图表 */
    renderPromotionTrend() {
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['平均促销力度']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.timeSeries
        },
        yAxis: {
          type: 'value',
          name: '促销力度 (%)'
        },
        series: [
          {
            name: '平均促销力度',
            type: 'line',
            stack: 'Total',
            smooth: true,
            lineStyle: {
              width: 3
            },
            areaStyle: {
              opacity: 0.3
            },
            data: this.promotionSeries,
            itemStyle: {
              color: '#f59e0b'
            }
          }
        ]
      }

      if (this.promotionTrendChart) {
        this.promotionTrendChart.setOption(option)
      }
    },
    /** 渲染销量趋势图表 */
    renderSalesTrend() {
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['销量']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.timeSeries
        },
        yAxis: {
          type: 'value',
          name: '销量'
        },
        series: [
          {
            name: '销量',
            type: 'line',
            stack: 'Total',
            smooth: true,
            lineStyle: {
              width: 3
            },
            areaStyle: {
              opacity: 0.3
            },
            data: this.salesSeries,
            itemStyle: {
              color: '#3b82f6'
            }
          }
        ]
      }

      if (this.salesTrendChart) {
        this.salesTrendChart.setOption(option)
      }
    },
    /** 渲染异常数据检测图表 */
    renderAnomalyDetection() {
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.timeSeries
        },
        yAxis: {
          type: 'value',
          name: '异常检测率 (%)'
        },
        series: [
          {
            name: '异常检测率',
            type: 'bar',
            data: this.anomalySeries,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: '#ef4444'
                },
                {
                  offset: 1,
                  color: '#fca5a5'
                }
              ])
            },
            label: {
              show: true,
              position: 'top',
              formatter: '{c}%'
            }
          }
        ]
      }

      if (this.anomalyDetectionChart) {
        this.anomalyDetectionChart.setOption(option)
      }
    },
    /** 窗口大小变化处理 */
    handleResize() {
      if (this.priceTrendChart) {
        this.priceTrendChart.resize()
      }
      if (this.promotionTrendChart) {
        this.promotionTrendChart.resize()
      }
      if (this.salesTrendChart) {
        this.salesTrendChart.resize()
      }
      if (this.anomalyDetectionChart) {
        this.anomalyDetectionChart.resize()
      }
    },
    /** 工具函数 */
    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.hasResults) {
        this.$modal.msgError('暂无可导出的分析结果')
        return
      }
      const payload = JSON.stringify(this.results || {}, null, 2)
      const blob = new Blob([payload], { type: 'application/json;charset=utf-8' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `sale_overview_results_${this.formatUploadDate(new Date())}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    }
  },
  computed: {
    hasResults() {
      return Object.keys(this.results || {}).length > 0
    },
    /** 异常数据列表 */
    anomalyData() {
      if (this.results.anomalies && this.results.anomalies.anomalies) {
        return this.results.anomalies.anomalies.sort((a, b) => b.deviation - a.deviation)
      }
      return []
    }
  }
}
</script>

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

.page-header {
  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;
  }
}

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

.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-desc-error {
          color: #F56C6C;
        }
      }
    }
    
    .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;
      }
    }
  }
}

::v-deep .el-card__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .header-desc {
    font-size: 12px;
    color: #909399;
    font-weight: normal;
  }
}

.view-selector {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  
  .el-radio-group {
    display: flex;
    align-items: center;
  }
  
  .el-select {
    margin-top: 5px;
  }
}

@media screen and (max-width: 768px) {
  .view-selector {
    flex-direction: column;
    align-items: flex-start;
    
    .el-select {
      width: 100% !important;
      margin-left: 0 !important;
    }
  }
}

/* Anomaly styles */
.anomaly-reason {
  line-height: 1.4;
  color: #303133;
}

.deviation-value {
  display: block;
  text-align: center;
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

::v-deep .el-table .cell {
  padding: 12px 10px;
}

::v-deep .el-table__row:hover {
  background-color: #f5f7fa !important;
}

::v-deep .el-tag {
  margin-right: 0;
}

/* Anomaly type tag styles */
::v-deep .el-tag--warning {
  background-color: #fff7e6;
  border-color: #ffd591;
  color: #fa8c16;
}

::v-deep .el-tag--danger {
  background-color: #fff1f0;
  border-color: #ffccc7;
  color: #f5222d;
}

::v-deep .el-tag--info {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

::v-deep .el-tag--success {
  background-color: #f6ffed;
  border-color: #b7eb8f;
  color: #52c41a;
}

/* Progress bar styles */
::v-deep .el-progress {
  margin-bottom: 4px;
}

::v-deep .el-progress-bar__outer {
  background-color: #f0f0f0;
}

::v-deep .el-progress-bar__inner {
  border-radius: 5px;
}
</style>