<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-card style="margin-bottom: 20px;">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="时间范围" prop="dateRange">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="handleDateRangeChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单状态" prop="validCode">
          <el-select v-model="queryParams.validCode" placeholder="请选择订单状态" clearable>
            <el-option
              v-for="dict in validCodeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品ID" prop="skuId">
          <el-input
            v-model="queryParams.skuId"
            placeholder="请输入商品ID"
            clearable
            style="width: 200px">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card>
          <div slot="header">
            <span>总订单数</span>
          </div>
          <div class="card-body">
            <h2>{{ statistics.totalOrders || 0 }}</h2>
            <p>累计订单数量</p>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div slot="header">
            <span>总佣金</span>
          </div>
          <div class="card-body">
            <h2>¥{{ formatMoney(statistics.totalCommission) }}</h2>
            <p>累计佣金收入</p>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div slot="header">
            <span>总商品数</span>
          </div>
          <div class="card-body">
            <h2>{{ statistics.totalSkuNum || 0 }}</h2>
            <p>累计商品数量</p>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div slot="header">
            <span>实际费用</span>
          </div>
          <div class="card-body">
            <h2>¥{{ formatMoney(statistics.totalActualFee) }}</h2>
            <p>累计实际费用</p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>订单状态分布</span>
          </div>
          <div class="chart-container">
            <div ref="statusChart" style="height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>佣金分布</span>
          </div>
          <div class="chart-container">
            <div ref="commissionChart" style="height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 状态详情表格 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <div slot="header">
            <span>订单状态详情</span>
          </div>
          <el-table :data="statusDetails" style="width: 100%">
            <el-table-column prop="label" label="状态" width="120" />
            <el-table-column prop="count" label="订单数量" width="120" align="center" />
            <el-table-column prop="skuNum" label="商品数量" width="120" align="center" />
            <el-table-column prop="commission" label="佣金" width="120" align="center">
              <template slot-scope="scope">
                ¥{{ formatMoney(scope.row.commission) }}
              </template>
            </el-table-column>
            <el-table-column prop="actualFee" label="实际费用" width="120" align="center">
              <template slot-scope="scope">
                ¥{{ formatMoney(scope.row.actualFee) }}
              </template>
            </el-table-column>
            <el-table-column prop="percentage" label="占比" width="100" align="center">
              <template slot-scope="scope">
                {{ scope.row.percentage }}%
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getOrderStatistics, getValidCodeSelectData } from '@/api/system/orderrows'

export default {
  name: "OrderStatistics",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        beginTime: null,
        endTime: null,
        validCode: null,
        skuId: null
      },
      // 日期范围
      dateRange: [],
      // 订单状态选项
      validCodeOptions: [],
      // 统计数据
      statistics: {
        totalOrders: 0,
        totalCommission: 0,
        totalSkuNum: 0,
        totalActualFee: 0,
        groupStats: {}
      },
      // 状态详情数据
      statusDetails: []
    }
  },
  created() {
    this.getValidCodeOptions()
    this.getStatistics()
  },
  mounted() {
    this.initCharts()
  },
  methods: {
    /** 获取订单状态选项 */
    getValidCodeOptions() {
      getValidCodeSelectData().then(response => {
        this.validCodeOptions = response.data
      })
    },
    /** 获取统计数据 */
    getStatistics() {
      this.loading = true
      getOrderStatistics(this.queryParams).then(response => {
        this.statistics = response.data
        this.processStatusDetails()
        this.$nextTick(() => {
          this.initCharts()
        })
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 处理状态详情数据 */
    processStatusDetails() {
      const groupStats = this.statistics.groupStats || {}
      this.statusDetails = Object.values(groupStats).map(item => {
        const percentage = this.statistics.totalOrders > 0 
          ? ((item.count / this.statistics.totalOrders) * 100).toFixed(2)
          : '0.00'
        return {
          ...item,
          percentage
        }
      })
    },
    /** 格式化金额 */
    formatMoney(amount) {
      if (!amount && amount !== 0) return '0.00'
      return parseFloat(amount).toFixed(2)
    },
    /** 日期范围变化处理 */
    handleDateRangeChange(dates) {
      if (dates && dates.length === 2) {
        this.queryParams.beginTime = dates[0]
        this.queryParams.endTime = dates[1]
      } else {
        this.queryParams.beginTime = null
        this.queryParams.endTime = null
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getStatistics()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.queryParams = {
        beginTime: null,
        endTime: null,
        validCode: null,
        skuId: null
      }
      this.getStatistics()
    },
    /** 初始化图表 */
    initCharts() {
      this.initStatusChart()
      this.initCommissionChart()
    },
    /** 初始化状态分布图表 */
    initStatusChart() {
      const chartDom = this.$refs.statusChart
      if (!chartDom) return
      
      const myChart = echarts.init(chartDom)
      
      const groupStats = this.statistics.groupStats || {}
      const data = Object.values(groupStats).map(item => ({
        value: item.count,
        name: item.label
      }))
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          type: 'scroll'
        },
        series: [
          {
            name: '订单状态',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data
          }
        ]
      }
      
      myChart.setOption(option)
    },
    /** 初始化佣金分布图表 */
    initCommissionChart() {
      const chartDom = this.$refs.commissionChart
      if (!chartDom) return
      
      const myChart = echarts.init(chartDom)
      
      const groupStats = this.statistics.groupStats || {}
      const data = Object.values(groupStats)
        .filter(item => item.commission > 0)
        .map(item => ({
          value: item.commission,
          name: item.label
        }))
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          type: 'scroll'
        },
        series: [
          {
            name: '佣金分布',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data
          }
        ]
      }
      
      myChart.setOption(option)
    }
  }
}
</script>

<style scoped>
.card-body {
  text-align: center;
}

.card-body h2 {
  color: #409EFF;
  margin: 10px 0;
  font-size: 28px;
}

.card-body p {
  color: #666;
  margin: 5px 0;
}

.chart-container {
  padding: 10px;
}
</style> 