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

defineOptions({
  name: "ProductStatistics"
});

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

const queryParams = reactive({
  page: 1,
  pageSize: 10,
  keyword: "",
  category: "",
  sortBy: "salesAmount",
  sortOrder: "desc"
});

const tableData = ref([]);
const total = ref(0);
const topProducts = ref([]);

const topChartRef = ref<HTMLElement | null>(null);
let topChart: echarts.ECharts | null = null;

async function fetchProductList() {
  loading.value = true;
  try {
    const params = {
      ...queryParams,
      startDate: formatDate(dateRange.value[0]),
      endDate: formatDate(dateRange.value[1])
    };
    
    const { data } = await getProductList(params);
    tableData.value = data.list || [];
    total.value = Number(data.total) || 0;
  } catch (error) {
    console.error("获取商品统计数据失败:", error);
  } finally {
    loading.value = false;
  }
}

async function fetchTopProducts() {
  try {
    const params = {
      startDate: formatDate(dateRange.value[0]),
      endDate: formatDate(dateRange.value[1]),
      type: "sales",
      limit: 10
    };
    
    const { data } = await getProductTop(params);
    topProducts.value = data || [];
    initTopChart();
  } catch (error) {
    console.error("获取TOP商品失败:", error);
  }
}

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

function initTopChart() {
  if (!topChartRef.value || topProducts.value.length === 0) return;
  
  if (topChart) {
    topChart.dispose();
  }
  
  topChart = echarts.init(topChartRef.value);
  
  const option: echarts.EChartsOption = {
    title: {
      text: "商品销售额TOP10",
      left: "center",
      textStyle: { fontSize: 14, fontWeight: "normal" }
    },
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "shadow" }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "value",
      name: "销售额(元)"
    },
    yAxis: {
      type: "category",
      data: topProducts.value.map((item: any) => item.productName).reverse(),
      axisLabel: {
        width: 100,
        overflow: "truncate"
      }
    },
    series: [
      {
        name: "销售额",
        type: "bar",
        data: topProducts.value.map((item: any) => item.salesAmount).reverse(),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: "#83bff6" },
            { offset: 1, color: "#188df0" }
          ])
        }
      }
    ]
  };
  
  topChart.setOption(option);
}

function handleSearch() {
  queryParams.page = 1;
  fetchProductList();
}

function handleReset() {
  queryParams.keyword = "";
  queryParams.category = "";
  queryParams.page = 1;
  fetchProductList();
}

function handleSortChange({ prop, order }: any) {
  queryParams.sortBy = prop || "salesAmount";
  queryParams.sortOrder = order === "ascending" ? "asc" : "desc";
  fetchProductList();
}

function handlePageChange(page: number) {
  queryParams.page = page;
  fetchProductList();
}

function handleSizeChange(size: number) {
  queryParams.pageSize = size;
  queryParams.page = 1;
  fetchProductList();
}

function handleDateChange() {
  fetchProductList();
  fetchTopProducts();
}

function resizeCharts() {
  topChart?.resize();
}

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

<template>
  <div class="product-statistics">
    <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="12">
        <el-card shadow="hover" class="chart-card">
          <div ref="topChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <span>TOP10商品列表</span>
          </template>
          <el-table :data="topProducts" stripe max-height="300">
            <el-table-column type="index" label="排名" width="60" />
            <el-table-column prop="productName" label="商品名称" show-overflow-tooltip />
            <el-table-column prop="quantity" label="销量" width="80" align="right" />
            <el-table-column prop="salesAmount" label="销售额" width="100" align="right">
              <template #default="{ row }">
                ¥{{ row.salesAmount?.toLocaleString() }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="never">
      <template #header>
        <div class="flex items-center justify-between">
          <span class="font-medium">商品销售明细</span>
          <div class="flex gap-2">
            <el-input
              v-model="queryParams.keyword"
              placeholder="商品名称/编码"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            />
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </div>
      </template>
      
      <el-table
        :data="tableData"
        stripe
        v-loading="loading"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="productCode" label="商品编码" width="120" />
        <el-table-column prop="productName" label="商品名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="category" label="品类" width="100" />
        <el-table-column prop="quantity" label="销售数量" width="100" align="right" sortable="custom" />
        <el-table-column prop="salesAmount" label="销售额(元)" width="120" align="right" sortable="custom">
          <template #default="{ row }">
            ¥{{ row.salesAmount?.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="costAmount" label="成本额(元)" width="120" align="right">
          <template #default="{ row }">
            ¥{{ row.costAmount?.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="profitAmount" label="利润额(元)" width="120" align="right" sortable="custom">
          <template #default="{ row }">
            <span :class="row.profitAmount >= 0 ? 'text-green-500' : 'text-red-500'">
              ¥{{ row.profitAmount?.toLocaleString() }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="profitRate" label="利润率" width="100" align="right">
          <template #default="{ row }">
            <span :class="row.profitRate >= 0 ? 'text-green-500' : 'text-red-500'">
              {{ row.profitRate }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="orderCount" label="订单数" width="80" align="right" />
        <el-table-column prop="userCount" label="购买人数" width="90" align="right" />
      </el-table>
      
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

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

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