import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"; import axios from "axios"; import { energyBaseUrl } from "@CON"; import { getTotalElectricByBaja, getCurPower } from "@UTIL"; const getElecMeter = (ordPath, dispatch) => { const date = new Date(); // 取得昨日及今日電錶總量 getTotalElectricByBaja(ordPath, date, "daily", dispatch); // 取得昨日及今日電錶總量比較(長條圖用) getTotalElectricByBaja(ordPath, date, "hourly", dispatch); // 取得本週/上週用電量比較(長條圖用) getTotalElectricByBaja(ordPath, date, "weekly", dispatch); }; export const fetchInitElecMeterByBaja = createAsyncThunk( "electricity/fetchInitElecMeterByBaja", async (token = "", { fulfillWithValue, rejectWithValue, dispatch }) => { const res = await axios.post(energyBaseUrl); const { code = 9999, msg, data = null } = res; if (code !== "0000" || !data) { return rejectWithValue(msg); } else { // 取得總電錶 const total = res.data.find((d) => d.mainSubTag === "total"); // 訂閱 "TPE_B1_EE_E4_R2F_NA_WHT_N1" ==> 總電錶 getElecMeter(`${total.system_device_tag}_KWH`, dispatch); //"TPE_B1_EE_E4_R2F_NA_WHT_N1_KWH" const ordPath = total?.system_device_tag.replaceAll("_", "/"); getCurPower(ordPath, dispatch); // "TPE/B1/EE/E4/R2F/NA/WHT/N1" const timer = window.setInterval(async () => { await getElecMeter(ordPath, dispatch); }, 3600000); return fulfillWithValue(timer); } }, ); const electricitySlice = createSlice({ name: "electricity", initialState: { timer: [], electricMeter: [{ text: "", data: 0 }], hourElectricMeter: { current: [], last: [] }, weekElectricMeter: { current: [], last: [] }, curElectricity: [ { data: "", text: "即時功率 " }, { data: "", text: "即時契約容量占比 " }, ], }, reducers: { getElectricMeter: (state, { payload }) => { state.electricMeter = payload; }, getHourElectricMeter: (state, { payload }) => { state.hourElectricMeter = payload; }, getWeekElectricMeter: (state, { payload }) => { state.weekElectricMeter = payload; }, getCurElectricity: (state, { payload }) => { state.curElectricity = payload; }, }, extraReducers: (builder) => { builder.addCase(fetchInitElecMeterByBaja.fulfilled, (state, { payload }) => { state.timer = [...state.timer, payload]; }); }, }); const { reducer, actions } = electricitySlice; export const { getElectricMeter, getHourElectricMeter, getWeekElectricMeter, getCurElectricity } = actions; export default reducer;