import constant from './constant';
import { envWx, EnvType } from '@/config';

// 存储变量名
type StorageKeyMap = Record<EnvType, string>;

const mapTokenKey: StorageKeyMap = {
    develop: 'storage_data',
    trial: 'storage_data',
    release: 'storage_data-app',
};

const storageKey: string = mapTokenKey[envWx];

// 存储节点变量名
const storageNodeKeys: string[] = [...Object.values(constant)];

// 存储的数据
let storageData: Record<string, any> = uni.getStorageSync(storageKey) || {};

interface StorageInterface {
    set: (key: string, value: any) => void;
    get: (key: string) => any;
    remove: (key: string) => void;
    clean: () => void;
}

const storage: StorageInterface = {
    set: function(key: string, value: any): void {
        if (storageNodeKeys.indexOf(key) !== -1) {
            let tmp: Record<string, any> = uni.getStorageSync(storageKey);
            tmp = tmp ? tmp : {};
            tmp[key] = value;
            uni.setStorageSync(storageKey, tmp);
        }
    },
    get: function(key: string): any {
        return storageData[key] || '';
    },
    remove: function(key: string): void {
        delete storageData[key];
        uni.setStorageSync(storageKey, storageData);
    },
    clean: function(): void {
        uni.removeStorageSync(storageKey);
    }
};

export default storage;
