库存数据看板

This commit is contained in:
砂糖
2025-08-11 18:07:01 +08:00
parent 6f415c44d1
commit 68f5f5bdab
8 changed files with 1264 additions and 259 deletions

View File

@@ -0,0 +1,207 @@
<template>
<div class="chart-wrapper" ref="chartWrapper">
<!-- 操作按钮组 -->
<div class="chart-actions">
<button
class="action-btn fullscreen-btn"
@click="toggleFullscreen"
title="全屏预览"
>
<i :class="isFullscreen? 'el-icon-close' : 'el-icon-full-screen'"></i>
</button>
</div>
<!-- 图表容器插槽内容 -->
<div class="chart-container" ref="chartContainer">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isFullscreen: false, // 是否处于全屏状态
fullscreenElement: null, // 存储全屏元素引用
};
},
mounted() {
// 监听浏览器全屏状态变化事件
document.addEventListener('fullscreenchange', this.handleFullscreenChange);
document.addEventListener('webkitfullscreenchange', this.handleFullscreenChange);
document.addEventListener('mozfullscreenchange', this.handleFullscreenChange);
document.addEventListener('msfullscreenchange', this.handleFullscreenChange);
},
methods: {
// 切换全屏/退出全屏
toggleFullscreen() {
if (!this.isFullscreen) {
this.enterFullscreen();
} else {
this.exitFullscreen();
}
},
// 进入全屏模式
enterFullscreen() {
const container = this.$refs.chartWrapper;
// 不同浏览器的全屏 API 兼容
if (container.requestFullscreen) {
container.requestFullscreen();
} else if (container.webkitRequestFullscreen) { /* Safari */
container.webkitRequestFullscreen();
} else if (container.msRequestFullscreen) { /* IE11 */
container.msRequestFullscreen();
} else if (container.mozRequestFullScreen) { /* Firefox */
container.mozRequestFullScreen();
}
this.fullscreenElement = container;
},
// 退出全屏模式
exitFullscreen() {
if (!document.fullscreenElement) return;
// 不同浏览器的退出全屏 API 兼容
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitExitFullscreen) { /* Safari */
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) { /* IE11 */
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) { /* Firefox */
document.mozCancelFullScreen();
}
this.fullscreenElement = null;
},
// 处理全屏状态变化
handleFullscreenChange() {
// 检查当前是否处于全屏状态
const isFull =!!(
document.fullscreenElement ||
document.webkitFullscreenElement ||
document.mozFullScreenElement ||
document.msFullscreenElement
);
this.isFullscreen = isFull;
// 触发窗口 resize 事件,让图表自适应
this.triggerResize();
},
// 触发窗口 resize 事件(让图表自适应)
triggerResize() {
const event = document.createEvent('Event');
event.initEvent('resize', true, true);
window.dispatchEvent(event);
}
},
beforeDestroy() {
// 移除事件监听
document.removeEventListener('fullscreenchange', this.handleFullscreenChange);
document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange);
document.removeEventListener('mozfullscreenchange', this.handleFullscreenChange);
document.removeEventListener('msfullscreenchange', this.handleFullscreenChange);
// 组件销毁时如果处于全屏状态则退出
if (this.isFullscreen) {
this.exitFullscreen();
}
}
};
</script>
<style scoped>
.chart-wrapper {
position: relative;
width: 100%;
height: 100%;
min-height: 100px; /* 最小高度防止内容为空时样式异常 */
}
/* 全屏状态下的样式调整 */
.chart-wrapper:-webkit-full-screen {
background-color: #fff;
width: 100%!important;
height: 100%!important;
}
.chart-wrapper:-moz-full-screen {
background-color: #fff;
width: 100%!important;
height: 100%!important;
}
.chart-wrapper:fullscreen {
background-color: #fff;
width: 100%!important;
height: 100%!important;
}
.chart-container {
width: 100%;
height: 100%;
min-height: inherit;
}
/* 操作按钮组样式 */
.chart-actions {
position: absolute;
top: 10px;
right: 10px;
z-index: 10; /* 确保按钮在图表上方 */
display: flex;
gap: 8px;
}
.action-btn {
width: 32px;
height: 32px;
border-radius: 4px;
border: none;
background-color: rgba(255, 255, 255, 0.8);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
transition: all 0.2s ease;
}
.action-btn:hover {
background-color: #fff;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
/* 图标样式(适配 Element UI 图标) */
.action-btn i {
font-size: 16px;
color: #666;
}
.action-btn:hover i {
color: #1890ff;
}
/* 全屏状态下的按钮样式优化 */
:fullscreen.chart-actions {
top: 20px;
right: 20px;
}
:-webkit-full-screen.chart-actions {
top: 20px;
right: 20px;
}
:-moz-full-screen.chart-actions {
top: 20px;
right: 20px;
}
</style>

View File

@@ -36,7 +36,6 @@
<el-table v-loading="loading" :data="stockLogList" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="主键ID" align="center" prop="id" v-if="true"/>
<el-table-column label="存储位置" align="center" prop="warehouseName" />
<el-table-column label="物品ID" align="center" prop="itemId">
<template slot-scope="scope">

View File

@@ -2,32 +2,82 @@
<div style="display: flex; height: calc(100vh - 100px);">
<!-- 左侧导航树 -->
<div style="width: 280px; min-width: 200px; border-right: 1px solid #eee; padding: 10px 0;">
<el-tree
:data="warehouseTreeData"
node-key="warehouseId"
:props="treeProps"
highlight-current
@node-click="handleTreeNodeClick"
:default-expand-all="true"
style="height: 100%; overflow-y: auto;"
/>
<el-tree :data="warehouseTreeData" node-key="warehouseId" :props="treeProps" highlight-current
@node-click="handleTreeNodeClick" :default-expand-all="true" style="height: 100%; overflow-y: auto;" />
</div>
<!-- 右侧图表 -->
<div ref="chartContainer" style="flex: 1; height: 100%;"></div>
<div style="flex: 1; height: calc(100vh - 100px); overflow-y: scroll; overflow-x: hidden;">
<el-row>
<el-col :span="24">
<el-card>
<template #header>
仓库库存
</template>
<div style="height: 600px;">
<ChartWrapper>
<rea-tree ref="reaTree" :stock-data="stockData" :warehouse-tree-data="warehouseTreeData" height="600px" />
</ChartWrapper>
</div>
</el-card>
</el-col>
</el-row>
<el-row :gutter="10">
<el-col :span="12">
<el-card>
<template #header>
物料统计TOP10
</template>
<div style="height: 300px;">
<ChartWrapper>
<material-bar ref="materialBar" :stock-data="stockData"
:selected-warehouse-id="currentTreeNode ? currentTreeNode.warehouseId : null"
:warehouse-tree-data="warehouseTreeData" />
</ChartWrapper>
</div>
</el-card>
</el-col>
<el-col :span="12">
<el-card>
<template #header>
变动趋势
<el-date-picker style="float: right;" v-model="defaultTimeRange" type="daterange" range-separator="至"
start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" />
</template>
<div style="height: 300px;">
<ChartWrapper>
<TrendChart ref="trendChart" :warehouseId="currentTreeNode ? currentTreeNode.warehouseId : null"
:time-range="defaultTimeRange"></TrendChart>
</ChartWrapper>
</div>
</el-card>
</el-col>
</el-row>
</div>
</div>
</template>
<script>
import * as echarts from 'echarts';
import { listStock } from "@/api/wms/stock";
import { listWarehouse } from "@/api/wms/warehouse";
import 'element-ui/lib/theme-chalk/index.css';
import ReaTree from './panels/reattree.vue';
import MaterialBar from './panels/bar.vue';
import TrendChart from './panels/trendChart.vue';
import ChartWrapper from '@/components/ChartWrapper/index.vue';
export default {
name: "StockBox",
components: {
ReaTree,
MaterialBar,
TrendChart,
ChartWrapper
},
data() {
return {
chart: null,
stockData: [],
warehouseData: [],
warehouseTreeData: [],
@@ -37,49 +87,29 @@ export default {
isLeaf: 'isLeaf',
id: 'id'
},
currentTreeNode: null
currentTreeNode: null,
defaultTimeRange: [
new Date(new Date().setDate(new Date().getDate() - 30)).toISOString().split('T')[0],
new Date().toISOString().split('T')[0]
]
};
},
mounted() {
this.initChart();
this.loadData();
},
methods: {
initChart() {
if (this.chart) {
this.chart.dispose();
}
this.chart = echarts.init(this.$refs.chartContainer);
window.addEventListener('resize', this.handleResize);
},
handleResize() {
this.chart && this.chart.resize();
},
async loadData() {
try {
// 显示加载动画
this.chart.showLoading();
const [warehouseRes, stockRes] = await Promise.all([
listWarehouse(),
listStock({ pageNum: 1, pageSize: 9999 })
]);
// 隐藏加载动画
this.chart.hideLoading();
// 处理树结构
this.warehouseTreeData = this.handleTree(warehouseRes.data, 'warehouseId', 'parentId');
this.stockData = stockRes.rows;
// 创建层级数据
const treeData = this.createTreeData();
// 更新图表
this.updateChart(treeData);
} catch (error) {
console.error('加载数据失败:', error);
this.chart.hideLoading();
this.$message.error('库存数据加载失败');
}
},
@@ -89,216 +119,26 @@ export default {
console.error('handleTree: data is not array', data);
return [];
}
const map = {};
const tree = [];
// 创建节点映射
data.forEach(item => {
map[item[id]] = { ...item, children: [] };
});
// 构建树结构
data.forEach(item => {
const node = map[item[id]];
if (!item[parentId] || item[parentId] === 0) {
// 顶级节点parentId为0或null
tree.push(node);
} else if (map[item[parentId]]) {
map[item[parentId]].children.push(node);
}
});
return tree;
},
// 创建树形数据
createTreeData() {
// 递归构建仓库树
const buildWarehouseTree = (warehouseNode, parentId = '') => {
const stocks = this.stockData.filter(stock => stock.warehouseId === warehouseNode.warehouseId);
const children = [];
let totalQuantity = 0;
// 添加库存物品
stocks.forEach(stock => {
const quantity = Number(stock.quantity) || 0;
totalQuantity += quantity;
// 物料节点 id 用 仓库id+物料编码
children.push({
id: `${warehouseNode.warehouseId}_${stock.itemCode || stock.itemName}`,
name: stock.itemName,
value: quantity,
itemInfo: {
type: stock.itemType,
code: stock.itemCode,
unit: stock.unit,
batchNo: stock.batchNo
}
});
});
// 递归处理子仓库
if (warehouseNode.children && warehouseNode.children.length > 0) {
warehouseNode.children.forEach(child => {
const childNode = buildWarehouseTree(child, warehouseNode.warehouseId);
if (childNode.value > 0) {
children.push(childNode);
totalQuantity += childNode.value;
}
});
}
// 仓库节点 id 用 warehouseId
return {
id: String(warehouseNode.warehouseId),
name: warehouseNode.warehouseName,
value: totalQuantity,
warehouseInfo: {
code: warehouseNode.warehouseCode
},
children: children.length > 0 ? children : undefined
};
};
// 直接返回顶级仓库节点
return this.warehouseTreeData.map(warehouse => buildWarehouseTree(warehouse));
},
// 获取层级样式配置参考ECharts官网示例
getLevelOption() {
return [
// 顶级仓库层级样式parentId为0或null
{
itemStyle: {
borderColor: '#555',
borderWidth: 4,
gapWidth: 3
},
emphasis: {
itemStyle: {
borderColor: '#333'
}
},
upperLabel: {
show: true,
height: 35,
fontSize: 16,
fontWeight: 'bold',
color: '#333'
}
},
// 子仓库层级样式
{
itemStyle: {
borderColor: '#777',
borderWidth: 3,
gapWidth: 2
},
emphasis: {
itemStyle: {
borderColor: '#555'
}
},
upperLabel: {
show: true,
height: 28,
fontSize: 14
}
},
// 物料层级样式
{
itemStyle: {
borderColor: '#999',
borderWidth: 2,
gapWidth: 1
},
emphasis: {
itemStyle: {
borderColor: '#777'
}
}
}
];
},
// 更新图表
updateChart(treeData) {
const option = {
title: {
left: 'center',
textStyle: {
fontSize: 18
}
},
tooltip: {
formatter: (info) => {
const value = info.value || 0;
const treePath = info.treePathInfo || [];
let path = '';
// 构建完整路径(从第一个节点开始)
for (let i = 0; i < treePath.length; i++) {
if (treePath[i].name) {
path += treePath[i].name;
if (i < treePath.length - 1) path += '/';
}
}
const content = [];
content.push(`<div class="tooltip-title">${echarts.format.encodeHTML(path)}</div>`);
content.push(`库存数量: ${echarts.format.addCommas(value)} ${this.getItemUnit(info.data)}`);
// 添加物品详细信息
if (info.data.itemInfo) {
const item = info.data.itemInfo;
content.push(`物料类型: ${this.getItemTypeName(item.type)}`);
content.push(`物料编码: ${item.code || '无'}`);
if (item.batchNo) content.push(`批次号: ${item.batchNo}`);
}
return content.join('<br>');
}
},
series: [{
name: '库存',
type: 'treemap',
visibleMin: 300, // 只有当区块面积大于300时才会显示标签
leafDepth: 2, // 只在叶子节点显示标签
label: {
show: true,
fontSize: 12,
formatter: (params) => {
// 对于物料只显示名称和数量
if (params.data.itemInfo) {
const unit = params.data.itemInfo.unit || '';
return `${params.name}\n${params.value}${unit}`;
}
// 对于仓库只显示名称
return params.name;
},
ellipsis: true // 超出时显示省略号
},
upperLabel: {
show: true,
fontWeight: 'bold'
},
itemStyle: {
borderColor: '#fff',
borderWidth: 1
},
levels: this.getLevelOption(),
data: treeData // 直接使用顶级仓库节点数组
}]
};
this.chart.setOption(option, true);
},
// 获取物料单位
getItemUnit(data) {
return data.itemInfo?.unit || '';
},
// 获取物料类型名称
getItemTypeName(type) {
const typeMap = {
raw_material: '原材料',
product: '产品',
semi_product: '半成品'
};
return typeMap[type] || type || '未分类';
return tree;
},
// 刷新数据
refresh() {
@@ -307,32 +147,9 @@ export default {
// 导航树点击事件
handleTreeNodeClick(node) {
this.currentTreeNode = node;
// 图表高亮并聚焦对应节点
if (node && node.warehouseId) {
this.highlightChartNode(node.warehouseId);
this.$refs.reaTree.highlightNode(node.warehouseId);
}
},
// 高亮并聚焦图表节点
highlightChartNode(id) {
if (!this.chart) return;
// 高亮节点
this.chart.dispatchAction({
type: 'highlight',
seriesIndex: 0,
targetNodeId: id
});
// 聚焦节点(自动缩放到该节点)
this.chart.dispatchAction({
type: 'treemapRootToNode',
seriesIndex: 0,
targetNodeId: id
});
}
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
if (this.chart) {
this.chart.dispose();
}
}
};
@@ -345,4 +162,8 @@ export default {
height: 100%;
min-height: 600px;
}
.el-row {
margin: 10px !important;
}
</style>

View File

@@ -37,12 +37,12 @@
<el-col :span="1.5">
<el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
</el-col>
<el-col :span="1.5">
<!-- <el-col :span="1.5">
<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleStockBox">添加暂存单据</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleViewStockBox">查看暂存单据</el-button>
</el-col>
</el-col> -->
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
</el-row>

View File

@@ -0,0 +1,218 @@
<template>
<div ref="chartContainer" style="height: 100%;"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
name: "MaterialBar",
props: {
// 图表高度
height: {
type: String,
default: '300px'
},
// 库存数据
stockData: {
type: Array,
default: () => []
},
// 选中的仓库ID
selectedWarehouseId: {
type: [String, Number],
default: null
},
// 仓库树数据
warehouseTreeData: {
type: Array,
default: () => []
}
},
data() {
return {
chart: null
};
},
watch: {
stockData: {
handler: 'updateChart',
deep: true
},
selectedWarehouseId: {
handler: 'updateChart',
immediate: true
}
},
mounted() {
this.initChart();
this.updateChart();
},
methods: {
initChart() {
if (this.chart) {
this.chart.dispose();
}
this.chart = echarts.init(this.$refs.chartContainer);
window.addEventListener('resize', this.handleResize);
},
handleResize() {
this.chart && this.chart.resize();
},
// 获取所有子仓库ID包括自身
getAllWarehouseIds(warehouseId) {
const ids = new Set();
const findChildren = (treeData, targetId) => {
for (const node of treeData) {
if (String(node.warehouseId) === String(targetId)) {
// 找到目标节点收集它和它的所有子节点的ID
const collectIds = (node) => {
ids.add(String(node.warehouseId));
if (node.children) {
node.children.forEach(child => collectIds(child));
}
};
collectIds(node);
return true;
}
if (node.children && findChildren(node.children, targetId)) {
return true;
}
}
return false;
};
if (warehouseId) {
findChildren(this.warehouseTreeData, warehouseId);
}
return ids;
},
// 处理数据获取前10的物料
processData() {
let filteredData;
if (this.selectedWarehouseId) {
// 获取选中仓库及其所有子仓库的ID
const warehouseIds = this.getAllWarehouseIds(this.selectedWarehouseId);
// 过滤属于这些仓库的数据
filteredData = this.stockData.filter(item => warehouseIds.has(String(item.warehouseId)));
} else {
filteredData = this.stockData;
}
// 按物料分组并汇总数量
const materialMap = new Map();
filteredData.forEach(item => {
const key = item.itemName;
const quantity = Number(item.quantity) || 0;
const currentQuantity = materialMap.get(key) || 0;
materialMap.set(key, currentQuantity + quantity);
});
// 转换为数组并排序
const sortedData = Array.from(materialMap.entries())
.map(([name, value]) => ({ name, value }))
.sort((a, b) => b.value - a.value)
.slice(0, 10); // 只取前10名
return sortedData;
},
updateChart() {
if (!this.chart) return;
const data = this.processData();
const names = data.map(item => item.name);
const values = data.map(item => item.value);
// 计算最大值,用于设置图表的最大刻度
const maxValue = Math.max(...values);
const interval = Math.ceil(maxValue / 5); // 将刻度分为5份
const option = {
title: {
text: this.selectedWarehouseId ? '当前仓库及子仓库物料TOP10' : '全部仓库物料TOP10',
left: 'center'
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
},
formatter: (params) => {
const data = params[0];
return `${data.name}<br/>数量: ${data.value}`;
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'value',
boundaryGap: [0, 0.01],
max: Math.ceil(maxValue / interval) * interval,
interval: interval
},
yAxis: {
type: 'category',
data: names,
axisTick: {
alignWithLabel: true
},
axisLabel: {
formatter: (value) => {
// 如果名称太长,截断并添加省略号
if (value.length > 10) {
return value.substring(0, 10) + '...';
}
return value;
}
}
},
series: [
{
name: '数量',
type: 'bar',
data: values,
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
{ offset: 0, color: '#83bff6' },
{ offset: 0.5, color: '#188df0' },
{ offset: 1, color: '#188df0' }
])
},
emphasis: {
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
{ offset: 0, color: '#2378f7' },
{ offset: 0.7, color: '#2378f7' },
{ offset: 1, color: '#83bff6' }
])
}
},
label: {
show: true,
position: 'right',
formatter: '{c}'
}
}
]
};
this.chart.setOption(option, true);
}
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
if (this.chart) {
this.chart.dispose();
this.chart = null;
}
}
};
</script>

View File

@@ -0,0 +1,269 @@
<template>
<div ref="chartContainer" :style="{ height: '100%' }"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
name: "ReaTree",
props: {
// 图表高度
height: {
type: String,
default: '600px'
},
// 库存数据
stockData: {
type: Array,
default: () => []
},
// 仓库数据树
warehouseTreeData: {
type: Array,
default: () => []
}
},
data() {
return {
chart: null
};
},
mounted() {
this.initChart();
this.updateChartData();
},
watch: {
stockData: {
handler: 'updateChartData',
deep: true
},
warehouseTreeData: {
handler: 'updateChartData',
deep: true
}
},
methods: {
initChart() {
if (this.chart) {
this.chart.dispose();
}
this.chart = echarts.init(this.$refs.chartContainer);
window.addEventListener('resize', this.handleResize);
},
handleResize() {
this.chart && this.chart.resize();
},
// 创建树形数据
createTreeData() {
// 递归构建仓库树
const buildWarehouseTree = (warehouseNode, parentId = '') => {
const stocks = this.stockData.filter(stock => stock.warehouseId === warehouseNode.warehouseId);
const children = [];
let totalQuantity = 0;
// 添加库存物品
stocks.forEach(stock => {
const quantity = Number(stock.quantity) || 0;
totalQuantity += quantity;
children.push({
id: `${warehouseNode.warehouseId}_${stock.itemCode || stock.itemName}`,
name: stock.itemName,
value: quantity,
itemInfo: {
type: stock.itemType,
code: stock.itemCode,
unit: stock.unit,
batchNo: stock.batchNo
}
});
});
// 递归处理子仓库
if (warehouseNode.children && warehouseNode.children.length > 0) {
warehouseNode.children.forEach(child => {
const childNode = buildWarehouseTree(child, warehouseNode.warehouseId);
if (childNode.value > 0) {
children.push(childNode);
totalQuantity += childNode.value;
}
});
}
return {
id: String(warehouseNode.warehouseId),
name: warehouseNode.warehouseName,
value: totalQuantity,
warehouseInfo: {
code: warehouseNode.warehouseCode
},
children: children.length > 0 ? children : undefined
};
};
return this.warehouseTreeData.map(warehouse => buildWarehouseTree(warehouse));
},
// 获取层级样式配置
getLevelOption() {
return [
{
itemStyle: {
borderColor: '#555',
borderWidth: 4,
gapWidth: 3
},
emphasis: {
itemStyle: {
borderColor: '#333'
}
},
upperLabel: {
show: true,
height: 35,
fontSize: 16,
fontWeight: 'bold',
color: '#333'
}
},
{
itemStyle: {
borderColor: '#777',
borderWidth: 3,
gapWidth: 2
},
emphasis: {
itemStyle: {
borderColor: '#555'
}
},
upperLabel: {
show: true,
height: 28,
fontSize: 14
}
},
{
itemStyle: {
borderColor: '#999',
borderWidth: 2,
gapWidth: 1
},
emphasis: {
itemStyle: {
borderColor: '#777'
}
}
}
];
},
// 获取物料单位
getItemUnit(data) {
return data.itemInfo?.unit || '';
},
// 获取物料类型名称
getItemTypeName(type) {
const typeMap = {
raw_material: '原材料',
product: '产品',
semi_product: '半成品'
};
return typeMap[type] || type || '未分类';
},
// 更新图表数据
updateChartData() {
if (!this.chart) return;
const treeData = this.createTreeData();
const option = {
tooltip: {
formatter: (info) => {
const value = info.value || 0;
const treePath = info.treePathInfo || [];
let path = '';
for (let i = 0; i < treePath.length; i++) {
if (treePath[i].name) {
path += treePath[i].name;
if (i < treePath.length - 1) path += '/';
}
}
const content = [];
content.push(`<div class="tooltip-title">${echarts.format.encodeHTML(path)}</div>`);
content.push(`库存数量: ${echarts.format.addCommas(value)} ${this.getItemUnit(info.data)}`);
if (info.data.itemInfo) {
const item = info.data.itemInfo;
content.push(`物料类型: ${this.getItemTypeName(item.type)}`);
content.push(`物料编码: ${item.code || '无'}`);
if (item.batchNo) content.push(`批次号: ${item.batchNo}`);
}
return content.join('<br>');
}
},
series: [{
name: '库存',
type: 'treemap',
visibleMin: 300,
leafDepth: 2,
label: {
show: true,
fontSize: 12,
formatter: (params) => {
if (params.data.itemInfo) {
const unit = params.data.itemInfo.unit || '';
return `${params.name}\n${params.value}${unit}`;
}
return params.name;
},
ellipsis: true
},
upperLabel: {
show: true,
fontWeight: 'bold'
},
itemStyle: {
borderColor: '#fff',
borderWidth: 1
},
levels: this.getLevelOption(),
data: treeData
}]
};
this.chart.setOption(option, true);
},
// 高亮指定节点
highlightNode(id) {
if (!this.chart) return;
this.chart.dispatchAction({
type: 'highlight',
seriesIndex: 0,
targetNodeId: id
});
this.chart.dispatchAction({
type: 'treemapRootToNode',
seriesIndex: 0,
targetNodeId: id
});
}
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
if (this.chart) {
this.chart.dispose();
this.chart = null;
}
}
};
</script>
<style scoped>
.tooltip-title {
font-weight: bold;
margin-bottom: 5px;
}
</style>

View File

@@ -0,0 +1,85 @@
// 防抖函数:避免频繁触发 resize
function debounce(fn, delay = 100) {
let timer = null;
return function (...args) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
timer = null;
}, delay);
};
}
export default {
data() {
return {
// 存储ResizeObserver实例
resizeObserver: null,
// 标记是否已初始化监听
isResizeListening: false
};
},
methods: {
/**
* 初始化尺寸监听
* @param {HTMLElement} container - 图表容器DOM默认取this.$refs.chartContainer
*/
initResizeListener(container) {
// 防止重复初始化
if (this.isResizeListening) return;
// 默认使用组件内的chartContainer作为监听目标
const target = container || this.$refs.chartContainer;
if (!target) {
console.warn('未找到图表容器,无法初始化尺寸监听');
return;
}
// 创建ResizeObserver实例
this.resizeObserver = new ResizeObserver(
debounce(entries => {
// 触发图表重绘
this.handleContainerResize(entries);
})
);
// 开始监听容器尺寸变化
this.resizeObserver.observe(target);
this.isResizeListening = true;
},
/**
* 处理容器尺寸变化
* @param {ResizeObserverEntry[]} entries - ResizeObserver回调参数
*/
handleContainerResize(entries) {
// 确保图表实例存在
if (this.chart && this.chart.resize) {
// 调用ECharts的resize方法重绘图表
this.chart.resize();
}
},
/**
* 销毁尺寸监听
*/
destroyResizeListener() {
if (this.resizeObserver) {
this.resizeObserver.disconnect();
this.resizeObserver = null;
}
this.isResizeListening = false;
}
},
// 组件挂载后初始化监听
mounted() {
// 延迟初始化确保DOM已渲染完成
this.$nextTick(() => {
this.initResizeListener();
});
},
// 组件销毁前清理监听
beforeDestroy() {
this.destroyResizeListener();
}
};

View File

@@ -0,0 +1,406 @@
<template>
<div class="chart-container">
<div v-if="isDrilled" class="drill-header">
<button @click="backToSummary" class="back-btn"> 返回汇总</button>
</div>
<div id="trendChart" style="width: 100%; height: 100%;"></div>
</div>
</template>
<script>
import { listStockLog } from '@/api/wms/stockLog';
import * as echarts from 'echarts';
import Resize from './resize';
export default {
name: 'TrendChart',
mixins: [Resize],
data() {
return {
trendChart: null,
allData: [], // 存储原始数据
dailySummary: {}, // 存储按天汇总数据
isDrilled: false, // 是否处于钻取状态
currentDrillDate: '' // 当前钻取的日期
};
},
props: {
timeRange: {
required: true,
type: Array,
},
warehouseId: {
required: false,
type: String,
},
},
mounted() {
this.initChart();
this.getTrendData();
},
watch: {
timeRange: {
handler: function() {
// 当时间范围变化时,重置钻取状态
this.isDrilled = false;
this.currentDrillDate = '';
this.getTrendData();
},
immediate: true,
},
warehouseId: function() {
this.isDrilled = false;
this.currentDrillDate = '';
this.getTrendData();
},
},
methods: {
initChart() {
this.trendChart = echarts.init(document.getElementById('trendChart'));
// 绑定双击事件用于数据钻取
this.trendChart.on('dblclick', (params) => {
// 如果点击的是坐标轴空白区域,返回汇总视图
if (params.componentType === 'grid') {
if (this.isDrilled) {
this.backToSummary();
}
return;
}
// 如果是柱状图元素,进行钻取
if (params.componentType === 'series' &&!this.isDrilled) {
const dateIndex = params.dataIndex;
const sortedDates = Object.keys(this.dailySummary).sort((a, b) => new Date(a) - new Date(b));
const drillDate = sortedDates[dateIndex];
this.drillDownToDate(drillDate);
}
});
window.addEventListener('resize', () => {
this.trendChart.resize();
});
},
getTrendData() {
const { timeRange, warehouseId } = this;
const params = {
startTime: timeRange? timeRange[0] + ' 00:00:00' : '',
endTime: timeRange? timeRange[1] + ' 23:59:59' : '',
warehouseId,
pageSize: 999999,
pageNum: 1,
};
listStockLog(params).then((res) => {
this.allData = res.rows;
this.processAndRenderData();
});
},
processAndRenderData() {
// 按日期分组统计
this.dailySummary = {};
this.allData.forEach((item) => {
const dateArr = item.changeTime.split(' ')[0].split('-');
const year = dateArr[0];
const month = dateArr[1].padStart(2, '0');
const day = dateArr[2].padStart(2, '0');
const date = `${year}-${month}-${day}`;
const changeQty = parseFloat(item.changeQty);
if (!this.dailySummary[date]) {
this.dailySummary[date] = {
total: 0,
items: []
};
}
this.dailySummary[date].total += changeQty;
this.dailySummary[date].items.push(item);
});
// 根据当前状态渲染不同视图
if (this.isDrilled) {
this.renderDetailChart(this.currentDrillDate);
} else {
this.renderSummaryChart();
}
},
renderSummaryChart() {
const sortedDates = Object.keys(this.dailySummary).sort((a, b) => new Date(a) - new Date(b));
const categories = sortedDates;
const placeholderData = [0];
const incomeData = [];
const expensesData = [];
let accumulatedValue = 0;
sortedDates.forEach((date) => {
const dailyChange = this.dailySummary[date].total;
accumulatedValue += dailyChange;
placeholderData.push(accumulatedValue);
if (dailyChange > 0) {
incomeData.push(dailyChange);
expensesData.push('-');
} else {
incomeData.push('-');
expensesData.push(Math.abs(dailyChange));
}
});
const option = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow',
},
formatter: (params) => {
let tar;
if (params[1] && params[1].value!== '-') {
tar = params[1];
} else {
tar = params[2];
}
if (tar) {
const date = sortedDates[tar.dataIndex];
const itemCount = this.dailySummary[date].items.length;
return `
<div>日期: ${date}</div>
<div>当日库存变化: ${this.dailySummary[date].total}</div>
<div>累计库存变化: ${placeholderData[tar.dataIndex + 1]}</div>
<div>操作记录: ${itemCount} 条</div>
<div style="color:#888">双击查看明细</div>
`;
}
return '';
},
},
legend: {
data: ['入库', '出库'],
top: 30,
},
grid: {
left: '3%',
right: '4%',
bottom: '15%',
containLabel: true,
},
xAxis: {
type: 'category',
data: categories,
axisLabel: {
rotate: 45,
interval: 0,
fontSize: 12,
},
},
yAxis: {
type: 'value',
name: '库存变化量',
nameLocation:'middle',
nameGap: 30,
},
series: [
{
name: '占位',
type: 'bar',
stack: 'Total',
silent: true,
itemStyle: {
color: 'transparent',
},
data: placeholderData.slice(0, -1),
},
{
name: '入库',
type: 'bar',
stack: 'Total',
label: {
show: true,
position: 'top',
formatter: (params) => params.value!== '-'? `+${params.value}` : '',
},
itemStyle: {
color: '#52c41a',
},
data: incomeData,
},
{
name: '出库',
type: 'bar',
stack: 'Total',
label: {
show: true,
position: 'bottom',
formatter: (params) => params.value!== '-'? `-${params.value}` : '',
},
itemStyle: {
color: '#f5222d',
},
data: expensesData,
},
],
};
this.trendChart.setOption(option);
},
// 钻取到指定日期的明细
drillDownToDate(date) {
this.isDrilled = true;
this.currentDrillDate = date;
this.renderDetailChart(date);
},
// 渲染明细图表
renderDetailChart(date) {
const dayItems = this.dailySummary[date].items.sort((a, b) => new Date(a.changeTime) - new Date(b.changeTime));
// 准备明细数据
const timeLabels = dayItems.map(item => {
const timePart = item.changeTime.split(' ')[1];
return timePart.slice(0, 5); // 只显示时分
});
const values = dayItems.map(item => {
const qty = parseFloat(item.changeQty);
return {
value: qty,
itemStyle: {
color: qty > 0? '#52c41a' : '#f5222d'
},
label: {
show: true,
position: qty > 0? 'top' : 'bottom',
formatter: `${qty > 0? '+' : ''}${qty}`
}
};
});
// 计算累积值用于阶梯效果
const bases = [0];
let accumulated = 0;
dayItems.forEach((item, index) => {
if (index > 0) {
accumulated += parseFloat(dayItems[index - 1].changeQty);
bases.push(accumulated);
}
});
const option = {
title: {
text: `${date} 库存变动明细`,
left: 'center'
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
},
formatter: (params) => {
const item = dayItems[params[0].dataIndex];
return `
<div>时间: ${item.changeTime}</div>
<div>类型: ${item.changeType}</div>
<div>物料ID: ${item.itemId}</div>
<div>变化量: ${item.changeQty}</div>
<div>操作后数量: ${item.afterQty}</div>
${item.remark? `<div>备注: ${item.remark}</div>` : ''}
`;
}
},
grid: {
left: '5%',
right: '4%',
bottom: '15%',
containLabel: true
},
xAxis: {
type: 'category',
data: timeLabels,
axisLabel: {
rotate: 45,
interval: 0
},
name: '时间'
},
yAxis: {
type: 'value',
name: '数量'
},
series: [
{
name: '占位',
type: 'bar',
stack: 'Detail',
silent: true,
itemStyle: {
color: 'transparent'
},
data: bases
},
{
name: '变动',
type: 'bar',
stack: 'Detail',
data: values,
barWidth: '60%'
}
]
};
this.trendChart.setOption(option);
},
// 返回汇总视图
backToSummary() {
this.isDrilled = false;
this.currentDrillDate = '';
this.renderSummaryChart();
},
},
beforeDestroy() {
window.removeEventListener('resize', () => {
this.trendChart.resize();
});
if (this.trendChart) {
this.trendChart.dispose();
}
},
};
</script>
<style scoped>
.chart-container {
position: relative;
}
.drill-header {
padding: 10px 0;
display: flex;
align-items: center;
gap: 10px;
}
.back-btn {
padding: 4px 10px;
background-color: #1890ff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
display: flex;
align-items: center;
gap: 5px;
}
.back-btn:hover {
background-color: #096dd9;
}
.drill-header h3 {
margin: 0;
font-size: 16px;
color: #333;
}
</style>