import form from "../api/apiForm";
let apiForm = form.apis;
let axios = null;

export default {
    name: "DATA_GLOBAL",

    OBJ_DATAS: {}, // 数据字典ID 对 本级数据字典数组
    OBJ_DATAOBJS: {},
    OBJ_TREE_DATAS: {}, // 数据字典ID 对 数据字典树
    KEY_NAME: {}, // 存放元数据的key和name，用作其他模块的使用

    install(Vue,opts){
        axios = opts.spcpFormAxios;
    },

    /**
     * 根据typeId刷新数据字典缓存
     * @param typeId
     */
    refreshByTypeId(typeId) {
        let vm = this;
        Object.keys(vm.OBJ_DATAS).forEach(function (key) {
            if (key.indexOf(typeId) > -1) {
                let arrKeys = key.split("_");
                vm.getDatas(arrKeys[0], arrKeys[1]);
            }
        });

        Object.keys(vm.OBJ_TREE_DATAS).forEach(function (key) {
            if (key.indexOf(typeId) > -1) {
                let arrKeys = key.split("_");
                vm.getTreeDatas(arrKeys[0], arrKeys[1]);
            }
        });
    },

    /**
     * 获取数据字典（数组形式）
     * @param typeId
     * @param parentId
     * @param ifRefresh 是否刷新
     * @returns {*}
     */
    getDatas(typeId, parentId, ifRefresh) {
        let vm = this;
        if (!typeId) {
            return [];
        }
        parentId = parentId || "";
        ifRefresh = ifRefresh || false;
        return new Promise(function (resolve) {

            if (vm.OBJ_DATAS[typeId + "_" + parentId] && !ifRefresh) {
                resolve(vm.OBJ_DATAS[typeId + "_" + parentId]);
            } else {
                let objDatas = [];
                axios.post(apiForm.mixDataTool.getDataByType,{"sourceKey":window.currentDataSourceKey,typeId: typeId, parentId: parentId}).then(function (res) {
                    (res.data || []).forEach(item => {
                        if(item && item.id && item.dataName){
                            objDatas.push(item);
                            vm.setKeyName(item.id, item.dataName);
                        }
                    })
                    vm.OBJ_DATAS[typeId + "_" + parentId] = objDatas;
                    resolve(objDatas);
                });
            }
        });
    },

    /**
     * 获取数据字典（数组形式）
     * @param typeId
     * @param parentId
     * @param ifRefresh 是否刷新
     * @param getOutDate 是否查询过期数据,1:默认查询，0：不查询
     * @returns {*}
     */
    getDatasContainOutDate(typeId, parentId, ifRefresh,getOutDate) {
        let vm = this;
        if (!typeId) {
            return [];
        }
        parentId = parentId || "";
        ifRefresh = ifRefresh || false;
        getOutDate = getOutDate || "1";
        return new Promise(function (resolve) {
            if (vm.OBJ_DATAS[typeId + "_" + parentId + "_" + getOutDate] && !ifRefresh) {
                resolve(vm.OBJ_DATAS[typeId + "_" + parentId + "_" + getOutDate]);
            } else {
                let objDatas = [];
                axios.post(apiForm.mixDataTool.getDataByType,{"sourceKey":window.currentDataSourceKey,typeId: typeId, parentId: parentId}).then(function (res) {
                    objDatas.push(...res.data);
                    resolve(objDatas);
                });
            }
        });
    },

    /**
     * 获取数据字典（对象形式）
     * @param typeId
     * @param parentId
     * @param ifRefresh 是否刷新
     * @returns {*}
     */
    getDataObjs(typeId, parentId, ifRefresh) {
        let vm = this;
        if (!typeId) {
            return {};
        }

        parentId = parentId || "-1";
        ifRefresh = ifRefresh || false;
        return new Promise(function (resolve) {
            if (vm.OBJ_DATAOBJS[typeId + "_" + parentId] && !ifRefresh) {
                resolve(vm.OBJ_DATAOBJS[typeId + "_" + parentId]);
            } else {
                vm.getDatas(typeId, parentId, ifRefresh).then(datas => {
                    let objData = {};
                    datas.forEach(data => {
                        objData[data.id] = data;
                    });
                    vm.OBJ_DATAOBJS[typeId + "_" + parentId] = objData;
                    resolve(objData);
                });
            }
        });
    },

    /**
     * 获取多层级数据字典
     * @param typeId
     * @param parentId
     * @param ifRefresh 是否刷新
     * @returns {*}
     */
    getTreeDatas(typeId, parentId, ifRefresh) {
        let vm = this;
        if (!typeId) {
            return [];
        }
        parentId = parentId || "-1";
        ifRefresh = ifRefresh || false;
        return new Promise(function (resolve) {
            if (vm.OBJ_TREE_DATAS[typeId + "_" + parentId] && !ifRefresh) {
                resolve(Object.assign([], vm.OBJ_TREE_DATAS[typeId + "_" + parentId]));
            } else {
                axios.post(apiForm.mixDataTool.getDataTree, {typeId: typeId, parentId: parentId,sourceKey:window.currentDataSourceKey}).then(function (res) {

                    // 如果原先已存在数据字典缓存信息，那么不直接赋值修改对象，应用引用型数据的特性
                    if (vm.OBJ_TREE_DATAS[typeId + "_" + parentId]) {
                        vm.OBJ_TREE_DATAS[typeId + "_" + parentId].splice(0, vm.OBJ_TREE_DATAS[typeId + "_" + parentId].length);
                        res.data.forEach(function (data) {
                            vm.OBJ_TREE_DATAS[typeId + "_" + parentId].push(data);
                        });
                    } else {
                        vm.OBJ_TREE_DATAS[typeId + "_" + parentId] = res.data;
                    }
                    resolve(Object.assign([], vm.OBJ_TREE_DATAS[typeId + "_" + parentId]));
                });
            }
        });
    },

    /*
    ** 存入key name
    */
    setKeyName(key, name) {
        this.KEY_NAME[key] = name;
    },
    /*
    ** 获取key name
    */
    getKeyName(key) {
        return this.KEY_NAME[key];
    },


    /**
     * 根据数据字典 ids （多个用逗号分隔）
     * @param ids
     * @returns {*}
     */
    getDataByIds(ids){
        let vm = this;
        if (!ids) {
            return new Promise(resolve => {
                resolve("");
            });
        }
        return new Promise(resolve=>{
            let dataNameArr = [];
            let idArr = ids.split(",") || [];
            let dataIdObj = {};
            let sIds = "";
            idArr.forEach(id =>{
                dataIdObj[id] = this.getKeyName(id) || '';
                if(!this.getKeyName(id)){
                    sIds += "," +id;
                }
                dataNameArr.push(this.getKeyName(id) || '');
            });
            if(sIds){
                sIds = sIds.substring(1);
                axios.post(apiForm.mixDataTool.getByIds, {ids: sIds,sourceKey:window.currentDataSourceKey}).then(res=> {
                    let arr = [];
                    (res.data || []).forEach(item =>{
                        //放入缓存中
                        if(item && item.id && item.dataName){
                            vm.setKeyName(item.id,item.dataName);
                            // arr.push(item.dataName);
                            dataIdObj[item.id] = item.dataName;
                        }
                    })
                    idArr.forEach(id =>{
                        arr.push(dataIdObj[id]);
                    })
                    if(arr.length == 1){
                        resolve(arr[0]);
                    }else {
                        resolve(arr);
                    }
                });
            }else {
                if(dataNameArr.length == 1){
                    resolve(dataNameArr[0]);
                }else {
                    resolve(dataNameArr);
                }
            }
        });
    },

    /**
     * 根据数据字典 id  先走缓存没有数据再查后台
     * @param id
     * @returns {*}
     */
    getDataById(id){
        let vm = this;
        return new Promise(function (resolve) {
            let dataName=vm.getKeyName(id);
            if(!dataName){//缓存不存在 查后台
                axios.post(apiForm.mixDataTool.getByIds, {ids: id,sourceKey:window.currentDataSourceKey}).then(res=> {
                    if(res.data && res.data[0]!=null){
                        let item=res.data[0];
                        //放入缓存中
                        if(item && item.id && item.dataName){
                            vm.setKeyName(item.id,item.dataName);
                        }
                        resolve(item.dataName);
                    }else{
                        dataName=id;
                        resolve(dataName);
                    }
                });
            }else{
                resolve(dataName);
            }

        })

    }

}
