CviLux_fe/src/views/energyManagement/components/ElecConsumption.vue

111 lines
2.4 KiB
Vue

<script setup>
import { ref, onMounted, nextTick, computed } from "vue";
import * as echarts from "echarts";
import { getRealTimeDist } from "@/apis/energy";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const chartDiv = ref(null);
const chartOption = {
tooltip: {
trigger: "item",
formatter: (p) => {
return `${p.name}: ${p.value}kWh (${p.data.percentage}%)`;
},
},
series: [
{
type: "sankey",
layout: "none",
nodeWidth: 10,
nodeGap: 10,
right: 180,
data: [],
links: [],
emphasis: {
focus: "adjacency",
},
label: {
position: "right",
fontSize: 14,
color: "#fff",
formatter: (p) => {
return `${p.name} (${p.data.percentage}%)`;
},
},
itemStyle: {
borderWidth: 0,
},
lineStyle: {
color: "target",
opacity: 0.7,
curveness: 0.5,
},
},
],
};
const loadData = async () => {
const res = await getRealTimeDist();
if (res.isSuccess) {
const rawData = res.data;
const totalValue = rawData.reduce((acc, item) => acc + item.value, 0);
// 構造 data 節點
const data = [
{ name: "Total", value: totalValue, percentage: 100 },
...rawData.map((item) => ({
name: item.key,
value: item.value,
percentage: item.percentage,
})),
];
// 構造 links 連結
const links = rawData.map((item) => ({
source: "Total",
target: item.key,
value: item.value,
percentage: item.percentage,
}));
// 更新 chartOption
chartOption.series[0].data = data;
chartOption.series[0].links = links;
// 初始化圖表
const myChart = echarts.init(chartDiv.value);
myChart.setOption(chartOption);
}
};
onMounted(() => {
loadData();
});
</script>
<template>
<div class="p-3">
<h2 class="text text-lg text-white mb-5 relative">
{{ $t("energy.elec_consumption") }}
</h2>
<div class="chart-container">
<div ref="chartDiv" class="w-full min-h-[200px] h-full"></div>
</div>
</div>
</template>
<style lang="scss" scoped>
.text::after {
@apply absolute -bottom-2.5 left-0 block w-3/5 h-[1px] bg-slate-600;
content: "";
}
ul li:last-child:after {
@apply absolute top-0 bottom-0 left-full block w-full h-[1px] bg-slate-600 m-auto z-10;
content: "";
}
</style>