index.vue 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. <script setup lang="ts">
  2. import { ref, onMounted, onUnmounted, computed } from "vue";
  3. import * as echarts from "echarts";
  4. import { getCategoryOverview, getCategoryTrend } from "@/api/statistics";
  5. import type { EChartsOption } from "echarts";
  6. defineOptions({
  7. name: "CategoryStatistics"
  8. });
  9. interface CategoryStat {
  10. category: string;
  11. quantity: number;
  12. salesAmount: number;
  13. costAmount: number;
  14. profitAmount: number;
  15. profitRate: number;
  16. orderCount: number;
  17. percentage: number;
  18. }
  19. const loading = ref(false);
  20. const dateRange = ref<[Date, Date]>([
  21. new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
  22. new Date()
  23. ]);
  24. const activeShortcut = ref("30d");
  25. const shortcuts = [
  26. { key: "today", label: "今日" },
  27. { key: "week", label: "本周" },
  28. { key: "month", label: "本月" },
  29. { key: "30d", label: "近30天" }
  30. ];
  31. const categoryList = ref<CategoryStat[]>([]);
  32. const selectedCategory = ref("");
  33. const totalSales = computed(() => categoryList.value.reduce((s, i) => s + (i.salesAmount || 0), 0));
  34. const totalProfit = computed(() => categoryList.value.reduce((s, i) => s + (i.profitAmount || 0), 0));
  35. const avgProfitRate = computed(() => {
  36. if (totalSales.value === 0) return 0;
  37. return Number(((totalProfit.value / totalSales.value) * 100).toFixed(2));
  38. });
  39. // 图表引用
  40. const pieChartRef = ref<HTMLElement | null>(null);
  41. const barChartRef = ref<HTMLElement | null>(null);
  42. const trendChartRef = ref<HTMLElement | null>(null);
  43. let pieChart: echarts.ECharts | null = null;
  44. let barChart: echarts.ECharts | null = null;
  45. let trendChart: echarts.ECharts | null = null;
  46. function formatDate(date: Date): string {
  47. return date.toISOString().split("T")[0];
  48. }
  49. function setDateShortcut(type: string) {
  50. activeShortcut.value = type;
  51. const today = new Date();
  52. today.setHours(23, 59, 59, 999);
  53. let start: Date;
  54. switch (type) {
  55. case "today": start = new Date(); start.setHours(0, 0, 0, 0); break;
  56. case "week": start = new Date(today); start.setDate(today.getDate() - 6); start.setHours(0, 0, 0, 0); break;
  57. case "month": start = new Date(today.getFullYear(), today.getMonth(), 1); break;
  58. case "30d": default: start = new Date(today); start.setDate(today.getDate() - 29); start.setHours(0, 0, 0, 0); break;
  59. }
  60. dateRange.value = [start, today];
  61. fetchData();
  62. }
  63. async function fetchData() {
  64. loading.value = true;
  65. try {
  66. const params = { startDate: formatDate(dateRange.value[0]), endDate: formatDate(dateRange.value[1]) };
  67. const res = await getCategoryOverview(params);
  68. if (res.code === 200 && res.data) {
  69. categoryList.value = res.data;
  70. }
  71. initCharts();
  72. fetchTrendData();
  73. } catch (error) {
  74. console.error("获取品类统计数据失败:", error);
  75. } finally {
  76. loading.value = false;
  77. }
  78. }
  79. async function fetchTrendData() {
  80. try {
  81. const params: any = {
  82. startDate: formatDate(dateRange.value[0]),
  83. endDate: formatDate(dateRange.value[1]),
  84. period: "day"
  85. };
  86. if (selectedCategory.value) params.category = selectedCategory.value;
  87. const res = await getCategoryTrend(params);
  88. if (res.code === 200 && res.data) {
  89. initTrendChart(res.data);
  90. }
  91. } catch (error) {
  92. console.error("获取品类趋势数据失败:", error);
  93. }
  94. }
  95. function handleCategoryClick(category: string) {
  96. selectedCategory.value = selectedCategory.value === category ? "" : category;
  97. fetchTrendData();
  98. }
  99. function handleDateChange() {
  100. activeShortcut.value = "";
  101. fetchData();
  102. }
  103. // ==================== 图表 ====================
  104. function initCharts() {
  105. setTimeout(() => { initPieChart(); initBarChart(); }, 100);
  106. }
  107. const COLORS = ["#5470c6", "#91cc75", "#fac858", "#ee6666", "#73c0de", "#3ba272", "#fc8452", "#9a60b4"];
  108. function initPieChart() {
  109. if (!pieChartRef.value) return;
  110. pieChart?.dispose();
  111. pieChart = echarts.init(pieChartRef.value);
  112. const option: EChartsOption = {
  113. title: { text: "品类销售额占比", left: "center", top: 10, textStyle: { fontSize: 14, fontWeight: "bold" } },
  114. tooltip: { trigger: "item", formatter: (p: any) => `${p.name}: ¥${p.value?.toLocaleString() || 0} (${p.percent}%)` },
  115. legend: { orient: "vertical", left: 10, top: "middle", itemWidth: 12, itemHeight: 12 },
  116. series: [{
  117. type: "pie", radius: ["45%", "72%"], center: ["58%", "55%"],
  118. avoidLabelOverlap: false, itemStyle: { borderRadius: 6, borderColor: "#fff", borderWidth: 2 },
  119. label: { show: false }, emphasis: { label: { show: true, fontSize: 16, fontWeight: "bold" } }, labelLine: { show: false },
  120. data: categoryList.value.slice(0, 8).map((item, i) => ({
  121. value: item.salesAmount, name: item.category, itemStyle: { color: COLORS[i % COLORS.length] }
  122. }))
  123. }]
  124. };
  125. pieChart.setOption(option);
  126. }
  127. function initBarChart() {
  128. if (!barChartRef.value) return;
  129. barChart?.dispose();
  130. barChart = echarts.init(barChartRef.value);
  131. const list = [...categoryList.value].sort((a, b) => (b.profitAmount || 0) - (a.profitAmount || 0)).slice(0, 10);
  132. const option: EChartsOption = {
  133. title: { text: "品类利润对比 (TOP10)", left: "center", top: 10, textStyle: { fontSize: 14, fontWeight: "bold" } },
  134. tooltip: { trigger: "axis", axisPointer: { type: "shadow" }, formatter: (p: any) => `${p[0].name}<br/>利润: ¥${p[0].value?.toLocaleString()}` },
  135. grid: { left: "3%", right: "8%", bottom: "3%", top: "15%", containLabel: true },
  136. xAxis: { type: "category", data: list.map(i => i.category), axisLabel: { rotate: 30, fontSize: 11 } },
  137. yAxis: { type: "value", name: "利润(元)", axisLabel: { formatter: (v: number) => v >= 10000 ? (v / 10000).toFixed(1) + "万" : String(v) } },
  138. series: [{ name: "利润额", type: "bar", data: list.map(i => i.profitAmount),
  139. itemStyle: { borderRadius: [4, 4, 0, 0], color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: "#91cc75" }, { offset: 1, color: "#3ba272" }]) }
  140. }]
  141. };
  142. barChart.setOption(option);
  143. }
  144. function initTrendChart(data: any) {
  145. if (!trendChartRef.value) return;
  146. trendChart?.dispose();
  147. trendChart = echarts.init(trendChartRef.value);
  148. const series = (data.series || []).map((s: any) => ({ name: s.name, type: "line" as const, smooth: true, data: s.data, symbol: "circle", symbolSize: 4 }));
  149. const option: EChartsOption = {
  150. title: { text: selectedCategory.value ? `${selectedCategory.value} 销售趋势` : "品类销售趋势", left: "center", top: 10, textStyle: { fontSize: 14, fontWeight: "bold" } },
  151. tooltip: { trigger: "axis", backgroundColor: "#fff", borderColor: "#e5e7eb", textStyle: { color: "#333" } },
  152. legend: { data: series.map(s => s.name), bottom: 0 },
  153. grid: { left: "3%", right: "4%", bottom: "12%", top: "15%", containLabel: true },
  154. xAxis: { type: "category", data: data.dates || [], axisLabel: { rotate: 45, fontSize: 11 } },
  155. yAxis: { type: "value", name: "销售额(元)", axisLabel: { formatter: (v: number) => v >= 10000 ? (v / 10000).toFixed(1) + "万" : String(v) } },
  156. series
  157. };
  158. trendChart.setOption(option);
  159. }
  160. function resizeCharts() {
  161. pieChart?.resize();
  162. barChart?.resize();
  163. trendChart?.resize();
  164. }
  165. onMounted(() => {
  166. fetchData();
  167. window.addEventListener("resize", resizeCharts);
  168. });
  169. onUnmounted(() => {
  170. window.removeEventListener("resize", resizeCharts);
  171. pieChart?.dispose();
  172. barChart?.dispose();
  173. trendChart?.dispose();
  174. });
  175. </script>
  176. <template>
  177. <div class="category-statistics">
  178. <!-- 工具栏 -->
  179. <div class="toolbar">
  180. <h2 class="page-title">品类销售统计</h2>
  181. <div class="toolbar-right">
  182. <div class="date-shortcuts">
  183. <el-button v-for="s in shortcuts" :key="s.key" :type="activeShortcut === s.key ? 'primary' : 'default'" size="small" @click="setDateShortcut(s.key)">{{ s.label }}</el-button>
  184. </div>
  185. <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" size="small" @change="handleDateChange" />
  186. </div>
  187. </div>
  188. <div v-loading="loading" class="page-body">
  189. <!-- KPI 卡片 -->
  190. <el-row :gutter="16" class="kpi-row">
  191. <el-col :span="8">
  192. <div class="kpi-card kpi-blue">
  193. <div class="kpi-label">总销售额</div>
  194. <div class="kpi-value">¥{{ totalSales.toLocaleString() }}</div>
  195. </div>
  196. </el-col>
  197. <el-col :span="8">
  198. <div class="kpi-card kpi-green">
  199. <div class="kpi-label">总利润</div>
  200. <div class="kpi-value">¥{{ totalProfit.toLocaleString() }}</div>
  201. </div>
  202. </el-col>
  203. <el-col :span="8">
  204. <div class="kpi-card kpi-orange">
  205. <div class="kpi-label">平均利润率</div>
  206. <div class="kpi-value">{{ avgProfitRate }}%</div>
  207. </div>
  208. </el-col>
  209. </el-row>
  210. <!-- 图表区 -->
  211. <el-row :gutter="16" class="chart-row">
  212. <el-col :span="12">
  213. <div class="chart-box"><div ref="pieChartRef" class="chart-container"></div></div>
  214. </el-col>
  215. <el-col :span="12">
  216. <div class="chart-box"><div ref="barChartRef" class="chart-container"></div></div>
  217. </el-col>
  218. </el-row>
  219. <el-row :gutter="16" class="chart-row">
  220. <el-col :span="24">
  221. <div class="chart-box chart-box-tall"><div ref="trendChartRef" class="chart-container"></div></div>
  222. </el-col>
  223. </el-row>
  224. <!-- 明细表格 -->
  225. <div class="table-box">
  226. <div class="table-header">
  227. <span class="table-title">品类销售明细</span>
  228. <span class="table-hint" v-if="selectedCategory">当前选中: <el-tag size="small" closable @close="handleCategoryClick(selectedCategory)">{{ selectedCategory }}</el-tag></span>
  229. </div>
  230. <el-table :data="categoryList" stripe v-loading="loading" @row-click="(row: any) => handleCategoryClick(row.category)" style="cursor: pointer;">
  231. <el-table-column prop="category" label="品类名称" min-width="120" fixed="left">
  232. <template #default="{ row }">
  233. <el-button type="primary" link size="small">{{ row.category }}</el-button>
  234. </template>
  235. </el-table-column>
  236. <el-table-column prop="quantity" label="销售数量" width="100" align="right">
  237. <template #default="{ row }">{{ row.quantity?.toLocaleString() || 0 }}</template>
  238. </el-table-column>
  239. <el-table-column prop="salesAmount" label="销售额(元)" width="130" align="right" sortable>
  240. <template #default="{ row }">¥{{ row.salesAmount?.toLocaleString() || 0 }}</template>
  241. </el-table-column>
  242. <el-table-column prop="costAmount" label="成本额(元)" width="130" align="right">
  243. <template #default="{ row }">¥{{ row.costAmount?.toLocaleString() || 0 }}</template>
  244. </el-table-column>
  245. <el-table-column prop="profitAmount" label="利润额(元)" width="130" align="right" sortable>
  246. <template #default="{ row }">
  247. <span :style="{ color: (row.profitAmount || 0) >= 0 ? '#52c41a' : '#f5222d' }">¥{{ row.profitAmount?.toLocaleString() || 0 }}</span>
  248. </template>
  249. </el-table-column>
  250. <el-table-column prop="profitRate" label="利润率" width="90" align="right" sortable>
  251. <template #default="{ row }">
  252. <span :style="{ color: (row.profitRate || 0) >= 0 ? '#52c41a' : '#f5222d' }">{{ row.profitRate }}%</span>
  253. </template>
  254. </el-table-column>
  255. <el-table-column prop="orderCount" label="订单数" width="90" align="right" sortable>
  256. <template #default="{ row }">{{ row.orderCount?.toLocaleString() || 0 }}</template>
  257. </el-table-column>
  258. <el-table-column prop="percentage" label="销售占比" width="100" align="right" sortable>
  259. <template #default="{ row }">
  260. <el-progress :percentage="Number(row.percentage) || 0" :stroke-width="6" :show-text="false" style="width: 60px; display: inline-block; vertical-align: middle;" />
  261. <span style="margin-left: 6px;">{{ row.percentage }}%</span>
  262. </template>
  263. </el-table-column>
  264. </el-table>
  265. </div>
  266. </div>
  267. </div>
  268. </template>
  269. <style lang="scss" scoped>
  270. .category-statistics {
  271. padding: 16px 20px;
  272. background-color: #f5f7fa;
  273. min-height: calc(100vh - 120px);
  274. }
  275. .toolbar {
  276. display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; flex-wrap: wrap; gap: 12px;
  277. .page-title { margin: 0; font-size: 18px; font-weight: 600; color: #1d2129; }
  278. .toolbar-right { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
  279. .date-shortcuts { display: flex; gap: 4px; }
  280. }
  281. .page-body { min-height: 400px; }
  282. .kpi-row { margin-bottom: 12px; }
  283. .kpi-card {
  284. background: #fff; border-radius: 8px; padding: 16px 20px; height: 100%; border-left: 4px solid #409eff; transition: box-shadow 0.2s;
  285. &:hover { box-shadow: 0 2px 12px rgba(0,0,0,0.08); }
  286. &.kpi-blue { border-left-color: #409eff; }
  287. &.kpi-green { border-left-color: #67c23a; }
  288. &.kpi-orange { border-left-color: #fa8c16; }
  289. .kpi-label { font-size: 13px; color: #86909c; margin-bottom: 6px; }
  290. .kpi-value { font-size: 22px; font-weight: 700; color: #1d2129; line-height: 1.2; }
  291. }
  292. .chart-row { margin-bottom: 12px; }
  293. .chart-box {
  294. background: #fff; border-radius: 8px; padding: 16px; height: 360px;
  295. &.chart-box-tall { height: 380px; }
  296. .chart-container { width: 100%; height: 100%; }
  297. }
  298. .table-box {
  299. background: #fff; border-radius: 8px; padding: 16px;
  300. .table-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; }
  301. .table-title { font-size: 14px; font-weight: 600; color: #1d2129; }
  302. .table-hint { font-size: 13px; color: #86909c; }
  303. }
  304. @media (max-width: 768px) {
  305. .kpi-value { font-size: 18px !important; }
  306. .chart-box, .chart-box-tall { height: 280px; }
  307. }
  308. </style>