import { defineStore } from 'pinia';

export const useDictStore = defineStore({
  id: 'dict',
  state: () => ({
    dict: []
  }),
  actions: {
    // 获取字典
    getDict(_key) {
        if (_key == null || _key === "") {
            return null;
        }
        try {
            for (let i = 0; i < this.dict.length; i++) {
                let item = this.dict[i];
                if (item.key === _key) {
                    return item.value;
                }
            }
        } catch (e) {
            return null;
        }
        return null; // 如果未找到对应的字典项，返回null
    },
    // 设置字典
    setDict({ key, value }) {
        if (key !== null && key !== "") {
            this.dict.push({ key, value });
        }
    },
    // 删除字典
    removeDict(_key) {
        let removed = false;
        try {
            for (let i = 0; i < this.dict.length; i++) {
                if (this.dict[i].key === _key) {
                    this.dict.splice(i, 1);
                    removed = true;
                    break; // 找到并移除后直接退出循环
                }
            }
        } catch (e) {
            removed = false;
        }
        return removed;
    },
    // 清空字典
    cleanDict() {
        this.dict = []; // 直接赋空数组即可清空字典
    }
  },
});
