@bams-app/store 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,217 @@
1
+ import { defineStore } from 'pinia';
2
+ import { env, localCache } from '@bams-app/utils';
3
+ import useAppStore from './app.js';
4
+
5
+ /**
6
+ * 运行时环境变量持久化 key(pinia-plugin-persistedstate 实际写入的 localStorage key)
7
+ */
8
+ export const RUNTIME_ENV_PERSIST_KEY = 'runtime-env';
9
+
10
+ /**
11
+ * 默认运行时环境变量接口地址
12
+ * 返回当前系统全部配置列表(每行含 category/configKey/val),按应用编码过滤后使用
13
+ */
14
+ export const DEFAULT_RUNTIME_ENV_URL = '/admin-api/sys/config/listConfigType';
15
+
16
+ /**
17
+ * 运行时环境变量持久化缓存的默认有效期(毫秒,24 小时)
18
+ */
19
+ export const RUNTIME_ENV_CACHE_TTL = 24 * 60 * 60 * 1000;
20
+
21
+ /**
22
+ * 带有效期的持久化存储适配器(委托 localCache)
23
+ * pinia-plugin-persistedstate 通过 getItem/setItem/removeItem 读写,
24
+ * 此处复用 localCache 的过期能力:写入时记录 addTime/expires,读取时自动判断过期并清理
25
+ */
26
+ const persistStorage = {
27
+ getItem(key) {
28
+ const value = localCache.get(key);
29
+ return value === undefined || value === null ? null : JSON.stringify(value);
30
+ },
31
+ setItem(key, value) {
32
+ localCache.set(key, JSON.parse(value), RUNTIME_ENV_CACHE_TTL);
33
+ },
34
+ removeItem(key) {
35
+ localCache.remove(key);
36
+ },
37
+ };
38
+
39
+ /**
40
+ * 运行时环境变量功能是否开启(构建时环境变量 VUE_APP_ENABLE_RUNTIME_ENV)
41
+ * 默认关闭;显式配置为 true/1/on/yes 时开启,关闭后不加载运行时配置
42
+ */
43
+ export function isRuntimeEnvEnabled() {
44
+ return env.resolveBooleanFeatureEnabled(env.getEnvVar("VUE_APP_ENABLE_RUNTIME_ENV"));
45
+ }
46
+
47
+ /**
48
+ * 功能开关状态(模块加载时确定一次,构建时注入的环境变量不会变化)
49
+ */
50
+ const RUNTIME_ENV_ENABLED = isRuntimeEnvEnabled();
51
+
52
+ /**
53
+ * 运行时环境变量 store
54
+ * 负责从后台接口读取当前应用编码(appStore.appCode)的环境变量配置:
55
+ * 配置唯一存于 state.config,由 pinia-plugin-persistedstate 插件负责本地持久化(有效期 24 小时)
56
+ * 功能受 VUE_APP_ENABLE_RUNTIME_ENV 环境变量控制,默认关闭
57
+ */
58
+ export default defineStore('runtimeEnv', {
59
+ state: () => ({
60
+ // 后台接口加载的环境变量配置(组件可通过 runtimeEnvStore.config 响应式读取)
61
+ config: {},
62
+ // 是否已加载可用配置(持久化缓存或接口;后端无配置时也标记为已加载,空结果同样进入 24 小时缓存)
63
+ loaded: false,
64
+ // 是否正在加载
65
+ loading: false,
66
+ // 加载错误信息
67
+ error: null,
68
+ }),
69
+ actions: {
70
+ /**
71
+ * 加载运行时环境变量配置
72
+ * 功能开关(VUE_APP_ENABLE_RUNTIME_ENV)关闭时直接返回,不注册读取器、不请求接口
73
+ * 1. 注册读取器:env.getEnvVar 立即可以读到 store.config(含持久化恢复的缓存值)
74
+ * 2. 应用编码来自 appStore(多应用 SPA 按应用区分配置)
75
+ * 3. 已有可用配置(24 小时有效期内的持久化缓存或本会话内已加载)时跳过接口请求,避免每次挂载都请求后端
76
+ * 4. 无有效缓存时请求后台接口获取最新配置,成功后写入 state.config(persist 插件自动持久化,带有效期)
77
+ * 加载失败时静默降级(保留持久化缓存或构建值),不影响应用正常启动
78
+ * @param {Object} [options] - 配置项
79
+ * @param {string} [options.url] - 接口地址
80
+ * @param {string} [options.appCode] - 应用编码,默认使用 appStore.appCode
81
+ * @returns {Promise<boolean>} 是否已有/成功加载可用配置
82
+ */
83
+ async load(options = {}) {
84
+ if (!RUNTIME_ENV_ENABLED) return false;
85
+ if (this.loading) return false;
86
+ this.loading = true;
87
+ try {
88
+ // 注册读取器:此后 env.getEnvVar 优先读取 store.config(含持久化恢复的缓存值)
89
+ env.registerRuntimeEnvReader(() => this.config);
90
+ // 已有可用配置(本会话已加载或持久化恢复,含"后端无配置"的空结果):跳过接口请求
91
+ // 以 loaded 标记为准而非 config 是否非空:后端无配置时接口返回空,空结果同样进入缓存,
92
+ // 避免每次刷新都重复请求接口
93
+ if (this.loaded || Object.keys(this.config).length > 0) {
94
+ return true;
95
+ }
96
+ const appCode = options.appCode || useAppStore().appCode;
97
+ const ok = await this.fetchEnvConfig({ ...options, appCode });
98
+ if (ok) {
99
+ this.loaded = true;
100
+ this.error = null;
101
+ }
102
+ return ok;
103
+ } catch (e) {
104
+ this.error = e;
105
+ return false;
106
+ } finally {
107
+ this.loading = false;
108
+ }
109
+ },
110
+
111
+ /**
112
+ * 清空运行时环境变量配置(内存 config + 持久化缓存)
113
+ * 注意:$reset 清空内存 config 后,依赖运行时配置的界面(如标题)会立即响应式回退为构建默认值
114
+ * 登出场景请使用 removePersistedCaches 仅清缓存,避免整页跳转/刷新前标题闪烁
115
+ */
116
+ clear() {
117
+ this.$reset();
118
+ this.removePersistedCaches();
119
+ },
120
+
121
+ /**
122
+ * 删除 localStorage 中的运行时环境变量持久化缓存
123
+ * 便于下次登录时重新获取最新配置
124
+ */
125
+ removePersistedCaches() {
126
+ try {
127
+ localCache.remove(RUNTIME_ENV_PERSIST_KEY);
128
+ } catch (e) {
129
+ // localStorage 不可用等异常,忽略即可
130
+ }
131
+ },
132
+
133
+ /**
134
+ * 应用环境变量配置:更新 store.config(persist 插件自动持久化),env.getEnvVar 立即生效
135
+ * 接口加载与持久化恢复的缓存均通过此方法统一生效
136
+ * @param {Object} config - 环境变量键值对
137
+ */
138
+ applyConfig(config) {
139
+ if (!config || typeof config !== 'object') return;
140
+ this.config = { ...this.config, ...config };
141
+ console.log('[runtimeEnv] 应用环境变量配置:', this.config);
142
+ },
143
+
144
+ /**
145
+ * 从后台接口读取当前应用编码的环境变量配置并应用
146
+ * 接口地址优先级:options.url > 默认地址 /admin-api/sys/config/listConfigType
147
+ * 响应格式:标准响应包 { code, msg, data },data 为配置列表数组
148
+ * 每行配置项含 category(应用编码)、configKey(不含 VUE_ 前缀的键)、val(值)
149
+ * 仅采用 category 等于当前应用编码的配置,且 configKey 对应的环境变量必须是构建时已声明的
150
+ * @param {Object} [options] - 配置项
151
+ * @param {string} [options.url] - 接口地址
152
+ * @param {string} [options.appCode] - 应用编码
153
+ * @returns {Promise<boolean>} 是否成功读取
154
+ */
155
+ async fetchEnvConfig({ url, appCode } = {}) {
156
+ const envUrl = url || DEFAULT_RUNTIME_ENV_URL;
157
+ if (!envUrl) return false;
158
+ try {
159
+ const res = await fetch(envUrl, {
160
+ method: 'GET',
161
+ headers: { 'Content-Type': 'application/json' },
162
+ cache: 'no-cache',
163
+ });
164
+ if (!res.ok) return false;
165
+ const result = await res.json();
166
+ if (result && result.code == 200) {
167
+ // 接口成功即视为已加载:即使当前应用没有任何配置项(后端空配置),
168
+ // 也持久化空结果,避免每次刷新都重新请求接口
169
+ const list = Array.isArray(result.data) ? result.data : [];
170
+ const config = this.normalizeConfig(list, appCode);
171
+ this.applyConfig(config);
172
+ return true;
173
+ }
174
+ } catch (e) {
175
+ // 接口加载失败,静默降级使用持久化缓存或本地 process.env
176
+ }
177
+ return false;
178
+ },
179
+
180
+ /**
181
+ * 将后台配置列表转换为当前应用的环境变量键值对
182
+ * 1. 仅保留 category 等于当前应用编码(appCode)的配置项
183
+ * 2. 接口返回的 configKey 不含 VUE_ 前缀(如 APP_TITLE 对应环境变量 VUE_APP_TITLE),补全前缀
184
+ * 3. 严格校验:转换后的环境变量必须是构建时声明的 VUE_ 前缀变量,未声明的一律忽略
185
+ * @param {Array} list - 后台返回的配置列表
186
+ * @param {string} appCode - 应用编码
187
+ * @returns {Object} 环境变量键值对
188
+ */
189
+ normalizeConfig(list, appCode) {
190
+ if (!Array.isArray(list)) return {};
191
+ const buildEnv = env.getProcessEnv({ withRuntime: false });
192
+ const config = {};
193
+ for (const item of list) {
194
+ if (!item || typeof item !== 'object') continue;
195
+ // 仅保留当前应用编码的配置项
196
+ if (item.category !== appCode) continue;
197
+ const { configKey, val } = item;
198
+ if (typeof configKey !== 'string' || !configKey || val === undefined || val === null) continue;
199
+ // configKey 不含 VUE_ 前缀,补全为构建时的环境变量名
200
+ const envKey = configKey.startsWith('VUE_') ? configKey : `VUE_${configKey}`;
201
+ // 严格校验:必须是构建时声明的环境变量,未声明的配置项忽略
202
+ if (!Object.prototype.hasOwnProperty.call(buildEnv, envKey)) continue;
203
+ config[envKey] = val;
204
+ }
205
+ return config;
206
+ },
207
+ },
208
+ // 持久化配置(pinia-plugin-persistedstate):只持久化 config,带 24 小时有效期
209
+ // 功能关闭时 config 始终为空对象,load() 短路已保证不加载运行时配置,此处无需按开关动态关闭持久化
210
+ persist: {
211
+ key: RUNTIME_ENV_PERSIST_KEY,
212
+ storage: persistStorage,
213
+ // 持久化 loaded:标记"已成功加载过(即使配置为空)",配合 24 小时有效期,
214
+ // 避免后端空配置时每次刷新都重复请求接口
215
+ pick: ['config', 'loaded'],
216
+ },
217
+ });
package/src/tabs.js ADDED
@@ -0,0 +1,269 @@
1
+ import { defineStore } from "pinia";
2
+ import useAppStore from "./app.js";
3
+ import useMenuStore from "./menu.js";
4
+ import { registerVersionChangeCleanup } from "./versionCacheCleanup.js";
5
+
6
+ const parseIsCache = value => {
7
+ if (typeof value === "boolean") return value;
8
+ if (typeof value === "number") return value === 1;
9
+ if (typeof value === "string") {
10
+ const normalizedValue = value.trim().toLowerCase();
11
+ return ["1", "true", "yes", "y"].includes(normalizedValue);
12
+ }
13
+ return false;
14
+ };
15
+
16
+ const buildCachedComponentName = routeName => {
17
+ return `CheckAuthWorkPage_${String(routeName)}`;
18
+ };
19
+
20
+ // 生成 tabs 持久化 key:persist 与版本变化清理共用,保证唯一来源
21
+ const getTabsPersistKey = () => {
22
+ const { appCode } = useAppStore();
23
+ return `[bams-app]-tabs-${appCode || "default"}`;
24
+ };
25
+
26
+ // 注册版本变化缓存清理:仅当用户点击"立即刷新"确认时清理本 store 的本地持久化缓存
27
+ registerVersionChangeCleanup(getTabsPersistKey);
28
+
29
+ export default defineStore("tabs", {
30
+ state: () => ({
31
+ // 当前已打开的页签列表
32
+ openedTabs: [],
33
+ // 当前激活的页签 key
34
+ activeKey: "",
35
+ // 正在执行“强制刷新”的缓存组件名,临时从 keep-alive include 中移除
36
+ refreshingComponentNames: [],
37
+ // 每个 tab 的刷新版本号,供内容区生成动态 key
38
+ refreshVersionMap: {},
39
+ }),
40
+ getters: {
41
+ // 仅为普通路由页且开启缓存的 tab 生成 keep-alive include 名单,
42
+ // 正在刷新的组件会先被排除,等视图重建后再恢复
43
+ cachedComponentNames: state => {
44
+ const refreshingNameSet = new Set(state.refreshingComponentNames);
45
+ return state.openedTabs
46
+ .filter(tab => String(tab.openType) === "0" && parseIsCache(tab.isCache))
47
+ .filter(tab => !refreshingNameSet.has(buildCachedComponentName(tab.name)))
48
+ .map(tab => buildCachedComponentName(tab.name));
49
+ },
50
+ // 开启缓存的 iframe 页签列表:常驻渲染、v-show 切换显隐,切走不销毁、切回不重载
51
+ cachedIframeTabs: state =>
52
+ state.openedTabs.filter(tab => String(tab.openType) === "1" && parseIsCache(tab.isCache)),
53
+ },
54
+ actions: {
55
+ // 将菜单数据和当前路由信息整理成 tabs 统一结构
56
+ createTabFromMenu(menuItem, route) {
57
+ const routeName = route?.name ? String(route.name) : String(menuItem.path || "");
58
+ return {
59
+ key: routeName,
60
+ name: routeName,
61
+ title: menuItem.menuName,
62
+ path: menuItem.path,
63
+ params: menuItem.params,
64
+ openType: menuItem.openType,
65
+ iframeSrc: menuItem.iframeSrc || "",
66
+ isCache: menuItem.isCache,
67
+ };
68
+ },
69
+ getTabByKey(key) {
70
+ return this.openedTabs.find(tab => tab.key === String(key)) || null;
71
+ },
72
+ getRefreshVersion(key) {
73
+ return this.refreshVersionMap[String(key)] || 0;
74
+ },
75
+ // 已存在则更新,不存在则追加,并同步激活态
76
+ upsertTab(tab) {
77
+ const existingIndex = this.openedTabs.findIndex(item => item.key === tab.key);
78
+
79
+ if (existingIndex === -1) {
80
+ this.openedTabs.push(tab);
81
+ } else {
82
+ this.openedTabs.splice(existingIndex, 1, {
83
+ ...this.openedTabs[existingIndex],
84
+ ...tab,
85
+ });
86
+ }
87
+
88
+ this.activeKey = tab.key;
89
+ return tab;
90
+ },
91
+ // 通用批量删除能力,同时负责收敛 activeKey、缓存刷新状态和刷新版本号
92
+ removeTabs(keys) {
93
+ const normalizedKeys = [...new Set(keys.map(key => String(key)))];
94
+
95
+ if (!normalizedKeys.length) {
96
+ return {
97
+ removedTabs: [],
98
+ nextTab: null,
99
+ };
100
+ }
101
+
102
+ const keySet = new Set(normalizedKeys);
103
+ const removedTabs = this.openedTabs.filter(tab => keySet.has(tab.key));
104
+
105
+ if (!removedTabs.length) {
106
+ return {
107
+ removedTabs: [],
108
+ nextTab: null,
109
+ };
110
+ }
111
+
112
+ let nextTab = null;
113
+
114
+ if (keySet.has(this.activeKey)) {
115
+ const activeIndex = this.openedTabs.findIndex(tab => tab.key === this.activeKey);
116
+ const rightTab = this.openedTabs.slice(activeIndex + 1).find(tab => !keySet.has(tab.key));
117
+ const leftTab = [...this.openedTabs.slice(0, activeIndex)].reverse().find(tab => !keySet.has(tab.key));
118
+ nextTab = rightTab || leftTab || null;
119
+ this.activeKey = nextTab?.key || "";
120
+ }
121
+
122
+ this.openedTabs = this.openedTabs.filter(tab => !keySet.has(tab.key));
123
+
124
+ const removingComponentNames = new Set(
125
+ removedTabs
126
+ .filter(tab => String(tab.openType) === "0" && parseIsCache(tab.isCache))
127
+ .map(tab => buildCachedComponentName(tab.name))
128
+ );
129
+ this.refreshingComponentNames = this.refreshingComponentNames.filter(name => !removingComponentNames.has(name));
130
+
131
+ const nextRefreshVersionMap = { ...this.refreshVersionMap };
132
+ normalizedKeys.forEach(key => {
133
+ delete nextRefreshVersionMap[key];
134
+ });
135
+ this.refreshVersionMap = nextRefreshVersionMap;
136
+
137
+ return {
138
+ removedTabs,
139
+ nextTab,
140
+ };
141
+ },
142
+ // 路由变化后同步 tabs;只有能命中菜单配置的页面才会加入 openedTabs
143
+ syncTabByRoute(route) {
144
+ const routeName = route?.name ? String(route.name) : "";
145
+
146
+ if (!routeName) {
147
+ this.activeKey = "";
148
+ return null;
149
+ }
150
+
151
+ const menuStore = useMenuStore();
152
+ const menuItem = menuStore.menuPathMap[routeName];
153
+
154
+ if (!menuItem || !menuItem.path) {
155
+ this.activeKey = routeName;
156
+ return null;
157
+ }
158
+
159
+ return this.upsertTab(this.createTabFromMenu(menuItem, route));
160
+ },
161
+ removeTab(key) {
162
+ return this.removeTabs([key]).nextTab;
163
+ },
164
+ // 保留目标 tab,关闭其余所有 tab
165
+ removeOtherTabs(key) {
166
+ const targetKey = String(key);
167
+ const exists = this.getTabByKey(targetKey);
168
+
169
+ if (!exists) {
170
+ return null;
171
+ }
172
+
173
+ const keysToRemove = this.openedTabs
174
+ .filter(tab => tab.key !== targetKey)
175
+ .map(tab => tab.key);
176
+
177
+ return this.removeTabs(keysToRemove).nextTab;
178
+ },
179
+ // 关闭目标 tab 左侧所有页签
180
+ removeLeftTabs(key) {
181
+ const targetKey = String(key);
182
+ const targetIndex = this.openedTabs.findIndex(tab => tab.key === targetKey);
183
+
184
+ if (targetIndex <= 0) {
185
+ return null;
186
+ }
187
+
188
+ const keysToRemove = this.openedTabs
189
+ .slice(0, targetIndex)
190
+ .map(tab => tab.key);
191
+
192
+ return this.removeTabs(keysToRemove).nextTab;
193
+ },
194
+ // 关闭目标 tab 右侧所有页签
195
+ removeRightTabs(key) {
196
+ const targetKey = String(key);
197
+ const targetIndex = this.openedTabs.findIndex(tab => tab.key === targetKey);
198
+
199
+ if (targetIndex === -1 || targetIndex >= this.openedTabs.length - 1) {
200
+ return null;
201
+ }
202
+
203
+ const keysToRemove = this.openedTabs
204
+ .slice(targetIndex + 1)
205
+ .map(tab => tab.key);
206
+
207
+ return this.removeTabs(keysToRemove).nextTab;
208
+ },
209
+ // 标记某个 tab 执行刷新:
210
+ // 1. 递增版本号,触发视图动态 key 更新
211
+ // 2. 如果该页面启用了缓存,则临时移出 keep-alive include
212
+ markTabForRefresh(key) {
213
+ const targetKey = String(key);
214
+ const targetTab = this.getTabByKey(targetKey);
215
+
216
+ this.refreshVersionMap = {
217
+ ...this.refreshVersionMap,
218
+ [targetKey]: this.getRefreshVersion(targetKey) + 1,
219
+ };
220
+
221
+ if (!targetTab) {
222
+ return null;
223
+ }
224
+
225
+ if (String(targetTab.openType) === "0" && parseIsCache(targetTab.isCache)) {
226
+ const componentName = buildCachedComponentName(targetTab.name);
227
+ if (!this.refreshingComponentNames.includes(componentName)) {
228
+ this.refreshingComponentNames = [...this.refreshingComponentNames, componentName];
229
+ }
230
+ }
231
+
232
+ return targetTab;
233
+ },
234
+ // 页面实例重建后,把该组件从“刷新中”状态移除,恢复缓存资格
235
+ finishTabRefresh(key) {
236
+ const targetKey = String(key);
237
+ const targetTab = this.getTabByKey(targetKey);
238
+ const componentName = buildCachedComponentName(targetTab?.name || targetKey);
239
+
240
+ this.refreshingComponentNames = this.refreshingComponentNames.filter(name => name !== componentName);
241
+ },
242
+ // 清空所有 tabs 以及与 tabs 相关的刷新状态
243
+ removeAllTabs() {
244
+ this.openedTabs = [];
245
+ this.activeKey = "";
246
+ this.refreshingComponentNames = [];
247
+ this.refreshVersionMap = {};
248
+ },
249
+ // 清除 tabs 持久化缓存:重置内存状态,并删除 localStorage 中的所有 tabs 持久化 key,
250
+ // 避免上一会话的历史页签被恢复到新会话(登录成功后调用)
251
+ // key 为 [bams-app]-tabs-${appCode},按前缀批量删除以覆盖不同 appCode 及历史遗留 key
252
+ removePersistedCaches() {
253
+ this.$reset();
254
+ try {
255
+ Object.keys(localStorage)
256
+ .filter(key => key.startsWith("[bams-app]-tabs-"))
257
+ .forEach(key => localStorage.removeItem(key));
258
+ } catch (e) {
259
+ // localStorage 不可用等异常,忽略即可
260
+ }
261
+ },
262
+ },
263
+ // 持久化已打开 tabs 和当前激活项,保证页面刷新后仍能恢复
264
+ persist: {
265
+ key: getTabsPersistKey,
266
+ storage: localStorage,
267
+ pick: ["openedTabs", "activeKey"],
268
+ },
269
+ });
package/src/unit.js ADDED
@@ -0,0 +1,167 @@
1
+ import { defineStore } from "pinia";
2
+ import { bdApi } from "@bams-app/api-model";
3
+
4
+ export default defineStore("unit", {
5
+ state: () => ({
6
+ unitList: [], // 单位数据列表,从localStorage恢复
7
+ total: 0, // 总条数
8
+ loading: false, // 加载状态
9
+ searchVal: "", // 搜索关键词
10
+ current: 1, // 当前页码
11
+ size: 10000, // 每页数量
12
+ initialized: false, // 是否已初始化(是否已调用过API)
13
+ }),
14
+
15
+ getters: {
16
+ // 获取所有单位列表
17
+ getAllUnits: state => state.unitList,
18
+
19
+ // 单位编码到单位对象的映射
20
+ unitMap: state => {
21
+ return state.unitList.reduce((map, unit) => {
22
+ if (unit.unitCode) {
23
+ map[unit.unitCode] = unit.unitName;
24
+ }
25
+ return map;
26
+ }, {});
27
+ },
28
+
29
+ // 根据ID获取单位
30
+ getUnitById: state => id => {
31
+ return state.unitList.find(unit => unit.id === id);
32
+ },
33
+
34
+ // 根据编码获取单位
35
+ getUnitByCode: state => code => {
36
+ return state.unitList.find(unit => unit.unitCode === code);
37
+ },
38
+
39
+ // 获取基本计量单位
40
+ getBaseUnits: state => {
41
+ return state.unitList.filter(unit => unit.isBaseUnit === "Y");
42
+ },
43
+
44
+ // 根据量纲获取单位
45
+ getUnitsByDimen: state => dimen => {
46
+ return state.unitList.filter(unit => unit.oppdimen === dimen);
47
+ },
48
+ },
49
+
50
+ actions: {
51
+ // 初始化方法(只调用一次)
52
+ async init() {
53
+ if (!this.initialized) {
54
+ await this.fetchUnitList();
55
+ this.initialized = true;
56
+ }
57
+ return this.unitList;
58
+ },
59
+
60
+ // 获取单位列表
61
+ async fetchUnitList(params = {}) {
62
+ this.loading = true;
63
+ try {
64
+ // 合并参数,默认查询全部(current: 0, size: 0)
65
+ const queryParams = {
66
+ searchVal: this.searchVal,
67
+ current: this.current,
68
+ size: this.size,
69
+ ...params,
70
+ };
71
+
72
+ // const response = await request({
73
+ // url: "/admin-api/bd/unit/list",
74
+ // method: "POST",
75
+ // data: queryParams,
76
+ // });
77
+ const response = await bdApi.getUnitList(queryParams);
78
+ console.log("获取单位列表成功:", response);
79
+ // 更新状态
80
+ this.unitList = response.records || [];
81
+ this.total = response.total || 0;
82
+ this.current = response.current || 0;
83
+ this.size = response.size || 0;
84
+
85
+ return response;
86
+ } catch (error) {
87
+ console.error("获取单位列表失败:", error);
88
+ this.unitList = [];
89
+ this.total = 0;
90
+ throw error;
91
+ } finally {
92
+ this.loading = false;
93
+ }
94
+ },
95
+
96
+ // 设置搜索关键词并刷新列表
97
+ async setSearchVal(searchVal) {
98
+ this.searchVal = searchVal;
99
+ await this.fetchUnitList();
100
+ },
101
+
102
+ // 设置页码并刷新列表
103
+ async setCurrentPage(current) {
104
+ this.current = current;
105
+ await this.fetchUnitList();
106
+ },
107
+
108
+ // 设置每页数量并刷新列表
109
+ async setPageSize(size) {
110
+ this.size = size;
111
+ await this.fetchUnitList();
112
+ },
113
+
114
+ // 刷新单位列表
115
+ async refreshUnitList() {
116
+ await this.fetchUnitList();
117
+ },
118
+
119
+ // 根据ID更新单个单位信息
120
+ updateUnitById(id, updateData) {
121
+ const index = this.unitList.findIndex(unit => unit.id === id);
122
+ if (index !== -1) {
123
+ this.unitList[index] = { ...this.unitList[index], ...updateData };
124
+ }
125
+ },
126
+
127
+ // 根据编码更新单个单位信息
128
+ updateUnitByCode(code, updateData) {
129
+ const index = this.unitList.findIndex(unit => unit.unitCode === code);
130
+ if (index !== -1) {
131
+ this.unitList[index] = { ...this.unitList[index], ...updateData };
132
+ }
133
+ },
134
+
135
+ // 添加新单位
136
+ addUnit(unit) {
137
+ this.unitList.unshift(unit);
138
+ this.total++;
139
+ },
140
+
141
+ // 删除单位
142
+ removeUnit(id) {
143
+ const index = this.unitList.findIndex(unit => unit.id === id);
144
+ if (index !== -1) {
145
+ this.unitList.splice(index, 1);
146
+ this.total--;
147
+ }
148
+ },
149
+
150
+ // 清空单位列表
151
+ clearUnitList() {
152
+ this.unitList = [];
153
+ this.total = 0;
154
+ this.searchVal = "";
155
+ this.current = 0;
156
+ this.size = null;
157
+ },
158
+ },
159
+
160
+ // 持久化存储配置
161
+ persist: {
162
+ key: "[bams-app]-unit",
163
+ storage: localStorage, // 使用localStorage持久化
164
+ pick: ["unitList"], // 只持久化单位列表数据
165
+ // 移除自定义序列化逻辑,使用插件默认配置确保paths生效
166
+ },
167
+ });