/**
 * 数据总线，用于字典类型数据的序列化传递
 */
export class DataBus {
    // 基础存储
    private _dict: Map<string, { type: new () => any, value: any }>;
    private static _converters: Map<new () => any, (value: string) => any>;

    constructor() {
        this._dict = new Map();
        if (!DataBus._converters) {
            DataBus._converters = new Map();
            // 注册类型转换器
            DataBus._converters.set(String, (val: string) => val);
            DataBus._converters.set(Number, (val: string) => Number(val));
            DataBus._converters.set(Boolean, (val: string) => Boolean(val));
            DataBus._converters.set(BigInt, (val: string) => BigInt(val));
        }
    }

    /**
     * 清理所有数据项
     */
    public Clear(): void {
        this._dict.clear();
    }

    /**
     * 获取总线数据
     * @param key 数据键
     * @returns 数据值
     */
    public GetDataItem<T>(key: string): T | null {
        if (!key || !this._dict.has(key)) return null;
        return this._dict.get(key)?.value as T;
    }

    /**
     * 设置总线数据
     * @param key 数据键
     * @param value 数据值
     * @returns 是否设置成功
     */
    public SetDataItem<T>(key: string, value: T): boolean {
        if (!key || value === null || value === undefined) return false;

        const type = (value as Object).constructor as new () => T;
        if (!DataBus._converters.has(type)) {
            throw new Error(`DataBus：不支持的数据类型->[${type.name}]`);
        }

        this._dict.set(key, { type, value });
        return true;
    }

    /**
     * 数据序列化
     * @returns 序列化后的字符串
     */
    public Serialize(): string {
        const result: { [key: string]: any } = {};
        this._dict.forEach((val, key) => {
            result[key] = {
                type: val.type.name,
                value: val.value
            };
        });
        return JSON.stringify(result);
    }

    /**
     * 数据反序列化
     * @param data 序列化数据
     * @returns DataBus实例
     */
    public static Deserialize(data: string): DataBus {
        const parsed = JSON.parse(data);
        const dataBus = new DataBus();
        
        Object.keys(parsed).forEach(key => {
            const item = parsed[key];
            const type = DataBus._getTypeByName(item.type);
            if (type && DataBus._converters.has(type)) {
                dataBus._dict.set(key, {
                    type,
                    value: item.value
                });
            }
        });
        
        return dataBus;
    }

    /**
     * 根据类型名称获取类型
     */
    private static _getTypeByName(typeName: string): new () => any | null {
        switch (typeName) {
            case 'String': return String;
            case 'Number': return Number;
            case 'Boolean': return Boolean;
            case 'BigInt': return BigInt;
            default: return null;
        }
    }
}

// Vue组合式API封装
export const useDataBus = () => {
    return reactive(new DataBus());
}