<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import * as echarts from "echarts";
import { getStatisticsOverview } from "@/api/statistics";

defineOptions({
  name: "StatisticsOverview"
});

const loading = ref(false);
const dateRange = ref<[Date, Date]>([
  new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
  new Date()
]);

const overviewData = ref({
  totalSales: 0,
  totalProfit: 0,
  avgProfitRate: 0,
  totalOrders: 0,
  totalUsers: 0,
  totalDevices: 0,
  onlineDevices: 0,
  totalShops: 0,
  avgOrderAmount: 0,
  categoryList: []
});

const salesChartRef = ref<HTMLElement | null>(null);
const categoryChartRef = ref<HTMLElement | null>(null);
let salesChart: echarts.ECharts | null = null;
let categoryChart: echarts.ECharts | null = null;

const onlineRate = computed(() => {
  if (overviewData.value.totalDevices === 0) return "0%";
  return ((overviewData.value.onlineDevices / overviewData.value.totalDevices) * 100).toFixed(1) + "%";
});

async function fetchOverviewData() {
  loading.value = true;
  try {
    const params = {
      startDate: formatDate(dateRange.value[0]),
      endDate: formatDate(dateRange.value[1])
    };
    const { data } = await getStatisticsOverview(params);
    overviewData.value = data;
    initCharts();
  } catch (error) {
    console.error("获取统计概览数据失败:", error);
  } finally {
    loading.value = false;
  }
}

function formatDate(date: Date): string {
  return date.toISOString().split("T")[0];
}

function initCharts() {
  setTimeout(() => {
    initSalesChart();
    initCategoryChart();
  }, 100);
}

function initSalesChart() {
  if (!salesChartRef.value) return;
  
  if (salesChart) {
    salesChart.dispose();
  }
  
  salesChart = echarts.init(salesChartRef.value);
  
  const option: echarts.EChartsOption = {
    title: {
      text: "品类销售分布",
      left: "center",
      textStyle: { fontSize: 14, fontWeight: "normal" }
    },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: ¥{c} ({d}%)"
    },
    legend: {
      orient: "vertical",
      left: "left",
      top: "middle"
    },
    series: [
      {
        name: "销售额",
        type: "pie",
        radius: ["40%", "70%"],
        center: ["60%", "50%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2
        },
        label: {
          show: false,
          position: "center"
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: "bold"
          }
        },
        labelLine: {
          show: false
        },
        data: overviewData.value.categoryList.slice(0, 6).map((item: any) => ({
          value: item.salesAmount,
          name: item.category
        }))
      }
    ]
  };
  
  salesChart.setOption(option);
}

function initCategoryChart() {
  if (!categoryChartRef.value) return;
  
  if (categoryChart) {
    categoryChart.dispose();
  }
  
  categoryChart = echarts.init(categoryChartRef.value);
  
  const categories = overviewData.value.categoryList.slice(0, 8);
  
  const option: echarts.EChartsOption = {
    title: {
      text: "品类利润对比",
      left: "center",
      textStyle: { fontSize: 14, fontWeight: "normal" }
    },
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "shadow" }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: categories.map((item: any) => item.category),
      axisLabel: {
        rotate: 30
      }
    },
    yAxis: {
      type: "value",
      name: "利润(元)"
    },
    series: [
      {
        name: "利润额",
        type: "bar",
        data: categories.map((item: any) => item.profitAmount),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#83bff6" },
            { offset: 0.5, color: "#188df0" },
            { offset: 1, color: "#188df0" }
          ])
        }
      }
    ]
  };
  
  categoryChart.setOption(option);
}

function handleDateChange() {
  fetchOverviewData();
}

function resizeCharts() {
  salesChart?.resize();
  categoryChart?.resize();
}

onMounted(() => {
  fetchOverviewData();
  window.addEventListener("resize", resizeCharts);
});
</script>

<template>
  <div class="statistics-overview">
    <el-card shadow="never" class="mb-4">
      <div class="flex items-center justify-between">
        <span class="text-lg font-medium">统计概览</span>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
      </div>
    </el-card>

    <el-row :gutter="20" class="mb-6">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card-wrapper">
          <div class="stat-card">
            <div class="stat-icon bg-blue">
              <i class="ri:money-cny-circle-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ overviewData.totalSales?.toLocaleString() || 0 }}</div>
              <div class="stat-label">总销售额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card-wrapper">
          <div class="stat-card">
            <div class="stat-icon bg-green">
              <i class="ri:profit-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ overviewData.totalProfit?.toLocaleString() || 0 }}</div>
              <div class="stat-label">总利润</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card-wrapper">
          <div class="stat-card">
            <div class="stat-icon bg-purple">
              <i class="ri:shopping-cart-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overviewData.totalOrders?.toLocaleString() || 0 }}</div>
              <div class="stat-label">总订单数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card-wrapper">
          <div class="stat-card">
            <div class="stat-icon bg-orange">
              <i class="ri:percent-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overviewData.avgProfitRate || 0 }}%</div>
              <div class="stat-label">平均利润率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mb-6">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card-wrapper">
          <div class="stat-card">
            <div class="stat-icon bg-cyan">
              <i class="ri:user-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overviewData.totalUsers?.toLocaleString() || 0 }}</div>
              <div class="stat-label">购买用户数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card-wrapper">
          <div class="stat-card">
            <div class="stat-icon bg-teal">
              <i class="ri:device-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overviewData.totalDevices || 0 }}</div>
              <div class="stat-label">设备总数 (在线率: {{ onlineRate }})</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card-wrapper">
          <div class="stat-card">
            <div class="stat-icon bg-indigo">
              <i class="ri:store-2-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overviewData.totalShops || 0 }}</div>
              <div class="stat-label">门店总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card-wrapper">
          <div class="stat-card">
            <div class="stat-icon bg-pink">
              <i class="ri:coins-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ overviewData.avgOrderAmount || 0 }}</div>
              <div class="stat-label">平均客单价</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div ref="salesChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div ref="categoryChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.statistics-overview {
  padding: 20px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 120px);
}

.stat-card-wrapper {
  :deep(.el-card__body) {
    padding: 20px;
  }
}

.stat-card {
  display: flex;
  align-items: center;
  
  .stat-icon {
    width: 56px;
    height: 56px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    
    i {
      font-size: 28px;
      color: white;
    }
    
    &.bg-blue { background: linear-gradient(135deg, #409eff, #337ecc); }
    &.bg-green { background: linear-gradient(135deg, #67c23a, #529b2e); }
    &.bg-purple { background: linear-gradient(135deg, #722ed1, #531dab); }
    &.bg-orange { background: linear-gradient(135deg, #fa8c16, #d46b08); }
    &.bg-cyan { background: linear-gradient(135deg, #13c2c2, #08979c); }
    &.bg-teal { background: linear-gradient(135deg, #52c41a, #389e0d); }
    &.bg-indigo { background: linear-gradient(135deg, #597ef7, #2f54eb); }
    &.bg-pink { background: linear-gradient(135deg, #eb2f96, #c41d7f); }
  }
  
  .stat-info {
    flex: 1;
    
    .stat-value {
      font-size: 24px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }
    
    .stat-label {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }
}

.chart-card {
  height: 380px;
  
  :deep(.el-card__body) {
    padding: 20px;
    height: 100%;
  }
  
  .chart-container {
    width: 100%;
    height: 100%;
    min-height: 320px;
  }
}
</style>
