基础设置 内容接入保存接口 ,再登录界面 就调用 接口 显示 默认 的 保存设置

This commit is contained in:
mmc
2026-10-12 15:16:43 +08:00
parent e00eda0709
commit 5d8b9559d0
5 changed files with 156 additions and 39 deletions

View File

@@ -8,6 +8,10 @@ import utils from './lib/utils';
import { useTranslation } from 'react-i18next';
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n';
import { useEffect } from 'react';
import { useAppDispatch } from './store';
import { setSettingField, setGlobalParams } from './store/basicSettingsSlice';
import { getSystemParam } from './api/global';
// 用于静态注入 message/modal/notification
const StaticAntd = () => {
@@ -50,6 +54,28 @@ const AntdConfigWrapper = ({ children }: { children: React.ReactNode }) => {
};
export default function App() {
const dispatch = useAppDispatch();
useEffect(() => {
getSystemParam()
.then((res: any) => {
if (res?.code === 200 && res?.data?.global) {
const globalArr = res.data.global;
// 存储完整数组,保存时基于此结构更新 paramValue
dispatch(setGlobalParams(globalArr));
// 同时提取 systemName 用于登录页和平台头部显示
const systemNameItem = globalArr.find((item: any) => item.paramKey === 'systemName');
if (systemNameItem?.paramValue) {
dispatch(setSettingField({ systemName: systemNameItem.paramValue }));
}
console.log('[System] global config loaded:', globalArr);
}
})
.catch((err: any) => {
console.error('[System] Failed to load global config:', err);
});
}, [dispatch]);
return (
<I18nextProvider i18n={i18n}>
<AntdConfigWrapper>

18
src/api/global.ts Normal file
View File

@@ -0,0 +1,18 @@
import request from './request';
//新增物模型
export function getSystemParam() {
return request({
url: '/system/param/list',
method: 'get',
});
}
//保存系统参数
export function saveSystemParam(data: any[]) {
return request({
url: '/system/param/save',
method: 'post',
data,
});
}

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect } from 'react';
import {
Form,
Input,
@@ -61,6 +61,7 @@ import {
import dayjs from 'dayjs';
import { useTranslation } from 'react-i18next';
import { getRoleList } from '@/api/role';
import { saveSystemParam } from '@/api/global';
import { useSelector } from 'react-redux';
import { RootState } from '@/src/store';
import { getUser } from '@/api/user';
@@ -87,8 +88,23 @@ const BasicSettings = () => {
const [userPage, setUserPage] = useState(1);
const [rolePage, setRolePage] = useState(1);
const [devicePage, setDevicePage] = useState(1);
// 本地临时状态,保存时才 dispatch
const [localLocale, setLocalLocale] = useState(locale);
const [localTimezone, setLocalTimezone] = useState(timezone);
const [localUnitSystem, setLocalUnitSystem] = useState(unitSystem);
const [localDateFormat, setLocalDateFormat] = useState(dateFormat);
// Redux 值变化时同步到本地(如保存后、重置后)
useEffect(() => {
setLocalLocale(locale);
setLocalTimezone(timezone);
setLocalUnitSystem(unitSystem);
setLocalDateFormat(dateFormat);
}, [locale, timezone, unitSystem, dateFormat]);
const tzOptions = getTimezoneOptions();
const dstActive = isDST(timezone);
const dstActive = isDST(localTimezone);
// 响应式字体大小
const fontNormal = 'clamp(12px, 0.75vw, 13px)';
@@ -97,26 +113,73 @@ const BasicSettings = () => {
const fontLarge = 'clamp(18px, 1.1vw, 22px)';
const handleSave = () => {
const systemName = form.getFieldValue('systemName') || basicSettings.systemName;
const defaultSite = form.getFieldValue('defaultSite') || basicSettings.defaultSite;
dispatch(saveAllSettings({
systemName: form.getFieldValue('systemName') || basicSettings.systemName,
defaultSite,
defaultPage: form.getFieldValue('defaultPage') || basicSettings.defaultPage,
refreshRate: form.getFieldValue('refreshRate') || basicSettings.refreshRate,
}));
// 查找默认场站名称
let defaultStationName = '';
if (defaultSite && stationList && stationList.length > 0) {
const target = stationList.find((s: any) => s.id === defaultSite);
if (target) {
dispatch(setCurrentStation(target));
defaultStationName = target.siteName || target.name || '';
}
}
if (defaultSite && stationList && stationList.length > 0) {
const target = stationList.find((s: any) => s.id === defaultSite);
if (target) {
dispatch(setCurrentStation(target));
// 基于 getSystemParam 返回的完整数组结构,只更新 paramValue
const paramsToSave = (basicSettings.globalParams || []).map((item: any) => {
const updated = { ...item };
switch (item.paramKey) {
case 'systemName':
updated.paramValue = systemName;
break;
case 'defaultStationName':
updated.paramValue = defaultStationName;
break;
case 'defaultLanguage':
updated.paramValue = localLocale === 'en' ? 'en_US' : 'zh_CN';
break;
case 'defaultZoneId':
updated.paramValue = localTimezone;
break;
case 'defaultUnit':
updated.paramValue = localUnitSystem === 'imperial' ? '英制' : '公制';
break;
case 'defaultDateFormat':
updated.paramValue = localDateFormat;
break;
}
}
utils.message.success(t('systemSetting.fixed2SettingsSaveFixed2'));
return updated;
});
saveSystemParam(paramsToSave).then((res: any) => {
if (res.code === 200) {
// 同步到 Redux/localStorage
dispatch(saveAllSettings({
systemName,
defaultSite,
defaultPage: form.getFieldValue('defaultPage') || basicSettings.defaultPage,
refreshRate: form.getFieldValue('refreshRate') || basicSettings.refreshRate,
}));
// 同步偏好设置
dispatch(setLocale(localLocale));
i18n.changeLanguage(localLocale);
dispatch(setTimezone(localTimezone));
dispatch(setUnitSystem(localUnitSystem));
dispatch(setDateFormat(localDateFormat));
// 同步默认场站
if (defaultSite && stationList && stationList.length > 0) {
const target = stationList.find((s: any) => s.id === defaultSite);
if (target) {
dispatch(setCurrentStation(target));
}
}
utils.message.success(t('systemSetting.fixed2SettingsSaveFixed2'));
} else {
utils.message.error(res.msg || t('common.saveFailed'));
}
}).catch((err: any) => {
utils.message.error(err?.message || t('common.saveFailed'));
});
};
// 顶部统计卡片数据
@@ -319,15 +382,15 @@ const BasicSettings = () => {
<Row gutter={16}>
<Col xs={24} sm={12} md={8}>
<Form.Item label={t('systemSetting.systemName')} name="systemName" style={{ marginBottom: 12 }}>
<Input size="small" value={basicSettings.systemName} />
<Input size="small" />
</Form.Item>
</Col>
<Col xs={24} sm={12} md={8}>
<Form.Item label={t('systemSetting.fixed2Default2')} name="defaultSite" style={{ marginBottom: 12 }}>
<Select size="small" value={basicSettings.defaultSite} onChange={(v) => dispatch(saveAllSettings({ defaultSite: v }))}>
<Select size="small">
{(stationList || []).slice().sort((a, b) => (a.id || 0) - (b.id || 0)).map((s, idx) => (
<Select.Option key={s.id} value={s.id}>
{idx + 1}. {s.siteName || s.name || s.id}
{s.siteName || s.name || s.id}
</Select.Option>
))}
</Select>
@@ -335,7 +398,7 @@ const BasicSettings = () => {
</Col>
<Col xs={24} sm={12} md={8}>
<Form.Item label={t('systemSetting.defaultLanguage')} style={{ marginBottom: 12 }}>
<Select size="small" value={locale} onChange={(v) => { dispatch(setLocale(v)); i18n.changeLanguage(v); }}>
<Select size="small" value={localLocale} onChange={(v) => setLocalLocale(v)}>
<Select.Option value="zh">{t('users.chinese')}</Select.Option>
<Select.Option value="en">English</Select.Option>
</Select>
@@ -343,7 +406,7 @@ const BasicSettings = () => {
</Col>
<Col xs={24} sm={12} md={8}>
<Form.Item label={t('systemSetting.timezoneSelect')} style={{ marginBottom: 12 }}>
<Select size="small" value={timezone} onChange={(v) => dispatch(setTimezone(v))} showSearch optionFilterProp="label">
<Select size="small" value={localTimezone} onChange={(v) => setLocalTimezone(v)} showSearch optionFilterProp="label">
{tzOptions.map(opt => <Select.Option key={opt.value} value={opt.value}>{opt.label}</Select.Option>)}
</Select>
</Form.Item>
@@ -351,13 +414,13 @@ const BasicSettings = () => {
<Col xs={24} sm={12} md={8}>
<Form.Item label={t('systemSetting.daylightSavingTime')} style={{ marginBottom: 12 }}>
<Tag color={dstActive ? 'green' : 'default'}>
{dstActive ? t('systemSetting.dstActive') : t('systemSetting.dstInactive')} ({getTimezoneOffsetLabel(timezone)})
{dstActive ? t('systemSetting.dstActive') : t('systemSetting.dstInactive')} ({getTimezoneOffsetLabel(localTimezone)})
</Tag>
</Form.Item>
</Col>
<Col xs={24} sm={12} md={8}>
<Form.Item label={t('systemSetting.unitSystem')} style={{ marginBottom: 12 }}>
<Radio.Group size="small" value={unitSystem} onChange={(e) => dispatch(setUnitSystem(e.target.value))}>
<Radio.Group size="small" value={localUnitSystem} onChange={(e) => setLocalUnitSystem(e.target.value)}>
<Radio value="metric" style={{ fontSize: fontSmall }}>{t('systemSetting.metric')}</Radio>
<Radio value="imperial" style={{ fontSize: fontSmall }}>{t('systemSetting.imperial')}</Radio>
</Radio.Group>
@@ -365,7 +428,7 @@ const BasicSettings = () => {
</Col>
<Col xs={24} sm={12} md={8}>
<Form.Item label={t('systemSetting.dateFormat')} style={{ marginBottom: 12 }}>
<Select size="small" value={dateFormat} onChange={(v) => dispatch(setDateFormat(v))}>
<Select size="small" value={localDateFormat} onChange={(v) => setLocalDateFormat(v)}>
<Select.Option value="YYYY-MM-DD HH:mm:ss">YYYY-MM-DD HH:mm:ss</Select.Option>
<Select.Option value="YYYY-MM-DD HH:mm">YYYY-MM-DD HH:mm</Select.Option>
<Select.Option value="MM/DD/YYYY HH:mm:ss">MM/DD/YYYY HH:mm:ss</Select.Option>
@@ -401,18 +464,19 @@ const BasicSettings = () => {
<div style={{ marginTop: 12 }}>
<Button type="primary" size="small" onClick={handleSave} style={{ width: 100, borderRadius: 6 }}>{t('systemSetting.fixed2SaveFixed2SettingsFixed2')}</Button>
<Button size="small" style={{ marginLeft: 8, borderRadius: 6 }} onClick={() => {
dispatch(resetBasicSettings());
dispatch(setLocale('zh'));
i18n.changeLanguage('zh');
dispatch(setTimezone('Asia/Shanghai'));
dispatch(setUnitSystem('metric'));
dispatch(setDateFormat('YYYY-MM-DD HH:mm:ss'));
if (stationList && stationList.length > 0) {
const sorted = [...stationList].sort((a, b) => (a.id || 0) - (b.id || 0));
const first = sorted[0];
dispatch(saveAllSettings({ defaultSite: first.id }));
dispatch(setCurrentStation(first));
}
// 只重置本地视图,不 dispatch;需点击保存才会生效
form.setFieldsValue({
systemName: '光伏机器人环境感知服务平台',
defaultSite: stationList && stationList.length > 0
? [...stationList].sort((a, b) => (a.id || 0) - (b.id || 0))[0]?.id
: '',
defaultPage: 'dashboard',
refreshRate: '5min',
});
setLocalLocale('zh');
setLocalTimezone('Asia/Shanghai');
setLocalUnitSystem('metric');
setLocalDateFormat('YYYY-MM-DD HH:mm:ss');
}}>{t('systemSetting.fixed2ResumeFixed2DefaultFixed2')}</Button>
</div>
</Form>

View File

@@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
Form,
@@ -17,7 +17,8 @@ import { motion } from 'motion/react';
import bgcImg from '../assets/bgc2.png';
import logincard from '../assets/logincard.png';
import { userLogin } from '../store/userSlice';
import { useAppDispatch } from '../store';
import { useSelector } from 'react-redux';
import { useAppDispatch, RootState } from '../store';
import Cookies from 'js-cookie';
import { useTranslation } from 'react-i18next';
@@ -31,6 +32,7 @@ export default function Login() {
const { message } = App.useApp();
// 登录 loading 状态
const [loading, setLoading] = useState(false);
const { systemName } = useSelector((state: RootState) => state.basicSettings);
// 账号密码登录
const onFinish = async (values: any) => {
@@ -89,7 +91,7 @@ export default function Login() {
<div className="md:w-1/2 bg-white p-10 md:p-16 flex flex-col justify-center relative z-10">
<motion.div initial={{ opacity: 0, x: -20 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.2 }}>
<Title level={2} style={{ marginBottom: 40, color: '#111', fontWeight: 700 }}>
{t('login.systemName')}
{systemName || t('login.systemName')}
</Title>
<Form name="login" layout="vertical" onFinish={onFinish} autoComplete="off" size="large">

View File

@@ -1,4 +1,4 @@
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
export interface BasicSettingsState {
systemName: string;
@@ -19,6 +19,7 @@ export interface BasicSettingsState {
nightModeStart: string;
nightModeEnd: string;
enableNightMode: boolean;
globalParams: any[];
}
const STORAGE_KEY = 'basicSettings';
@@ -42,6 +43,7 @@ const defaultState: BasicSettingsState = {
nightModeStart: '23:00',
nightModeEnd: '07:00',
enableNightMode: false,
globalParams: [],
};
const loadFromStorage = (): BasicSettingsState => {
@@ -91,6 +93,10 @@ const basicSettingsSlice = createSlice({
Object.assign(state, action.payload);
persist(state);
},
setGlobalParams: (state, action: PayloadAction<any[]>) => {
state.globalParams = action.payload;
persist(state);
},
saveAllSettings: (state, action: PayloadAction<Partial<BasicSettingsState>>) => {
Object.assign(state, action.payload);
persist(state);
@@ -108,6 +114,7 @@ export const {
setDefaultPage,
setRefreshRate,
setSettingField,
setGlobalParams,
saveAllSettings,
resetBasicSettings,
} = basicSettingsSlice.actions;