import page from './page'

// 可以在不同的地方共享数据、传参
let _DATA: { [key: string]: any } = {}

function get<T>(key?: string, defaultValue?: T): T {
    if (!key) {
        key = page.getPagePath()
    }
    const val = _DATA[key]
    return (val === undefined ? defaultValue : val) as T
}

// 设值
function set(key: string, value: any) {
    _DATA[key] = value
}

// 弹出值
function pop<T>(key?: string, defaultValue?: T): T {
    if (!key) {
        key = page.getPagePath()
    }
    const value = _DATA[key]
    delete _DATA[key]
    return value || defaultValue
}

// 清空
function clear() {
    _DATA = {}
}

// 函数的key
function _pageFnObjKey(pageUrl: string) {
    return pageUrl + '_mj_fn_obj'
}

function _getPageFnObj(pageUrl: string) {
    const key = _pageFnObjKey(pageUrl)
    let fnObj = _DATA[key]
    if (!fnObj) {
        fnObj = {}
        _DATA[key] = fnObj
    }
    return fnObj
}

// 调用函数
function callFn(key: string, ...args: any) {
    // 函数对象
    const fn = _getPageFnObj(page.getPagePath())[key]
    if (fn) {
        // 直接调用
        return fn(...args)
    }
    // console.log('callFn', _DATA)
}

// 存储函数
function setFn(key: string, fn: any) {
    _getPageFnObj(page.getPagePath())[key] = fn
    // console.log('setFn', _DATA)
}

function popPageFns(pageUrl: string) {
    delete _DATA[_pageFnObjKey(pageUrl)]
    // console.log('popPageFns', _DATA)
}

export default {
    get,
    set,
    pop,
    clear,
    callFn,
    setFn,
    popPageFns,
}
