feat: 安环管理

This commit is contained in:
砂糖
2025-09-30 20:52:52 +08:00
parent 29c0c7bb73
commit 184e24cdff
8 changed files with 1752 additions and 190 deletions

View File

@@ -12,12 +12,12 @@
<el-tree @node-click="handleNodeClick" :data="locationList" :props="defaultProps" :default-expand-all="true" :style="{ height: 'calc(50vh - 50px)' }"></el-tree>
<!-- 设备列表 -->
<ul v-if="locationId">
<!-- <ul v-if="locationId">
<li></li>
</ul>
<div v-else>
<el-empty description="请选择区域"></el-empty>
</div>
</div> -->
</el-col>
<el-col :span="20" v-if="showRight">

View File

@@ -1,239 +1,608 @@
<template>
<div class="energy-analysis-container">
<!-- 年份选择与查询按钮区域 -->
<div class="query-section">
<el-input
v-model="year"
placeholder="请输入年份"
style="width: 200px; margin-right: 10px;"
/>
<el-button type="primary" @click="handleQuery">查询</el-button>
</div>
<!-- 图表区域含图例图表类型切换刷新 -->
<div class="chart-section">
<el-row :gutter="10" align="middle" style="margin-bottom: 10px;">
<!-- 图例 -->
<el-col>
<div class="legend-item">
<span class="legend-dot" style="background-color: #409EFF;"></span>
<span>本期</span>
</div>
<div class="legend-item">
<span class="legend-dot" style="background-color: #C084FC;"></span>
<span>同期</span>
</div>
<div class="month-on-month-analysis">
<!-- 筛选区域//年切换 + 单周期选择 -->
<div class="filter-section">
<el-row :gutter="20" align="middle">
<!-- 时间类型切换默认选中按周 -->
<el-col :span="6">
<el-select
v-model="timeType"
placeholder="请选择时间类型"
@change="handleTimeTypeChange"
clearable
>
<el-option label="按周" value="week"></el-option>
<el-option label="按月" value="month"></el-option>
<el-option label="按年" value="year"></el-option>
</el-select>
</el-col>
<!-- 图表类型切换 + 刷新 -->
<el-col :offset="18">
<el-button-group>
<el-button type="text" @click="chartType = 'bar'">柱状图</el-button>
<el-button type="text" @click="chartType = 'line'">折线图</el-button>
</el-button-group>
<el-button icon="el-icon-refresh" type="text" @click="handleRefresh">刷新</el-button>
<!-- 日期选择器单周期选择非范围 -->
<el-col :span="12">
<!-- 1. 按周单周选择器 -->
<el-date-picker
v-if="timeType === 'week'"
v-model="dateRange"
type="date"
placeholder="选择周"
format="yyyy年第WW周"
value-format="yyyy-'W'WW"
picker-options="{ type: 'week' }"
:disabled-date="disableFutureDate"
></el-date-picker>
<!-- 2. 按月单月选择器 -->
<el-date-picker
v-else-if="timeType === 'month'"
v-model="dateRange"
type="date"
placeholder="选择月"
format="yyyy-MM"
value-format="yyyy-MM"
picker-options="{ type: 'month' }"
:disabled-date="disableFutureDate"
></el-date-picker>
<!-- 3. 按年单年选择器 -->
<el-date-picker
v-else-if="timeType === 'year'"
v-model="dateRange"
type="date"
placeholder="选择年"
format="yyyy"
value-format="yyyy"
picker-options="{ type: 'year' }"
:disabled-date="disableFutureDate"
></el-date-picker>
</el-col>
<!-- 查询/重置按钮无选择时禁用查询 -->
<el-col :span="6">
<el-button type="primary" @click="handleQuery" :disabled="!dateRange">查询</el-button>
<el-button type="text" @click="handleReset" style="margin-left: 10px;">重置</el-button>
</el-col>
</el-row>
<!-- ECharts 容器 -->
<div ref="chartRef" class="echarts-box" />
</div>
<!-- 同比分析表格 -->
<div class="table-section">
<el-table :data="tableData" border style="width: 100%">
<el-table-column prop="periodTime" label="本期时间" />
<el-table-column prop="currentEnergy" label="本期能耗(Nm3)" />
<el-table-column prop="samePeriodEnergy" label="同比能耗(Nm3)" />
<el-table-column prop="yearOnYear" label="同比(%)" />
</el-table>
<!-- 加载状态 -->
<div v-if="loading" class="loading-container">
<el-loading-spinner></el-loading-spinner>
<p>数据加载中...</p>
</div>
<!-- 环比指标卡区域保持原有展示逻辑 -->
<div v-else class="indicator-cards">
<el-row :gutter="20">
<!-- 当期值 -->
<el-col :span="6">
<div class="indicator-card">
<div class="card-header">
<span class="card-title">当期值</span>
<span class="card-period">{{ currentPeriodText }}</span>
</div>
<div class="card-value">{{ formatNumber(currentValue) }} {{ unit }}</div>
<div class="card-desc">当前{{ timeTypeMap[timeType] }}{{ indicatorName }}</div>
</div>
</el-col>
<!-- 上期值 -->
<el-col :span="6">
<div class="indicator-card">
<div class="card-header">
<span class="card-title">上期值</span>
<span class="card-period">{{ previousPeriodText }}</span>
</div>
<div class="card-value">{{ formatNumber(previousValue) }} {{ unit }}</div>
<div class="card-desc">上一个{{ timeTypeMap[timeType] }}{{ indicatorName }}</div>
</div>
</el-col>
<!-- 增加值 -->
<el-col :span="6">
<div class="indicator-card">
<div class="card-header">
<span class="card-title">增加值</span>
<span class="card-icon"><i class="el-icon-arrow-right"></i></span>
</div>
<div class="card-value" :class="increaseValue > 0 ? 'text-increase' : increaseValue < 0 ? 'text-decrease' : ''">
{{ formatNumber(increaseValue) }} {{ unit }}
</div>
<div class="card-desc">当期 - 上期</div>
</div>
</el-col>
<!-- 环比 -->
<el-col :span="6">
<div class="indicator-card">
<div class="card-header">
<span class="card-title">环比</span>
<span class="card-icon"><i class="el-icon-refresh"></i></span>
</div>
<div class="card-value" :class="monthOnMonth > 0 ? 'text-increase' : monthOnMonth < 0 ? 'text-decrease' : ''">
{{ monthOnMonth !== null ? (monthOnMonth * 100).toFixed(2) + '%' : '--' }}
</div>
<div class="card-desc">当期 - 上期/ 上期 × 100%</div>
</div>
</el-col>
</el-row>
</div>
</div>
</template>
<script>
import echarts from 'echarts'
export default {
name: 'MonthToMonthAnalysis',
name: 'CycleAnalysis',
props: {
energyType: {
type: String,
default: ''
},
locationId: {
type: String,
default: ''
},
deviceId: {
type: String,
default: ''
},
// 数据单位kWh、Nm³、元
unit: {
type: String,
default: ''
default: 'kWh'
},
energyName: {
// 指标名称(如:能耗、费用、产量)
indicatorName: {
type: String,
default: ''
default: '能耗'
}
},
data() {
return {
year: '2025',
chartType: 'bar',
tableData: [
{ periodTime: '1月', currentEnergy: '--', samePeriodEnergy: '--', yearOnYear: '--' },
{ periodTime: '2月', currentEnergy: '--', samePeriodEnergy: '--', yearOnYear: '--' },
{ periodTime: '3月', currentEnergy: '--', samePeriodEnergy: '--', yearOnYear: '--' },
{ periodTime: '4月', currentEnergy: '--', samePeriodEnergy: '--', yearOnYear: '--' },
{ periodTime: '5月', currentEnergy: '--', samePeriodEnergy: '--', yearOnYear: '--' },
{ periodTime: '6月', currentEnergy: '--', samePeriodEnergy: '--', yearOnYear: '--' },
{ periodTime: '7月', currentEnergy: '--', samePeriodEnergy: '--', yearOnYear: '--' },
{ periodTime: '8月', currentEnergy: '--', samePeriodEnergy: '--', yearOnYear: '--' },
{ periodTime: '9月', currentEnergy: '--', samePeriodEnergy: '--', yearOnYear: '--' },
{ periodTime: '10月', currentEnergy: '--', samePeriodEnergy: '--', yearOnYear: '--' },
{ periodTime: '11月', currentEnergy: '--', samePeriodEnergy: '--', yearOnYear: '--' },
{ periodTime: '12月', currentEnergy: '--', samePeriodEnergy: '--', yearOnYear: '--' }
],
chartInstance: null
// 时间类型默认按周week
timeType: 'week',
// 单周期选择值格式week→yyyy-Wwwmonth→yyyy-MMyear→yyyy
dateRange: '',
// 加载状态
loading: false,
// 核心数据
currentValue: null, // 当期值
previousValue: null, // 上期值
increaseValue: null, // 增加值(当期-上期)
monthOnMonth: null, // 环比((当期-上期)/上期)
// 周期文本描述2025年第23周、2025年06月
currentPeriodText: '',
previousPeriodText: '',
// 时间类型映射(用于文案显示)
timeTypeMap: {
week: '周',
month: '月',
year: '年'
}
}
},
mounted() {
this.initChart()
},
beforeDestroy() {
if (this.chartInstance) {
this.chartInstance.dispose()
}
},
watch: {
chartType: {
handler(newVal) {
this.drawChart()
},
immediate: true
}
// 初始化默认周期(当前周/月/年)+ 自动查询一次
this.initDateRange()
this.handleQuery()
},
methods: {
// 初始化图表
initChart() {
this.chartInstance = echarts.init(this.$refs.chartRef)
this.drawChart()
// 监听窗口大小变化,调整图表尺寸
window.addEventListener('resize', this.handleResize)
},
// 绘制图表
drawChart() {
const option = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
},
yAxis: {
type: 'value'
},
series: [
{
name: '本期',
type: this.chartType,
data: [120, 132, 101, 134, 90, 230, 210, 120, 132, 101, 134, 90],
itemStyle: {
color: '#409EFF'
}
},
{
name: '同期',
type: this.chartType,
data: [90, 110, 120, 110, 120, 140, 130, 90, 110, 120, 110, 120],
itemStyle: {
color: '#C084FC'
}
}
]
/**
* 初始化默认周期(当前时间类型的当前周期)
*/
initDateRange() {
const now = new Date()
const year = now.getFullYear()
let currentPeriod
switch (this.timeType) {
case 'week':
// 周格式yyyy-Www两位周数
const [currentWeek] = this.getWeekInfo(now)
currentPeriod = `${year}-W${this.padZero(currentWeek)}`
break
case 'month':
// 月格式yyyy-MM两位月份
const currentMonth = now.getMonth() + 1
currentPeriod = `${year}-${this.padZero(currentMonth)}`
break
case 'year':
// 年格式yyyy
currentPeriod = `${year}`
break
}
this.chartInstance.setOption(option)
this.dateRange = currentPeriod
// 同步更新周期文本(当期+上期)
this.updatePeriodText()
},
// 处理查询
/**
* 获取周信息(本年周数 + 周起始日期)
* @param {Date} date - 日期对象
* @returns {Array} [周数, 周起始日期Date]
*/
getWeekInfo(date) {
const firstDayOfYear = new Date(date.getFullYear(), 0, 1)
const pastDaysOfYear = (date - firstDayOfYear) / (24 * 60 * 60 * 1000)
// 周日为一周第一天,计算本年周数
const weekNumber = Math.ceil((pastDaysOfYear + firstDayOfYear.getDay() + 1) / 7)
// 计算当前周的起始日期(周日)
const weekStart = new Date(date)
weekStart.setDate(date.getDate() - date.getDay())
return [weekNumber, weekStart]
},
/**
* 计算上期周期(根据当前周期自动推导)
* @param {String} currentPeriod - 当前周期2025-W23、2025-06、2025
* @param {String} timeType - 时间类型week/month/year
* @returns {String} 上期周期
*/
getPreviousPeriod(currentPeriod, timeType) {
const [year, part] = currentPeriod.split(
timeType === 'week' ? '-W' : timeType === 'month' ? '-' : ''
)
let prevYear = parseInt(year)
let prevPart
switch (timeType) {
case 'week':
const currentWeek = parseInt(part)
// 若当前是第1周上期为上一年最后一周
if (currentWeek === 1) {
prevYear -= 1
prevPart = this.getLastWeekOfYear(prevYear)
} else {
prevPart = currentWeek - 1
}
return `${prevYear}-W${this.padZero(prevPart)}`
case 'month':
const currentMonth = parseInt(part)
// 若当前是1月上期为上一年12月
if (currentMonth === 1) {
prevYear -= 1
prevPart = 12
} else {
prevPart = currentMonth - 1
}
return `${prevYear}-${this.padZero(prevPart)}`
case 'year':
// 上期为上一年
return `${prevYear - 1}`
}
},
/**
* 获取某一年的最后一周(处理跨年周场景)
* @param {Number} year - 年份
* @returns {Number} 最后一周的周数
*/
getLastWeekOfYear(year) {
const lastDayOfYear = new Date(year, 11, 31) // 12月31日
const [lastWeek] = this.getWeekInfo(lastDayOfYear)
return lastWeek
},
/**
* 将周期转换为时间段startDate ~ endDate格式yyyy-MM-dd
* @param {String} period - 周期2025-W23、2025-06、2025
* @param {String} timeType - 时间类型week/month/year
* @returns {Object} { start: 开始日期, end: 结束日期 }
*/
getPeriodTimeRange(period, timeType) {
let startDate, endDate
const [year, part] = period.split(
timeType === 'week' ? '-W' : timeType === 'month' ? '-' : ''
)
const targetYear = parseInt(year)
switch (timeType) {
case 'week':
const week = parseInt(part)
// 计算该年第N周的起始日期周日
const firstDayOfYear = new Date(targetYear, 0, 1)
const firstWeekStart = new Date(firstDayOfYear)
firstWeekStart.setDate(firstDayOfYear.getDate() - firstDayOfYear.getDay())
// 第N周起始 = 第一周起始 + (N-1)*7天
startDate = new Date(firstWeekStart)
startDate.setDate(firstWeekStart.getDate() + (week - 1) * 7)
// 第N周结束 = 起始 + 6天周六
endDate = new Date(startDate)
endDate.setDate(startDate.getDate() + 6)
break
case 'month':
const month = parseInt(part) - 1 // 月份从0开始
startDate = new Date(targetYear, month, 1) // 当月1号
endDate = new Date(targetYear, month + 1, 0) // 当月最后一天
break
case 'year':
startDate = new Date(targetYear, 0, 1) // 1月1号
endDate = new Date(targetYear, 11, 31) // 12月31号
break
}
// 格式化为 yyyy-MM-dd
const format = (date) => date.toISOString().split('T')[0]
return { start: format(startDate), end: format(endDate) }
},
/**
* 更新周期文本描述(当期+上期)
*/
updatePeriodText() {
if (!this.dateRange) return
const currentPeriod = this.dateRange
const previousPeriod = this.getPreviousPeriod(currentPeriod, this.timeType)
switch (this.timeType) {
case 'week':
const [currWYear, currW] = currentPeriod.split('-W')
const [prevWYear, prevW] = previousPeriod.split('-W')
this.currentPeriodText = `${currWYear}年第${currW}`
this.previousPeriodText = `${prevWYear}年第${prevW}`
break
case 'month':
const [currMYear, currM] = currentPeriod.split('-')
const [prevMYear, prevM] = previousPeriod.split('-')
this.currentPeriodText = `${currMYear}${currM}`
this.previousPeriodText = `${prevMYear}${prevM}`
break
case 'year':
this.currentPeriodText = `${currentPeriod}`
this.previousPeriodText = `${previousPeriod}`
break
}
},
/**
* 时间类型切换:重置周期 + 自动查询
*/
handleTimeTypeChange() {
this.dateRange = ''
this.initDateRange()
this.resetData()
this.handleQuery()
},
/**
* 查询按钮:构建参数 + 调用接口 + 计算环比
*/
handleQuery() {
// 实际项目中这里会调用接口获取数据
console.log('查询年份:', this.year)
// 模拟数据加载
this.tableData = this.tableData.map(item => ({
...item,
currentEnergy: Math.floor(Math.random() * 1000) + '',
samePeriodEnergy: Math.floor(Math.random() * 1000) + '',
yearOnYear: (Math.random() * 20 - 10).toFixed(2) + ''
}))
this.drawChart()
this.loading = true
// 1. 构建接口参数(含当期/上期时间段)
const apiParams = this.buildApiParams()
// 2. 调用接口实际项目替换为axios
this.mockApiRequest(apiParams)
.then(({ currentValue, previousValue }) => {
// 3. 保存原始数据保留2位小数
this.currentValue = Number(currentValue.toFixed(2))
this.previousValue = Number(previousValue.toFixed(2))
// 4. 计算增加值和环比
this.calculateIndicators()
// 5. 更新周期文本
this.updatePeriodText()
})
.catch(err => {
this.$message.error(`数据获取失败:${err.message}`)
this.resetData()
})
.finally(() => {
this.loading = false
})
},
// 刷新图表
handleRefresh() {
this.drawChart()
},
// 处理窗口大小变化
handleResize() {
if (this.chartInstance) {
this.chartInstance.resize()
/**
* 构建接口参数(核心:传递当期/上期时间段)
* @returns {Object} 接口请求参数
*/
buildApiParams() {
if (!this.dateRange) return {}
// 当前周期 + 上期周期
const currentPeriod = this.dateRange
const previousPeriod = this.getPreviousPeriod(currentPeriod, this.timeType)
// 转换为时间段start/end: yyyy-MM-dd
const currentTimeRange = this.getPeriodTimeRange(currentPeriod, this.timeType)
const previousTimeRange = this.getPeriodTimeRange(previousPeriod, this.timeType)
return {
indicatorName: this.indicatorName, // 指标名称(如:能耗)
timeType: this.timeType, // 时间类型week/month/year
currentRange: currentTimeRange, // 当期时间段
previousRange: previousTimeRange // 上期时间段
}
},
/**
* 模拟接口请求实际项目替换为axios.post/get
* @param {Object} params - 接口参数
* @returns {Promise} 包含当期/上期值的Promise
*/
mockApiRequest(params) {
return new Promise((resolve) => {
// 模拟网络延迟
setTimeout(() => {
// 根据时间类型生成合理范围的随机数据(以上期为基础)
let baseValue = 0
switch (params.timeType) {
case 'week':
baseValue = 7000 + Math.random() * 2000 // 周数据7000-9000
break
case 'month':
baseValue = 30000 + Math.random() * 5000 // 月数据30000-35000
break
case 'year':
baseValue = 365000 + Math.random() * 50000 // 年数据36.5万-41.5万
break
}
// 当期值 = 上期值 × 随机波动(-5% ~ +15%
const previousValue = baseValue
const fluctuation = -0.05 + Math.random() * 0.2 // 波动范围:-5% ~ +15%
const currentValue = previousValue * (1 + fluctuation)
resolve({ currentValue, previousValue })
}, 800)
})
},
/**
* 计算增加值和环比处理上期为0的异常场景
*/
calculateIndicators() {
// 增加值 = 当期 - 上期
this.increaseValue = this.currentValue - this.previousValue
// 环比 = (当期 - 上期) / 上期上期为0时特殊处理
if (this.previousValue === 0) {
this.monthOnMonth = this.currentValue > 0 ? 1 : 0 // 上期为0时当期有值则环比100%
} else {
this.monthOnMonth = this.increaseValue / this.previousValue
}
},
/**
* 重置:恢复默认周期 + 清空数据 + 自动查询
*/
handleReset() {
this.initDateRange()
this.resetData()
this.handleQuery()
},
/**
* 清空核心数据
*/
resetData() {
this.currentValue = null
this.previousValue = null
this.increaseValue = null
this.monthOnMonth = null
this.currentPeriodText = ''
this.previousPeriodText = ''
},
/**
* 数字补零(确保周数/月份为两位)
* @param {Number} num - 需补零的数字
* @returns {String} 补零后的字符串
*/
padZero(num) {
return num < 10 ? `0${num}` : `${num}`
},
/**
* 格式化数字(千分位分隔 + 保留2位小数
* @param {Number} num - 需格式化的数字
* @returns {String} 格式化后的字符串
*/
formatNumber(num) {
if (num === null || isNaN(num)) return '--'
return num.toLocaleString('zh-CN', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
})
},
/**
* 禁用未来日期选择(无法选择未到的周/月/年)
* @param {Date} date - 待判断日期
* @returns {Boolean} 是否禁用
*/
disableFutureDate(date) {
return date > new Date()
},
refresh() {
this.handleQuery()
}
}
}
</script>
<style scoped>
.energy-analysis-container {
.month-on-month-analysis {
padding: 20px;
background-color: #fff;
border-radius: 4px;
border-radius: 6px;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}
.query-section {
.filter-section {
margin-bottom: 20px;
padding-bottom: 15px;
border-bottom: 1px solid #f0f0f0;
}
.indicator-cards {
margin-top: 10px;
}
.indicator-card {
background-color: #fff;
border-radius: 6px;
padding: 18px;
height: 100%;
border: 1px solid #f0f0f0;
transition: all 0.3s ease;
}
.indicator-card:hover {
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
transform: translateY(-2px);
}
.card-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
}
.chart-section {
margin-bottom: 20px;
.card-title {
font-size: 14px;
color: #666;
font-weight: 500;
}
.echarts-box {
width: 100%;
height: 400px;
border: 1px solid #e6e6e6;
.card-period {
font-size: 12px;
color: #999;
background-color: #f5f7fa;
padding: 2px 8px;
border-radius: 4px;
}
.legend-item {
display: inline-block;
margin-right: 20px;
vertical-align: middle;
.card-icon {
color: #409eff;
font-size: 14px;
}
.legend-dot {
display: inline-block;
width: 12px;
height: 12px;
border-radius: 50%;
margin-right: 5px;
.card-value {
font-size: 26px;
font-weight: 600;
color: #333;
margin-bottom: 6px;
transition: color 0.3s ease;
}
.table-section {
margin-top: 20px;
.card-desc {
font-size: 12px;
color: #999;
}
</style>
/* 增加值/环比颜色:上升红、下降绿 */
.text-increase {
color: #f56c6c;
}
.text-decrease {
color: #67c23a;
}
/* 加载状态 */
.loading-container {
text-align: center;
padding: 60px 0;
color: #666;
}
.loading-container p {
margin-top: 12px;
font-size: 14px;
}
</style>

View File

@@ -1,5 +1,340 @@
<template>
<div>
同比分析
<div class="energy-analysis-container">
<!-- 年份选择与查询按钮区域增加年份格式验证 -->
<div class="query-section">
<el-date-picker v-model="year" type="year" value-format="yyyy" placeholder="选择年份" style="margin-right: 10px;"/>
<el-button type="primary" @click="handleQuery">查询</el-button>
</div>
<!-- 图表区域新增刷新按钮优化图例布局 -->
<div class="chart-section">
<el-row :gutter="10" align="middle" style="margin-bottom: 10px;">
<!-- 图例 -->
<el-col :span="4">
<div class="legend-item">
<span class="legend-dot" style="background-color: #409EFF;"></span>
<span>本期{{ year }}</span>
</div>
<div class="legend-item">
<span class="legend-dot" style="background-color: #C084FC;"></span>
<span>同期{{ Number(year) - 1 }}</span>
</div>
</el-col>
<!-- 图表类型切换 + 刷新按钮 -->
<el-col :span="20" class="chart-operation">
<el-button-group>
<el-button type="text" :class="{ active: chartType === 'bar' }" @click="chartType = 'bar'">柱状图</el-button>
<el-button type="text" :class="{ active: chartType === 'line' }" @click="chartType = 'line'">折线图</el-button>
<el-button type="text" @click="handleRefresh">
<i class="el-icon-refresh"></i> 刷新数据
</el-button>
</el-button-group>
</el-col>
</el-row>
<!-- ECharts 容器增加无数据提示 -->
<div ref="chartRef" class="echarts-box" />
</div>
<!-- 同比分析表格格式化数据显示 -->
<div class="table-section">
<el-table :data="tableData" border style="width: 100%" :cell-style="{ textAlign: 'center' }">
<el-table-column prop="periodTime" label="本期时间" align="center" />
<el-table-column :label="'本期能耗(' + unit + ')'" align="center">
<template #default="scope">
{{ scope.row.currentEnergy !== null ? scope.row.currentEnergy : '--' }}
</template>
</el-table-column>
<el-table-column :label="'同期能耗(' + unit + ')'" align="center">
<template #default="scope">
{{ scope.row.samePeriodEnergy !== null ? scope.row.samePeriodEnergy : '--' }}
</template>
</el-table-column>
<el-table-column label="同比(%)" align="center">
<template #default="scope">
<span :class="scope.row.yearOnYear !== null ? (scope.row.yearOnYear > 0 ? 'text-red' : 'text-green') : ''">
{{ scope.row.yearOnYear !== null ? (scope.row.yearOnYear * 100).toFixed(2) + '%' : '--' }}
</span>
</template>
</el-table-column>
</el-table>
</div>
</div>
</template>
</template>
<script>
import * as echarts from 'echarts'
export default {
name: 'YearOnYearAnalysis',
props: {
energyType: { type: String, default: '' },
locationId: { type: String, default: '' },
deviceId: { type: String, default: '' },
unit: { type: String, default: 'Nm3' }, // 能耗单位默认Nm3
energyName: { type: String, default: '天然气' }
},
data() {
return {
year: new Date().getFullYear().toString(), // 默认当前年份
chartType: 'bar', // 默认柱状图
// 统一数据源:表格和图表共用此数据
tableData: Array.from({ length: 12 }, (_, i) => ({
periodTime: `${i + 1}`, // 月份1月-12月
currentEnergy: null, // 本期能耗(当前年份当月)
samePeriodEnergy: null, // 同期能耗(上一年当月)
yearOnYear: null // 同比((本期-同期)/同期)
})),
chartInstance: null // ECharts实例
}
},
mounted() {
this.initChart()
// 窗口大小变化监听
window.addEventListener('resize', this.handleResize)
},
beforeDestroy() {
// 销毁ECharts实例避免内存泄漏
if (this.chartInstance) {
this.chartInstance.dispose()
}
window.removeEventListener('resize', this.handleResize)
},
watch: {
// 图表类型切换时重新绘制
chartType: {
handler: 'drawChart',
immediate: true
}
},
methods: {
// 1. 初始化ECharts实例
initChart() {
this.chartInstance = echarts.init(this.$refs.chartRef)
this.drawChart()
},
// 2. 绘制图表核心从tableData提取数据
drawChart() {
// 从统一数据源tableData提取图表所需数据
const xData = this.tableData.map(item => item.periodTime) // X轴月份
const hasValidData = this.tableData.some(item => item.currentEnergy !== null) // 是否有有效数据
// 处理数据null值转为0避免图表报错
const currentData = this.tableData.map(item => item.currentEnergy ?? 0)
const samePeriodData = this.tableData.map(item => item.samePeriodEnergy ?? 0)
const chartOption = {
// 提示框配置(显示同比信息)
tooltip: {
trigger: 'axis',
axisPointer: { type: this.chartType === 'bar' ? 'shadow' : 'line' },
formatter: (params) => {
const month = params[0].name
const currentItem = this.tableData.find(item => item.periodTime === month)
let tooltipHtml = `<div>${month}</div>`
params.forEach(param => {
const seriesName = param.seriesName
const value = param.value
const percent = currentItem.yearOnYear !== null
? `(同比:${(currentItem.yearOnYear * 100).toFixed(2)}%`
: ''
tooltipHtml += `<div>${seriesName}${value} ${this.unit} ${percent}</div>`
})
return tooltipHtml
}
},
// 图表网格(边距调整)
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
// X轴配置
xAxis: {
type: 'category',
data: xData,
axisLabel: { interval: 0 } // 强制显示所有月份标签
},
// Y轴配置显示能耗单位
yAxis: {
type: 'value',
name: `能耗(${this.unit})`,
nameTextStyle: { marginRight: 10 }
},
// 系列数据(本期+同期)
series: [
{
name: `本期(${this.year}年)`,
type: this.chartType,
data: hasValidData ? currentData : [], // 无数据时传空数组,触发无数据提示
itemStyle: { color: '#409EFF' },
...(this.chartType === 'bar' && { barBorderRadius: [4, 4, 0, 0] }) // 柱状图圆角
},
{
name: `同期(${Number(this.year) - 1}年)`,
type: this.chartType,
data: hasValidData ? samePeriodData : [],
itemStyle: { color: '#C084FC' },
...(this.chartType === 'bar' && { barBorderRadius: [4, 4, 0, 0] })
}
],
// 无数据提示配置
noDataLoadingOption: {
text: '暂无数据,请选择年份并点击查询',
textStyle: { fontSize: 16, color: '#999' },
position: 'center'
}
}
this.chartInstance.setOption(chartOption)
},
// 3. 处理查询核心调用模拟API同步更新tableData
handleQuery() {
// 校验年份必须是4位数字
console.log(this.year)
if (!/^\d{4}$/.test(this.year)) {
this.$message.warning('请输入有效的4位年份如2025')
return
}
// 模拟API请求实际项目替换为axios请求
this.mockGetEnergyData(this.year)
.then(apiData => {
// 同步更新统一数据源:表格和图表将自动使用新数据
this.tableData = apiData
// 重新绘制图表(确保图表使用新数据)
this.drawChart()
this.$message.success(`成功获取${this.year}年能耗数据`)
})
.catch(err => {
this.$message.error(`数据获取失败:${err.message}`)
})
},
// 4. 刷新数据(重新调用查询逻辑)
handleRefresh() {
this.handleQuery()
},
// 5. 窗口大小变化时调整图表尺寸
handleResize() {
this.chartInstance?.resize()
},
// 6. 模拟API根据年份返回能耗数据实际项目替换为后端接口
mockGetEnergyData(year) {
return new Promise((resolve) => {
// 模拟网络延迟800ms
setTimeout(() => {
const currentYear = Number(year)
const lastYear = currentYear - 1
// 生成12个月的模拟数据确保表格和图表数据一致
const mockData = Array.from({ length: 12 }, (_, index) => {
const month = index + 1
const periodTime = `${month}`
// 生成合理的随机能耗(根据年份区分基数,避免数据重复)
const currentEnergy = Math.floor(currentYear * 5 + Math.random() * 100) // 本期能耗
const samePeriodEnergy = Math.floor(lastYear * 5 + Math.random() * 100) // 同期能耗
// 计算同比处理同期为0的异常情况
const yearOnYear = samePeriodEnergy === 0
? (currentEnergy > 0 ? 1 : 0) // 同期为0时本期有值则同比100%
: (currentEnergy - samePeriodEnergy) / samePeriodEnergy
return {
periodTime,
currentEnergy,
samePeriodEnergy,
yearOnYear // 保留小数(表格显示时转为百分比)
}
})
resolve(mockData)
}, 800)
})
},
refresh() {
this.handleQuery()
}
}
}
</script>
<style scoped>
.energy-analysis-container {
padding: 20px;
background-color: #fff;
border-radius: 4px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}
.query-section {
margin-bottom: 20px;
display: flex;
align-items: center;
}
.chart-section {
margin-bottom: 20px;
}
.echarts-box {
width: 100%;
height: 400px;
border: 1px solid #e6e6e6;
border-radius: 4px;
}
/* 图例样式 */
.legend-item {
display: inline-block;
margin-right: 20px;
vertical-align: middle;
font-size: 14px;
color: #666;
}
.legend-dot {
display: inline-block;
width: 12px;
height: 12px;
border-radius: 50%;
margin-right: 5px;
vertical-align: middle;
}
/* 图表操作区(右对齐) */
.chart-operation {
text-align: right;
}
/* 图表类型按钮激活状态 */
.el-button-group .active {
color: #409EFF;
font-weight: 500;
}
/* 表格同比颜色(红色:上升,绿色:下降) */
.text-red {
color: #F56C6C;
}
.text-green {
color: #67C23A;
}
.table-section {
margin-top: 20px;
}
</style>