import {storageIO} from "sasp-base";
import apiOutAdmin from "../api/apiOutAdmin";
import localForage from 'localforage';
import {apiForm} from "../../../../index";
let axios = null;

let {setLocalJSON, getLocalJSON, removeLocal} = storageIO;


export default {
    name: "CACHE_GLOBAL",

    synObj: {},

    DATA_CACHE: {},
    ARR_USER_INFO:[],//所有用户信息

    ARR_ALL_USER_INFO:[], //所有用户信息（包含已锁定）

    LOCK_USER_INFO:[], //锁定用户信息
    ARR_ALL_POS_USER_INFO:[], //所有组织岗位用户信息（包含已锁定）

    ALL_TYPE_AND_DATA:{},  //所有数据字典

    ALL_TYPE_AND_DATA_TIME:{},  //所有数据字典时间

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

    clearCache(){
        this.ARR_USER_INFO=[];
        this.ARR_ALL_USER_INFO = [];
    },

    init() {
        this.DATA_CACHE = {};
    },

    getLoginUser() {
        return getLocalJSON('LOGINUSER') || {};
    },
    /*
    ** 将登录用户存入sessionStorage中
    */
    setLocalJSON(key,value){
        setLocalJSON(key, value);
    },
    setLoginUser(user, token) {
        setLocalJSON('LOGINUSER', user);
    },
    setLoginToken(token) {
        let customToken = window.customToken;
        if(!customToken) {
            customToken = "pl_token_";
        }
        setLocalJSON('USERTOKEN', customToken + token);

        localStorage["Authorization" + (window.projectSuffix || "")] = customToken + token;
        axios.defaults.headers.common["Authorization"] = customToken + token;
    },

    clearLoginToken(token) { // 登陆前清空登录认证token
        setLocalJSON('USERTOKEN', "");
        localStorage["Authorization" + (window.projectSuffix || "")] = "";
        axios.defaults.headers.common["Authorization"] = "";
    },

    /**
     * 将登录用户的部门信息存入sessionStorage中
     * @param deptInfo
     */
    setLoginDept(deptInfo) {
        setLocalJSON('LOGINUSERDEPT', deptInfo);
    },

    clearLoginDept() { // 登陆前清空登录部门信息
        setLocalJSON('LOGINUSERDEPT', "");
    },

    /*
    ** 从sessionStorage中获取登录用户
    */
    getLoginToken() {
        return getLocalJSON('USERTOKEN');
    },
    /*
    ** 从sessionStorage中获取登录用户
    */

    getLocalJSON(key){
        return getLocalJSON(key);
    },
    /*
    ** 将登录用户存入sessionStorage中
    */
    setSysDataObj(sysdataObj,sourceKey) {
        localForage.setItem('SYSDATAOBJ_' + (sourceKey || 'master'), sysdata).then(() => {});
    },
    /*
    ** 将登录用户存入sessionStorage中
    */
    setSysDataArr(sysdata,sourceKey) {
        localForage.setItem('SYSDATAARR_' + (sourceKey || 'master'), sysdata).then(() => {});
    },

    /*
    ** 从sessionStorage中获取登录用户
    */
    getSysDataObj(sourceKey) {
        return new Promise(resolve => {

            let key = 'SYSDATAOBJ_' + (sourceKey || 'master');
            if (this.DATA_CACHE[key]) {
                resolve(this.DATA_CACHE[key]);
                return;
            }

            localForage.getItem(key).then(val => {
                if(val==null){
                    this.getAllDataType(sourceKey).then(datas => {
                        let sysDataObj = {};
                        datas.forEach(item => {
                            sysDataObj[item.id] = item;
                        })
                        resolve(sysDataObj);
                        this.setSysDataObj(sysDataObj,sourceKey);
                    });
                }else {
                    resolve(val);
                }
            });
        })
    },


    /**
     * 从sessionStorage中获取登录用户的部门信息
     * @returns {*}
     */
    getLoginDept() {
        return getLocalJSON('LOGINUSERDEPT');
    },

    /**
     * 获取纯前端地址
     */
    getWebUrl(route) {
        let path = route.path;
        return location.href.substring(0, location.href.lastIndexOf(path));
    },

    /**
     * 查询所有组织岗位用户信息
     */
    getAllPosUser(isShowLock){
        return new Promise(resolve => {
            let vm=this;
            if(vm.ARR_ALL_POS_USER_INFO.length == 0){ // LOCK_USER_INFO
                axios.post(apiOutAdmin.apis.sysOrgPosUser.findNoPage).then(function (res) {
                    axios.post(apiOutAdmin.apis.sysUser.getOnlyUsers,{"userType":"ent","order":"USER_NAME_QP asc"}).then(function (resUser) {
                        (resUser.data ||[]).forEach(item =>{
                            if(item.userStatus != '10'){
                                vm.LOCK_USER_INFO.push({
                                    orgName:"",
                                    userName:item.userName,
                                    userId:item.id,
                                    isLockUser:true
                                });
                            }
                        });

                        vm.ARR_ALL_POS_USER_INFO = res.data || [];
                        if(isShowLock){
                            resolve(vm.ARR_ALL_POS_USER_INFO.concat(vm.LOCK_USER_INFO));
                        }else{
                            resolve(vm.ARR_ALL_POS_USER_INFO);
                        }
                    });
                });
            }else{
                if(isShowLock){
                    resolve(vm.ARR_ALL_POS_USER_INFO.concat(vm.LOCK_USER_INFO));
                }else{
                    resolve(vm.ARR_ALL_POS_USER_INFO);
                }
            }
        });
    },

    getDataToLocalForage(sourceKey) {
        return new Promise((resolve) => {
            // 先判断 ALL_TYPE_AND_DATA有没有
            if (!this.ALL_TYPE_AND_DATA[sourceKey]) {
                localForage.getItem("SYSDATAARR_" + sourceKey).then(datas => {
                    if(datas){
                        resolve(datas);
                        this.getInteval(sourceKey)
                    }else{
                        this.getAllDataType(sourceKey).then(axiosDatas => {
                            resolve(axiosDatas);
                        })
                    }
                })
            }else{
                resolve(this.ALL_TYPE_AND_DATA[sourceKey]);
            }
        });

    },
    /**
     * 获取全量数据字典
     */
    getAllDataType(sourceKey,time){
        return new Promise(resolve => {
            axios.post(apiForm.apis.mixData.findAllTypeAndDataForLocalForage,{'sourceKey':sourceKey,"time":time}).then((res)=>{
                if (res.data.operateMessage == "true"){
                    resolve();
                }else{
                    let timestrap = res.data.operateObj.timestrap;
                    let allTypeAndData = res.data.operateObj.allTypeAndData;
                    this.ALL_TYPE_AND_DATA[sourceKey] = allTypeAndData;
                    this.ALL_TYPE_AND_DATA_TIME[sourceKey] = timestrap;
                    this.setSysDataArr(allTypeAndData,sourceKey);
                    localForage.setItem('timestrap_' + (sourceKey || 'master'), timestrap);
                    resolve(allTypeAndData);
                }
            });
        })
    },


    getInteval(sourceKey) {
        if (!this.synObj[sourceKey]){
            setTimeout(() =>{
                localForage.getItem("timestrap_" + sourceKey).then(time => {
                    this.getAllDataType(sourceKey,time);
                    this.synObj[sourceKey] = true;
                });
            }, 1000);
        }
    }
};
