<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2><i class="el-icon-s-operation"></i> 销售控制中心</h2>
      <p class="page-desc">销售数据实时监控与分析，包含关键指标和趋势分析</p>
    </div>

    <div class="upload-toolbar">
      <div class="toolbar-left">
        <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"
        >
          <el-button plain>上传文件</el-button>
        </el-upload>
        <el-button :loading="upload.isUploading" type="primary" @click="submitUpload">开始分析</el-button>
        <el-button type="success" :disabled="!hasResults" @click="exportResults">导出分析</el-button>
      </div>
      <div class="toolbar-status" v-if="upload.fileName">已上传：{{ upload.fileName }}</div>
      <div class="toolbar-status" v-else-if="upload.pendingFileName">已选择：{{ upload.pendingFileName }}</div>
      <div class="toolbar-status muted" v-else>未上传</div>
    </div>

    <!-- 关键指标卡片 -->
    <el-row :gutter="20" class="mb-20">
      <el-col :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">订单总数</p>
              <p class="stat-value">{{ orderCount }}</p>
              <p class="stat-desc">所有订单</p>
            </div>
            <div class="stat-icon stat-icon-purple">
              <i class="el-icon-s-order"></i>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :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">商品总数</p>
              <p class="stat-value">{{ productCount }}</p>
              <p class="stat-desc">按商品名称</p>
            </div>
            <div class="stat-icon stat-icon-blue">
              <i class="el-icon-s-goods"></i>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :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">总销售额</p>
              <p class="stat-value">{{ totalRevenue }}</p>
              <p class="stat-desc">实际支付金额</p>
            </div>
            <div class="stat-icon stat-icon-teal">
              <i class="el-icon-s-finance"></i>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :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">总销量</p>
              <p class="stat-value">{{ totalQuantity }}</p>
              <p class="stat-desc">购买数量</p>
            </div>
            <div class="stat-icon stat-icon-green">
              <i class="el-icon-s-marketing"></i>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :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">退款金额</p>
              <p class="stat-value">{{ totalRefund }}</p>
              <p class="stat-desc">已退款金额</p>
            </div>
            <div class="stat-icon stat-icon-yellow">
              <i class="el-icon-warning"></i>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :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">退款率</p>
              <p class="stat-value">{{ refundRate }}%</p>
              <p class="stat-desc">退款订单占比</p>
            </div>
            <div class="stat-icon stat-icon-red">
              <i class="el-icon-s-flag"></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="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-pie-chart"></i> 商品销售占比</span>
            <span class="header-desc">按销售额</span>
          </div>
          <div ref="productDistributionChart" 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-grid"></i> 订单状态分布</span>
            <span class="header-desc">按订单数量</span>
          </div>
          <div ref="orderStatusChart" 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-s-finance"></i> 退款分析</span>
            <span class="header-desc">按商品</span>
          </div>
          <div ref="refundAnalysisChart" style="height: 400px"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

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

export default {
  name: 'SaleControl',
  data() {
    return {
      // 图表实例
      salesTrendChart: null,
      productDistributionChart: null,
      orderStatusChart: null,
      refundAnalysisChart: null,
      // 数据
      results: {},
      // 计算属性数据
      orderCount: 0,
      productCount: 0,
      totalRevenue: 0,
      totalQuantity: 0,
      totalRefund: 0,
      refundRate: 0,
      // 文件上传相关
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的文件
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_PYTHON_API + '/api/sale-control/upload',
        // 文件名称
        fileName: '',
        // 已选择文件名称
        pendingFileName: '',
        // 是否忽略文件选择改变
        ignoreFileChange: false,
      }
    }
  },
  computed: {
    hasResults() {
      return Object.keys(this.results || {}).length > 0
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
    })
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.salesTrendChart) {
      this.salesTrendChart.dispose()
    }
    if (this.productDistributionChart) {
      this.productDistributionChart.dispose()
    }
    if (this.orderStatusChart) {
      this.orderStatusChart.dispose()
    }
    if (this.refundAnalysisChart) {
      this.refundAnalysisChart.dispose()
    }
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    /** 文件选择改变处理 */
    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 = ''
    },
    /** 文件上传前的校验 */
    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
    },
    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    /** 自定义上传方法 */
    customUpload(options) {
      const file = options.file
      this.upload.isUploading = true
      analyzeFile(file).then(response => {
        this.upload.isUploading = false
        if (response && response.success) {
          this.$modal.msgSuccess('文件上传并分析成功')
          this.upload.fileName = this.upload.pendingFileName || file.name
          this.upload.pendingFileName = ''
          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() {
      if (this.$refs.upload) this.$refs.upload.clearFiles()
      if (this.$refs.toolbarUpload) this.$refs.toolbarUpload.clearFiles()
    },
    /** 获取销售分析结果 */
    getList() {
      getResults().then(response => {
        if (response && response.success && response.data) {
          this.results = response.data || {}
          this.calculateMetrics()
          this.$nextTick(() => {
            this.renderCharts()
          })
        }
      }).catch(() => {
        this.results = {}
      })
    },
    /** 计算关键指标 */
    calculateMetrics() {
      // 仅取真实销售数据，排除聚合概要
      const entries = Object.entries(this.results || {})
      const resultsArr = entries.filter(([k]) => k !== '_analysis_summary_').map(([, v]) => v)

      this.orderCount = resultsArr.length

      // 商品总数（按商品名称去重）
      const products = new Set()
      resultsArr.forEach(r => {
        if (r?.商品名称) products.add(r.商品名称)
      })
      this.productCount = products.size

      // 总销售额
      this.totalRevenue = resultsArr.reduce((s, r) => s + Number(r?.买家实际支付金额 || 0), 0)

      // 总销量
      this.totalQuantity = resultsArr.reduce((s, r) => s + Number(r?.购买数量 || 0), 0)

      // 总退款金额
      this.totalRefund = resultsArr.reduce((s, r) => {
        if (r?.退款状态 && r?.退款状态 !== '没有申请退款' && r?.退款金额) {
          return s + Number(r.退款金额)
        }
        return s
      }, 0)

      // 退款率
      const refundCount = resultsArr.filter(r => r?.退款状态 && r?.退款状态 !== '没有申请退款').length
      this.refundRate = this.orderCount ? ((refundCount / this.orderCount) * 100).toFixed(1) : 0
    },
    /** 初始化图表 */
    initCharts() {
      if (this.$refs.salesTrendChart) {
        this.salesTrendChart = echarts.init(this.$refs.salesTrendChart, 'macarons')
      }
      if (this.$refs.productDistributionChart) {
        this.productDistributionChart = echarts.init(this.$refs.productDistributionChart, 'macarons')
      }
      if (this.$refs.orderStatusChart) {
        this.orderStatusChart = echarts.init(this.$refs.orderStatusChart, 'macarons')
      }
      if (this.$refs.refundAnalysisChart) {
        this.refundAnalysisChart = echarts.init(this.$refs.refundAnalysisChart, 'macarons')
      }
    },
    /** 渲染所有图表 */
    renderCharts() {
      const entries = Object.entries(this.results || {})
      const resultsArr = entries.filter(([k]) => k !== '_analysis_summary_').map(([, v]) => v)

      // 1. 销售趋势（折线图）
      this.renderSalesTrend(resultsArr)

      // 2. 商品销售占比（饼图）
      this.renderProductDistribution(resultsArr)

      // 3. 订单状态分布（柱状图）
      this.renderOrderStatus(resultsArr)

      // 4. 退款分析（柱状图）
      this.renderRefundAnalysis(resultsArr)
    },
    /** 渲染销售趋势图 */
    renderSalesTrend(list) {
      // 按日期分组
      const dateMap = {}
      list.forEach(item => {
        const date = item?.订单创建时间 ? item.订单创建时间.split(' ')[0] : '未知'
        if (!dateMap[date]) {
          dateMap[date] = {
            revenue: 0,
            quantity: 0
          }
        }
        dateMap[date].revenue += Number(item?.买家实际支付金额 || 0)
        dateMap[date].quantity += Number(item?.购买数量 || 0)
      })

      // 按日期排序
      const sortedDates = Object.keys(dateMap).sort()
      const dates = sortedDates
      const revenues = sortedDates.map(date => dateMap[date].revenue)
      const quantities = sortedDates.map(date => dateMap[date].quantity)

      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: dates
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '销售额',
            position: 'left'
          },
          {
            type: 'value',
            name: '销量',
            position: 'right'
          }
        ],
        series: [
          {
            name: '销售额',
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: {
              focus: 'series'
            },
            data: revenues,
            itemStyle: {
              color: '#3b82f6'
            }
          },
          {
            name: '销量',
            type: 'line',
            stack: 'Total',
            emphasis: {
              focus: 'series'
            },
            data: quantities,
            yAxisIndex: 1,
            itemStyle: {
              color: '#10b981'
            }
          }
        ]
      }

      if (this.salesTrendChart) {
        this.salesTrendChart.setOption(option)
      }
    },
    /** 渲染商品销售占比饼图 */
    renderProductDistribution(list) {
      // 按商品名称分组
      const productMap = {}
      list.forEach(item => {
        const product = item?.商品名称 || '未知'
        if (!productMap[product]) {
          productMap[product] = 0
        }
        productMap[product] += Number(item?.买家实际支付金额 || 0)
      })

      // 转换为饼图数据
      const data = Object.entries(productMap).map(([name, value]) => ({
        name,
        value
      }))

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: Object.keys(productMap)
        },
        series: [
          {
            name: '商品销售',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {c}\n({d}%)'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 16,
                fontWeight: 'bold'
              }
            },
            data: data
          }
        ]
      }

      if (this.productDistributionChart) {
        this.productDistributionChart.setOption(option)
      }
    },
    /** 渲染订单状态分布 */
    renderOrderStatus(list) {
      // 按订单状态分组
      const statusMap = {}
      list.forEach(item => {
        const status = item?.订单状态 || '未知'
        if (!statusMap[status]) {
          statusMap[status] = 0
        }
        statusMap[status]++
      })

      const statuses = Object.keys(statusMap)
      const counts = Object.values(statusMap)

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: statuses
        },
        yAxis: {
          type: 'value',
          name: '订单数量'
        },
        series: [
          {
            name: '订单数量',
            type: 'bar',
            data: counts,
            itemStyle: {
              color: 'rgba(59,130,246,0.7)'
            },
            label: {
              show: true,
              position: 'top'
            }
          }
        ]
      }

      if (this.orderStatusChart) {
        this.orderStatusChart.setOption(option)
      }
    },
    /** 渲染退款分析 */
    renderRefundAnalysis(list) {
      // 按商品名称分组，计算退款金额
      const refundMap = {}
      list.forEach(item => {
        if (item?.退款状态 && item?.退款状态 !== '没有申请退款' && item?.退款金额) {
          const product = item?.商品名称 || '未知'
          if (!refundMap[product]) {
            refundMap[product] = 0
          }
          refundMap[product] += Number(item?.退款金额 || 0)
        }
      })

      const products = Object.keys(refundMap)
      const refunds = Object.values(refundMap)

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: products
        },
        yAxis: {
          type: 'value',
          name: '退款金额'
        },
        series: [
          {
            name: '退款金额',
            type: 'bar',
            data: refunds,
            itemStyle: {
              color: 'rgba(239,68,68,0.7)'
            },
            label: {
              show: true,
              position: 'top'
            }
          }
        ]
      }

      if (this.refundAnalysisChart) {
        this.refundAnalysisChart.setOption(option)
      }
    },
    /** 窗口大小变化处理 */
    handleResize() {
      if (this.salesTrendChart) {
        this.salesTrendChart.resize()
      }
      if (this.productDistributionChart) {
        this.productDistributionChart.resize()
      }
      if (this.orderStatusChart) {
        this.orderStatusChart.resize()
      }
      if (this.refundAnalysisChart) {
        this.refundAnalysisChart.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_control_results_${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 {
  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;
}

.upload-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #ffffff;
  border: 1px solid #e6eaf2;
  border-radius: 8px;
  padding: 12px 16px;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgba(15, 23, 42, 0.06);
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.toolbar-upload ::v-deep .el-upload {
  display: inline-flex;
}

.toolbar-status {
  font-size: 13px;
  color: #16a34a;
  background: #f0fdf4;
  border: 1px solid #dcfce7;
  border-radius: 6px;
  padding: 6px 10px;
}

.toolbar-status.muted {
  color: #6b7280;
  background: #f8fafc;
  border-color: #e2e8f0;
}

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

.upload-card .el-card__header {
  padding: 12px 16px;
  border-bottom: 1px solid #eef2f7;
}

.upload-row {
  display: flex;
  align-items: center;
  gap: 16px;
}

.upload-compact {
  flex: 1;
  max-width: 260px;
}

.upload-compact ::v-deep .el-upload-dragger {
  width: 100%;
  height: 140px;
  padding: 10px 12px;
  border-radius: 8px;
}

.upload-compact ::v-deep .el-icon-upload {
  font-size: 26px;
  margin-bottom: 4px;
}

.upload-compact ::v-deep .el-upload__text {
  font-size: 13px;
}

.upload-compact ::v-deep .el-upload__tip {
  margin-top: 6px;
  font-size: 12px;
  color: #909399;
}

.upload-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
  min-width: 120px;
}

::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 {
  border-bottom: 1px solid #eef2f7;
}

.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;
      }
    }
  }
}

::v-deep .el-card__header {
  display: flex;
  justify-content: space-between;
  align-items: center;

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