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

@@ -0,0 +1,44 @@
import request from '@/utils/request'
// 查询安全警报设备列表
export function listAlarmDevice(query) {
return request({
url: '/ems/alarmDevice/list',
method: 'get',
params: query
})
}
// 查询安全警报设备详细
export function getAlarmDevice(deviceId) {
return request({
url: '/ems/alarmDevice/' + deviceId,
method: 'get'
})
}
// 新增安全警报设备
export function addAlarmDevice(data) {
return request({
url: '/ems/alarmDevice',
method: 'post',
data: data
})
}
// 修改安全警报设备
export function updateAlarmDevice(data) {
return request({
url: '/ems/alarmDevice',
method: 'put',
data: data
})
}
// 删除安全警报设备
export function delAlarmDevice(deviceId) {
return request({
url: '/ems/alarmDevice/' + deviceId,
method: 'delete'
})
}

View File

@@ -0,0 +1,44 @@
import request from '@/utils/request'
// 查询警报记录列表
export function listAlarmRecord(query) {
return request({
url: '/ems/alarmRecord/list',
method: 'get',
params: query
})
}
// 查询警报记录详细
export function getAlarmRecord(recordId) {
return request({
url: '/ems/alarmRecord/' + recordId,
method: 'get'
})
}
// 新增警报记录
export function addAlarmRecord(data) {
return request({
url: '/ems/alarmRecord',
method: 'post',
data: data
})
}
// 修改警报记录
export function updateAlarmRecord(data) {
return request({
url: '/ems/alarmRecord',
method: 'put',
data: data
})
}
// 删除警报记录
export function delAlarmRecord(recordId) {
return request({
url: '/ems/alarmRecord/' + recordId,
method: 'delete'
})
}

View File

@@ -0,0 +1,382 @@
<template>
<div class="app-container">
<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<el-form-item label="设备名称" prop="deviceName">
<el-input
v-model="queryParams.deviceName"
placeholder="请输入设备名称"
clearable
@keyup.enter.native="handleQuery"
/>
</el-form-item>
<el-form-item label="设备编码" prop="deviceCode">
<el-input
v-model="queryParams.deviceCode"
placeholder="请输入设备编码"
clearable
@keyup.enter.native="handleQuery"
/>
</el-form-item>
<el-form-item label="设备类型" prop="deviceType">
<el-select v-model="queryParams.deviceType" placeholder="请选择设备类型" clearable>
<el-option
v-for="dict in dict.type.alarm_device_type"
:key="dict.value"
:label="dict.label"
:value="dict.value"
/>
</el-select>
</el-form-item>
<el-form-item label="设备状态" prop="status">
<el-select v-model="queryParams.status" placeholder="请选择设备状态" clearable>
<el-option
v-for="dict in dict.type.alarm_devide_status"
:key="dict.value"
:label="dict.label"
:value="dict.value"
/>
</el-select>
</el-form-item>
<el-form-item label="IP地址" prop="ipAddress">
<el-input
v-model="queryParams.ipAddress"
placeholder="请输入设备IP地址"
clearable
@keyup.enter.native="handleQuery"
/>
</el-form-item>
<el-form-item label="固件版本" prop="firmwareVer">
<el-input
v-model="queryParams.firmwareVer"
placeholder="请输入固件版本"
clearable
@keyup.enter.native="handleQuery"
/>
</el-form-item>
<el-form-item>
<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
</el-form-item>
</el-form>
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button
type="primary"
plain
icon="el-icon-plus"
size="mini"
@click="handleAdd"
>新增</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="success"
plain
icon="el-icon-edit"
size="mini"
:disabled="single"
@click="handleUpdate"
>修改</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="danger"
plain
icon="el-icon-delete"
size="mini"
:disabled="multiple"
@click="handleDelete"
>删除</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="warning"
plain
icon="el-icon-download"
size="mini"
@click="handleExport"
>导出</el-button>
</el-col>
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
</el-row>
<el-table v-loading="loading" :data="alarmDeviceList" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="" align="center" prop="deviceId" v-if="false"/>
<el-table-column label="设备名称" align="center" prop="deviceName" />
<el-table-column label="设备编码" align="center" prop="deviceCode" />
<el-table-column label="设备类型" align="center" prop="deviceType">
<template slot-scope="scope">
<dict-tag :options="dict.type.alarm_device_type" :value="scope.row.deviceType"/>
</template>
</el-table-column>
<el-table-column label="安装位置" align="center" prop="locationName"></el-table-column>
<el-table-column label="设备状态" align="center" prop="status">
<template slot-scope="scope">
<dict-tag :options="dict.type.alarm_devide_status" :value="scope.row.status"/>
</template>
</el-table-column>
<el-table-column label="设备IP地址" align="center" prop="ipAddress" />
<el-table-column label="固件版本" align="center" prop="firmwareVer" />
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template slot-scope="scope">
<el-button
size="mini"
type="text"
icon="el-icon-edit"
@click="handleUpdate(scope.row)"
>修改</el-button>
<el-button
size="mini"
type="text"
icon="el-icon-delete"
@click="handleDelete(scope.row)"
>删除</el-button>
</template>
</el-table-column>
</el-table>
<pagination
v-show="total>0"
:total="total"
:page.sync="queryParams.pageNum"
:limit.sync="queryParams.pageSize"
@pagination="getList"
/>
<!-- 添加或修改安全警报设备对话框 -->
<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
<el-form ref="form" :model="form" :rules="rules" label-width="80px">
<el-form-item label="设备名称" prop="deviceName">
<el-input v-model="form.deviceName" placeholder="请输入设备名称" />
</el-form-item>
<el-form-item label="设备编码" prop="deviceCode">
<el-input v-model="form.deviceCode" placeholder="请输入设备编码" />
</el-form-item>
<el-form-item label="设备类型" prop="deviceType">
<el-select v-model="form.deviceType" placeholder="请选择设备类型">
<el-option
v-for="dict in dict.type.alarm_device_type"
:key="dict.value"
:label="dict.label"
:value="dict.value"
></el-option>
</el-select>
</el-form-item>
<el-form-item label="安装位置" prop="locationId">
<el-select v-model="form.locationId" placeholder="请选择安装位置">
<el-option
v-for="item in locationList"
:key="item.locationId"
:label="item.name"
:value="item.locationId"
></el-option>
</el-select>
</el-form-item>
<el-form-item label="设备状态" prop="status">
<el-select v-model="form.status" placeholder="请选择设备状态">
<el-option
v-for="dict in dict.type.alarm_device_status"
:key="dict.value"
:label="dict.label"
:value="parseInt(dict.value)"
></el-option>
</el-select>
</el-form-item>
<el-form-item label="设备IP地址" prop="ipAddress">
<el-input v-model="form.ipAddress" placeholder="请输入设备IP地址" />
</el-form-item>
<el-form-item label="固件版本" prop="firmwareVer">
<el-input v-model="form.firmwareVer" placeholder="请输入固件版本" />
</el-form-item>
<el-form-item label="备注" prop="remark">
<el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button :loading="buttonLoading" type="primary" @click="submitForm"> </el-button>
<el-button @click="cancel"> </el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import { listAlarmDevice, getAlarmDevice, delAlarmDevice, addAlarmDevice, updateAlarmDevice } from "@/api/ems/alarmDevice";
import { listLocation } from "@/api/ems/location";
export default {
name: "AlarmDevice",
dicts: ['alarm_device_type', 'alarm_device_status'],
data() {
return {
// 按钮loading
buttonLoading: false,
// 遮罩层
loading: true,
// 选中数组
ids: [],
// 非单个禁用
single: true,
// 非多个禁用
multiple: true,
// 显示搜索条件
showSearch: true,
// 总条数
total: 0,
// 安全警报设备表格数据
alarmDeviceList: [],
// 弹出层标题
title: "",
// 是否显示弹出层
open: false,
// 查询参数
queryParams: {
pageNum: 1,
pageSize: 10,
deviceName: undefined,
deviceCode: undefined,
deviceType: undefined,
status: undefined,
ipAddress: undefined,
firmwareVer: undefined,
},
// 表单参数
form: {},
// 表单校验
rules: {
createTime: [
{ required: true, message: "创建时间不能为空", trigger: "blur" }
],
},
locationList: []
};
},
created() {
this.getList();
this.getLocationList();
},
methods: {
getLocationList() {
listLocation().then(response => {
this.locationList = response.data;
});
},
/** 查询安全警报设备列表 */
getList() {
this.loading = true;
listAlarmDevice(this.queryParams).then(response => {
this.alarmDeviceList = response.rows;
this.total = response.total;
this.loading = false;
});
},
// 取消按钮
cancel() {
this.open = false;
this.reset();
},
// 表单重置
reset() {
this.form = {
deviceId: undefined,
deviceName: undefined,
deviceCode: undefined,
deviceType: undefined,
locationId: undefined,
status: undefined,
ipAddress: undefined,
firmwareVer: undefined,
createBy: undefined,
updateBy: undefined,
createTime: undefined,
updateTime: undefined,
delFlag: undefined,
remark: undefined
};
this.resetForm("form");
},
/** 搜索按钮操作 */
handleQuery() {
this.queryParams.pageNum = 1;
this.getList();
},
/** 重置按钮操作 */
resetQuery() {
this.resetForm("queryForm");
this.handleQuery();
},
// 多选框选中数据
handleSelectionChange(selection) {
this.ids = selection.map(item => item.deviceId)
this.single = selection.length!==1
this.multiple = !selection.length
},
/** 新增按钮操作 */
handleAdd() {
this.reset();
this.open = true;
this.title = "添加安全警报设备";
},
/** 修改按钮操作 */
handleUpdate(row) {
this.loading = true;
this.reset();
const deviceId = row.deviceId || this.ids
getAlarmDevice(deviceId).then(response => {
this.loading = false;
this.form = response.data;
this.open = true;
this.title = "修改安全警报设备";
});
},
/** 提交按钮 */
submitForm() {
this.$refs["form"].validate(valid => {
if (valid) {
this.buttonLoading = true;
if (this.form.deviceId != null) {
updateAlarmDevice(this.form).then(response => {
this.$modal.msgSuccess("修改成功");
this.open = false;
this.getList();
}).finally(() => {
this.buttonLoading = false;
});
} else {
addAlarmDevice(this.form).then(response => {
this.$modal.msgSuccess("新增成功");
this.open = false;
this.getList();
}).finally(() => {
this.buttonLoading = false;
});
}
}
});
},
/** 删除按钮操作 */
handleDelete(row) {
const deviceIds = row.deviceId || this.ids;
this.$modal.confirm('是否确认删除安全警报设备编号为"' + deviceIds + '"的数据项?').then(() => {
this.loading = true;
return delAlarmDevice(deviceIds);
}).then(() => {
this.loading = false;
this.getList();
this.$modal.msgSuccess("删除成功");
}).catch(() => {
}).finally(() => {
this.loading = false;
});
},
/** 导出按钮操作 */
handleExport() {
this.download('ems/alarmDevice/export', {
...this.queryParams
}, `alarmDevice_${new Date().getTime()}.xlsx`)
}
}
};
</script>

View File

@@ -0,0 +1,388 @@
<template>
<div class="app-container">
<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<el-form-item label="警报类型" prop="alarmType">
<el-select v-model="queryParams.alarmType" placeholder="请选择警报类型" clearable>
<el-option
v-for="dict in dict.type.alarm_record_type"
:key="dict.value"
:label="dict.label"
:value="dict.value"
/>
</el-select>
</el-form-item>
<el-form-item label="警报级别" prop="alarmLevel">
<el-select v-model="queryParams.alarmLevel" placeholder="请选择警报级别" clearable>
<el-option
v-for="dict in dict.type.alarm_record_level"
:key="dict.value"
:label="dict.label"
:value="dict.value"
/>
</el-select>
</el-form-item>
<el-form-item label="处理人" prop="handleUser">
<el-input
v-model="queryParams.handleUser"
placeholder="请输入处理人"
clearable
@keyup.enter.native="handleQuery"
/>
</el-form-item>
<el-form-item>
<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
</el-form-item>
</el-form>
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button
type="primary"
plain
icon="el-icon-plus"
size="mini"
@click="handleAdd"
>新增</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="success"
plain
icon="el-icon-edit"
size="mini"
:disabled="single"
@click="handleUpdate"
>修改</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="danger"
plain
icon="el-icon-delete"
size="mini"
:disabled="multiple"
@click="handleDelete"
>删除</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="warning"
plain
icon="el-icon-download"
size="mini"
@click="handleExport"
>导出</el-button>
</el-col>
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
</el-row>
<el-table v-loading="loading" :data="alarmRecordList" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="告警设备" align="center" prop="deviceName" />
<el-table-column label="警报类型" align="center" prop="alarmType">
<template slot-scope="scope">
<dict-tag :options="dict.type.alarm_record_type" :value="scope.row.alarmType"/>
</template>
</el-table-column>
<el-table-column label="警报级别" align="center" prop="alarmLevel">
<template slot-scope="scope">
<dict-tag :options="dict.type.alarm_record_level" :value="scope.row.alarmLevel"/>
</template>
</el-table-column>
<el-table-column label="警报内容" align="center" prop="alarmContent">
<template slot-scope="scope">
<div v-html="scope.row.alarmContent"></div>
</template>
</el-table-column>
<el-table-column label="发生时间" align="center" prop="alarmTime" width="180">
<template slot-scope="scope">
<span>{{ parseTime(scope.row.alarmTime, '{y}-{m}-{d}') }}</span>
</template>
</el-table-column>
<el-table-column label="处理状态" align="center" prop="handleStatus" />
<el-table-column label="处理人" align="center" prop="handleUser" />
<el-table-column label="处理时间" align="center" prop="handleTime" width="180">
<template slot-scope="scope">
<span>{{ parseTime(scope.row.handleTime, '{y}-{m}-{d}') }}</span>
</template>
</el-table-column>
<el-table-column label="处理备注" align="center" prop="handleNotes" />
<el-table-column label="备注" align="center" prop="remark" />
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template slot-scope="scope">
<el-button
size="mini"
type="text"
icon="el-icon-edit"
@click="handleUpdate(scope.row)"
>修改</el-button>
<el-button
size="mini"
type="text"
icon="el-icon-delete"
@click="handleDelete(scope.row)"
>删除</el-button>
</template>
</el-table-column>
</el-table>
<pagination
v-show="total>0"
:total="total"
:page.sync="queryParams.pageNum"
:limit.sync="queryParams.pageSize"
@pagination="getList"
/>
<!-- 添加或修改警报记录对话框 -->
<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
<el-form ref="form" :model="form" :rules="rules" label-width="80px">
<el-form-item label="告警设备" prop="deviceId">
<el-select v-model="form.deviceId" placeholder="请选择告警设备">
<el-option
v-for="item in alarmDeviceList"
:key="item.deviceId"
:label="item.deviceName"
:value="item.deviceId"
></el-option>
</el-select>
</el-form-item>
<el-form-item label="警报类型" prop="alarmType">
<el-select v-model="form.alarmType" placeholder="请选择警报类型">
<el-option
v-for="dict in dict.type.alarm_record_type"
:key="dict.value"
:label="dict.label"
:value="dict.value"
></el-option>
</el-select>
</el-form-item>
<el-form-item label="警报级别" prop="alarmLevel">
<el-select v-model="form.alarmLevel" placeholder="请选择警报级别">
<el-option
v-for="dict in dict.type.alarm_record_level"
:key="dict.value"
:label="dict.label"
:value="parseInt(dict.value)"
></el-option>
</el-select>
</el-form-item>
<el-form-item label="警报内容">
<editor v-model="form.alarmContent" :min-height="192"/>
</el-form-item>
<el-form-item label="发生时间" prop="alarmTime">
<el-date-picker clearable
v-model="form.alarmTime"
type="datetime"
value-format="yyyy-MM-dd HH:mm:ss"
placeholder="请选择警报发生时间">
</el-date-picker>
</el-form-item>
<el-form-item label="处理人" prop="handleUser">
<el-input v-model="form.handleUser" placeholder="请输入处理人" />
</el-form-item>
<el-form-item label="处理时间" prop="handleTime">
<el-date-picker clearable
v-model="form.handleTime"
type="datetime"
value-format="yyyy-MM-dd HH:mm:ss"
placeholder="请选择处理时间">
</el-date-picker>
</el-form-item>
<el-form-item label="处理备注" prop="handleNotes">
<el-input v-model="form.handleNotes" type="textarea" placeholder="请输入内容" />
</el-form-item>
<el-form-item label="备注" prop="remark">
<el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button :loading="buttonLoading" type="primary" @click="submitForm"> </el-button>
<el-button @click="cancel"> </el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import { listAlarmRecord, getAlarmRecord, delAlarmRecord, addAlarmRecord, updateAlarmRecord } from "@/api/ems/alarmRecord";
import { listAlarmDevice } from "@/api/ems/alarmDevice";
export default {
name: "AlarmRecord",
dicts: ['alarm_record_type', 'alarm_record_level'],
data() {
return {
// 按钮loading
buttonLoading: false,
// 遮罩层
loading: true,
// 选中数组
ids: [],
// 非单个禁用
single: true,
// 非多个禁用
multiple: true,
// 显示搜索条件
showSearch: true,
// 总条数
total: 0,
// 警报记录表格数据
alarmRecordList: [],
// 告警设备列表
alarmDeviceList: [],
// 弹出层标题
title: "",
// 是否显示弹出层
open: false,
// 查询参数
queryParams: {
pageNum: 1,
pageSize: 10,
deviceId: undefined,
alarmType: undefined,
alarmLevel: undefined,
alarmContent: undefined,
alarmTime: undefined,
handleStatus: undefined,
handleUser: undefined,
handleTime: undefined,
handleNotes: undefined,
},
// 表单参数
form: {},
// 表单校验
rules: {
}
};
},
created() {
this.getList();
this.getAlarmDeviceList();
},
methods: {
getAlarmDeviceList() {
listAlarmDevice({ pageNum: 1, pageSize: 1000 }).then(response => {
this.alarmDeviceList = response.rows;
});
},
/** 查询警报记录列表 */
getList() {
this.loading = true;
listAlarmRecord(this.queryParams).then(response => {
this.alarmRecordList = response.rows;
this.total = response.total;
this.loading = false;
});
},
// 取消按钮
cancel() {
this.open = false;
this.reset();
},
// 表单重置
reset() {
this.form = {
recordId: undefined,
deviceId: undefined,
alarmType: undefined,
alarmLevel: undefined,
alarmContent: undefined,
alarmTime: undefined,
handleStatus: undefined,
handleUser: undefined,
handleTime: undefined,
handleNotes: undefined,
createBy: undefined,
updateBy: undefined,
createTime: undefined,
updateTime: undefined,
delFlag: undefined,
remark: undefined
};
this.resetForm("form");
},
/** 搜索按钮操作 */
handleQuery() {
this.queryParams.pageNum = 1;
this.getList();
},
/** 重置按钮操作 */
resetQuery() {
this.resetForm("queryForm");
this.handleQuery();
},
// 多选框选中数据
handleSelectionChange(selection) {
this.ids = selection.map(item => item.recordId)
this.single = selection.length!==1
this.multiple = !selection.length
},
/** 新增按钮操作 */
handleAdd() {
this.reset();
this.open = true;
this.title = "添加警报记录";
},
/** 修改按钮操作 */
handleUpdate(row) {
this.loading = true;
this.reset();
const recordId = row.recordId || this.ids
getAlarmRecord(recordId).then(response => {
this.loading = false;
this.form = response.data;
this.open = true;
this.title = "修改警报记录";
});
},
/** 提交按钮 */
submitForm() {
this.$refs["form"].validate(valid => {
if (valid) {
this.buttonLoading = true;
if (this.form.recordId != null) {
updateAlarmRecord(this.form).then(response => {
this.$modal.msgSuccess("修改成功");
this.open = false;
this.getList();
}).finally(() => {
this.buttonLoading = false;
});
} else {
addAlarmRecord(this.form).then(response => {
this.$modal.msgSuccess("新增成功");
this.open = false;
this.getList();
}).finally(() => {
this.buttonLoading = false;
});
}
}
});
},
/** 删除按钮操作 */
handleDelete(row) {
const recordIds = row.recordId || this.ids;
this.$modal.confirm('是否确认删除警报记录编号为"' + recordIds + '"的数据项?').then(() => {
this.loading = true;
return delAlarmRecord(recordIds);
}).then(() => {
this.loading = false;
this.getList();
this.$modal.msgSuccess("删除成功");
}).catch(() => {
}).finally(() => {
this.loading = false;
});
},
/** 导出按钮操作 */
handleExport() {
this.download('ems/alarmRecord/export', {
...this.queryParams
}, `alarmRecord_${new Date().getTime()}.xlsx`)
}
}
};
</script>

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>

View File

@@ -216,7 +216,7 @@ $--metal-gradient-light: linear-gradient(145deg, #f5f5f5, #fff);
.login-form {
.el-input {
input {
height: 40px;
height: 40px !important;
color: $--color-text-primary; // 白色文字
background: transparent;
}