import cacheGlobal from "../../assets/js/global/cacheGlobal";
import apiOutAdmin from "../../assets/js/api/apiOutAdmin";
let apiOutAdmin = apiOutAdmin.apis;
import axios from 'axios';

export default {
    name: "RES_GLOBAL",

    OBJ_RES: {}, // 系统参数
    ARR_OWN_MENU_OPT: [],
    ARR_OPERATE_ROOT: [],
    ALL_ROLE_ID:[],
    initSuccess:false,
    callBackArr:[], // 回调队列

    initOwnMenuOpt() {
        return new Promise(resolve => {
            let loginUser = cacheGlobal.getLoginUser();
            axios.post(apiOutAdmin.auth.getOwnMenuOpt, {
                userId: loginUser.id,
                userType: loginUser.userType,
                optType: 'menu'
            }).then(res => {
                this.ALL_ROLE_ID = [];
                (res.data || []).forEach(item => {
                    if(this.ALL_ROLE_ID.indexOf(item.roleId) == -1){
                        this.ALL_ROLE_ID.push(item.roleId);
                    }
                })
                this.ARR_OWN_MENU_OPT = res.data;
                this.initSuccess = true;
                this.callBackArr.forEach(callback => {
                    callback && callback(this.ALL_ROLE_ID.join(","));
                })
                resolve(this.ARR_OWN_MENU_OPT);
            })
        });
    },

    getUserOwnMenuOpt() {
        return new Promise(resolve => {
            if(this.ARR_OWN_MENU_OPT == null || this.ARR_OWN_MENU_OPT.length == 0){
                this.initOwnMenuOpt().then(data => {
                    resolve(this.ARR_OWN_MENU_OPT);
                });
            }else{
                resolve(this.ARR_OWN_MENU_OPT);
            }
        });
    },

    /**
     * 根据ID获取资源地址
     * @param id
     * @param userType 当前登陆用户类型（开发者用户不走缓存）
     * @returns {*}
     */
    getById(id,userType) {
        return new Promise(resolve => {
            if(!this.OBJ_RES.hasOwnProperty(id)||!this.OBJ_RES[id] || userType == 'sup'){
                axios.post(apiOutAdmin.resources.findResourcesById, {id: id}).then(res => {
                    if(res.data && res.data.operateObj){
                        this.OBJ_RES[id] = res.data.operateObj|| {};
                        resolve(this.OBJ_RES[id]);
                    }
                });
            }else{
                resolve(this.OBJ_RES[id]);
            }
        });
    }
}
