import axios from 'axios/index';

/**
 * 是否开启表单window缓存
 * @type {boolean}
 */
let OPEN_CACHE = true;

let DATA_CACHE = {
    menu: {},
    menuOpts: {},

    formAllModel: {},
    viewFormModel: {},
    formFields: {},
    manyTableFields: {},
    formTreeDefine: {},
    formHideFields: {},
    formScripts: {}
};

/**
 * 判断是否缓存
 * @param cacheVal  缓存值
 * @returns {*|boolean} 是否缓存
 */
function isCache(cacheVal) {
    return cacheVal && OPEN_CACHE;
}

/**
 * 公共获取缓存值得方法
 * @param keyName   缓存的keyName
 * @param key       被缓存的key值
 * @param url       后台请求地址
 * @param params    参数
 * @returns         返回值
 */
function getVal(keyName, key, url, params) {
    return new Promise(resolve => {
        if (isCache(DATA_CACHE[keyName][key])) {
            resolve(DATA_CACHE[keyName][key]);
        } else {
            axios.post(url, params).then(res => {
                DATA_CACHE[keyName][key] = res.data;
                resolve(DATA_CACHE[keyName][key]);
            });
        }
    });
}

export default {
    name: "FLOW_INST_GLOBAL",

    openCache() {
        OPEN_CACHE = true;
    },

    /**
     * 关闭缓存的同时会清掉现有缓存
     */
    closeCache() {
        OPEN_CACHE = false;
        this.clearCache();
    },

    clearCache() {
        for (let [key] of Object.entries(DATA_CACHE)) {
            DATA_CACHE[key] = {};
        }
    },

    getMenuById(menuId) {
        return getVal("menu", menuId, "menuController/getById", {id: menuId});
    },

    getMenuOptsByMenuId(menuId) {
        return getVal("menuOpts", menuId, "authController/getMenuOptsByUserAndMenu", {"menuId": menuId});
    },

    getFormAllListModel(viewListId) {
        return getVal("formAllModel", viewListId, 'formViewsController/getAllListModel', {"formId": viewListId});
    },

    getViewFormModel(viewFormId) {
        return getVal("viewFormModel", viewFormId, "tableViewsController/getById", {id: viewFormId});
    },

    getFormFields(formId) {
        return getVal("formFields", formId, 'fieldbaseController/listNoPage', {"formId": formId});
    },

    getFormHideFields(viewId) {
        return getVal("formHideFields", viewId, 'hidefieldController/find', {viewId: viewId});
    },

    getManyTableFields(formId, viewId) {
        return getVal("manyTableFields", formId + "_" + viewId, "fieldbaseController/getManyTableFields", {
            "formId": formId,
            "viewId": viewId,
            "isAllField": "1",
        });
    },

    getFormTreeDefineById(treeId) {
        return getVal("formTreeDefine", treeId, "formtreedefineController/getById", {
            "id": treeId
        });
    },

    getFormScriptsByIds(ids) {
        return getVal("formScripts", ids, 'formscriptController/getByIds', {"ids": ids});
    }
};
