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

let axios = null;

export default {
    name: "FORM_GLOBAL",

    OBJ_LAST_LIST_DATA:{}, // 根据formDefineKey与listViewDefineKey获取的所有最新列表视图信息
    LOAD_LAST_LIST_FINISH:false, // 是否已经加载了最新的列表视图数据
    OBJ_LIST_VIEWS: {}, // 列表视图定义信息
    OBJ_TABLE_VIEWS: {}, // 表单视图定义信息
    OBJ_LIST_FIELDS: {}, // 列表列信息
    OBJ_LIST_AND_FIELDS: {}, // 列表和列信息
    OBJ_FORM_FIELDS: {}, // 表单列信息
    OBJ_FORM_FIELD_ID: {}, // 表单列信息
    OBJ_SEARCH_BOX: {}, // 查询框信息
    OBJ_LIST_VIEWS_BUTTONS: {}, // 列表按钮信息
    OBJ_VIEWS_BUTTONS: {}, //表单按钮信息
    OBJ_LIST_MODEL: {}, //表单按钮信息
    OBJ_FORM_BASE: {}, // 智能建表信息
    OBJ_CONTROL_CONFIGS:{},//表单控件信息
    OBJ_EVENT_RULES : {},//事件规则
    OBJ_EVENT_SETS : {},//表单事件
    OBJ_FLOWID_PAGE : {},// 流程ID转pageInfo

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

    clearCache(){
        this.OBJ_LIST_VIEWS = {}; // 列表视图定义信息
        this.OBJ_TABLE_VIEWS = {}; // 表单视图定义信息
        this.OBJ_LIST_FIELDS = {}; // 列表列信息
        this.OBJ_LIST_AND_FIELDS = {}; // 列表和列信息
        this.OBJ_FORM_FIELDS = {}; // 表单列信息
        this.OBJ_FORM_FIELD_ID = {}; // 表单列信息
        this.OBJ_SEARCH_BOX = {}; // 查询框信息
        this.OBJ_LIST_VIEWS_BUTTONS = {}; // 列表按钮信息
        this.OBJ_VIEWS_BUTTONS = {}; //表单按钮信息
        this.OBJ_LIST_MODEL = {}; //表单按钮信息
        this.LOAD_LAST_LIST_FINISH = false; // 是否已经加载了最新的列表视图数据
        this.OBJ_LAST_LIST_DATA = {};
        this.OBJ_FORM_BASE = {};
        this.OBJ_CONTROL_CONFIGS = {};//表单控件信息
        this.OBJ_EVENT_RULES = {};//事件规则
        this.OBJ_EVENT_SETS = {};//表单事件
        this.OBJ_FLOWID_PAGE = {};// 流程ID转pageInfo
    },

    getPageInfoByFlowId(flowId){
        return new Promise(resolve => {
            if(this.OBJ_FLOWID_PAGE[flowId]){
                resolve(this.OBJ_FLOWID_PAGE[flowId]);
            }else{
                let url = apiForm.plPageInfo.find;
                axios.post(url,{flowId:flowId}).then(res => {
                    let datas = res.data || [];
                    if(datas.length > 0){
                        let pageInfo = datas[0];
                        this.OBJ_FLOWID_PAGE[flowId] = pageInfo;
                        resolve(pageInfo);
                    }else{
                        resolve(false);
                    }
                })
            }
        })
    },

    /**
     * 根据ID获取列表视图定义信息
     * @param id
     * @param userType 当前登陆用户类型（开发者用户不走缓存）
     * @returns {*}
     */
    getListViews(id,userType) {
        return new Promise(resolve => {
            let cacheObj = this.OBJ_LIST_VIEWS;
            let key = `${id}`;
            let url = apiForm.plListViews.getListViewCacheById;
            let params = {id};
            if (!cacheObj.hasOwnProperty(key) || userType == 'sup') {
                axios.post(url, params).then(res => {
                    if (res.data) {
                        cacheObj[key] = res.data || [];
                        resolve(cacheObj[key]);
                    }
                });
            } else {
                resolve(cacheObj[key]);
            }
        });
    },

    /**
     * 根据ID获取表单视图定义信息
     * @param id
     * @param userType 当前登陆用户类型（开发者用户不走缓存）
     * @returns {*}
     */
    getTableViews(id,userType) {
        return new Promise(resolve => {
            let cacheObj = this.OBJ_TABLE_VIEWS;
            let key = `${id}`;
            let url = apiForm.plTableviews.getCacheById;
            let params = {id};
            if (!cacheObj.hasOwnProperty(key) || userType == 'sup') {
                axios.post(url, params).then(res => {
                    if (res.data) {
                        cacheObj[key] = res.data || {};
                        resolve(cacheObj[key]);
                    }
                });
            } else {
                resolve(cacheObj[key]);
            }
        });
    },
    /**
     * 根据ID获取表单定义信息
     * @param id
     * @param userType 当前登陆用户类型（开发者用户不走缓存）
     * @returns {*}
     */
    getFormBase(id,userType) {
        return new Promise(resolve => {
            let cacheObj = this.OBJ_FORM_BASE;
            let key = `${id}`;
            let url = apiForm.plFormBase.getById;
            let params = {id};
            if (!cacheObj.hasOwnProperty(key) || userType == 'sup') {
                axios.post(url, params).then(res => {
                    if (res.data) {
                        cacheObj[key] = res.data || {};
                        resolve(cacheObj[key]);
                    }
                });
            } else {
                resolve(cacheObj[key]);
            }
        });
    },

    /**
     * 根据ID获取流程定义信息
     * @param listViewId
     * @param userType 当前登陆用户类型（开发者用户不走缓存）
     * @returns {*}
     */
    getListFields(listViewId,userType) {
        let order = "FIELD_ORDER";
        return new Promise(resolve => {
            let cacheObj = this.OBJ_LIST_FIELDS;
            let key = `${listViewId}_${order}`;
            let url = apiForm.plListField.getCacheByViewId;
            let params = {listViewId, order};
            if (!cacheObj.hasOwnProperty(key) || userType == 'sup') {
                axios.post(url, params).then(res => {
                    if (res.data) {
                        cacheObj[key] = res.data || [];
                        resolve(cacheObj[key]);
                    }
                });
            } else {
                resolve(cacheObj[key]);
            }
        });
    },

    /**
     * 根据ID获取流程定义信息
     * @param listViewDefineId
     * @param formDefineKey
     * @param userType 当前登陆用户类型（开发者用户不走缓存）
     * @returns {*}
     */
    getViewAndFields(listViewDefineId,formDefineKey,userType) {
        return new Promise(resolve => {
            let cacheObj = this.OBJ_LIST_AND_FIELDS;
            let key = `${listViewDefineId}`;
            let url = apiForm.plFormBase.getViewAndField;
            let params = {listViewDefineId,formDefineKey};
            if (!cacheObj.hasOwnProperty(key) || userType == 'sup') {
                axios.post(url, params).then(res => {
                    if (res.data) {
                        cacheObj[key] = res.data || [];
                        resolve(cacheObj[key]);
                    }
                });
            } else {
                resolve(cacheObj[key]);
            }
        });
    },

    /**
     * 根据ID获取流程定义信息
     * @param formId
     * @param userType 当前登陆用户类型（开发者用户不走缓存）
     * @returns {*}
     */
    getFormFields(formId,userType) {
        return new Promise(resolve => {
            let cacheObj = this.OBJ_FORM_FIELDS;
            let key = `${formId}`;
            let url = apiForm.plFormField.find;
            let params = {formId};
            if (!cacheObj.hasOwnProperty(key) || userType == 'sup') {
                axios.post(url, params).then(res => {
                    if (res.data) {
                        cacheObj[key] = res.data || [];
                        this.initFormFieldIdCache(cacheObj[key]);
                        resolve(cacheObj[key]);
                    }
                });
            } else {
                resolve(cacheObj[key]);
            }
        });
    },

    clearFormFields(formId){
        delete this.OBJ_FORM_FIELDS[formId];
    },

    /**
     * 刷新列缓存
     * @param datas
     */
    initFormFieldIdCache(datas) {
        (datas || []).forEach(data => {
            this.OBJ_FORM_FIELD_ID[data.id] = data;
        });
    },

    /**
     * 根据IDS获取表单字段信息(增量查询缓存)
     * @param ids
     * @param userType 当前登陆用户类型（开发者用户不走缓存）
     * @returns {*}
     */
    getFormFieldsByIds(ids,userType) {
        return new Promise(resolve => {
            let results = [];
            let arrParamIds = [];
            ids.split(",").forEach(id => {
                if (this.OBJ_FORM_FIELD_ID.hasOwnProperty(id) && userType != 'sup') {
                    results.push(this.OBJ_FORM_FIELD_ID[id]);
                }else{
                    arrParamIds.push(id);
                }
            });

            if (arrParamIds.length == 0) {
                resolve(results);
                return;
            }

            let url = apiForm.plFormField.getCacheByIds;
            let params = {id: arrParamIds.join(",")};
            axios.post(url, params).then(res => {
                (res.data || []).forEach(data => {
                    results.push(data);
                    this.OBJ_FORM_FIELD_ID[data.id] = data;
                });
                resolve(results);
            });
        });
    },

    /**
     * 根据ID获取流程定义信息
     * @param formId
     * @param listViewId
     * @param order
     * @param userType 当前登陆用户类型（开发者用户不走缓存）
     * @returns {*}
     */
    getSearchBox(formId, listViewId, order,userType) {
        return new Promise(resolve => {
            let cacheObj = this.OBJ_SEARCH_BOX;
            let key = `${formId}_${listViewId}_${order}`;
            let url = apiForm.plSearchbox.getCacheByListViewId;
            let params = {formId, listViewId, order};
            if (!cacheObj.hasOwnProperty(key) || userType == 'sup') {
                axios.post(url, params).then(res => {
                    // if (res.data) { 空数据也要走resolve，不然不能触发promise的then回调
                    cacheObj[key] = res.data || [];
                    resolve(cacheObj[key]);
                    // }
                });
            } else {
                resolve(cacheObj[key]);
            }
        });
    },

    /**
     * 根据ID获取流程定义信息
     * @param formId
     * @param listViewId
     * @param openMode
     * @param order
     * @param userType 当前登陆用户类型（开发者用户不走缓存）
     * @returns {*}
     */
    getListViewsButtons(formId, listViewId, openMode, order,userType) {
        return new Promise(resolve => {
            let cacheObj = this.OBJ_LIST_VIEWS_BUTTONS;
            let key = `${formId}_${listViewId}_${openMode}_${order}`;
            let url = apiForm.plListViewsButton.findButton;
            let params = {formId, listViewId, openMode, order};
            if (!cacheObj.hasOwnProperty(key) || userType == 'sup') {
                axios.post(url, params).then(res => {
                    // if (res.data) {空数据也要走resolve，不然不能触发promise的then回调
                        cacheObj[key] = (res.data && res.data.operateObj) || [];
                        resolve(cacheObj[key]);
                    // }
                });
            } else {
                resolve(cacheObj[key]);
            }
        });
    },

    /**
     * 根据ID获取流程定义信息
     * @param tviewId
     * @param userType 当前登陆用户类型（开发者用户不走缓存）
     * @returns {*}
     */
    getViewsButtons(tviewId,userType) {
        return new Promise(resolve => {
            let cacheObj = this.OBJ_VIEWS_BUTTONS;
            let key = `${tviewId}`;
            let url = apiForm.plViewsButton.getCacheByTableViewId;
            let params = {tviewId};
            if (!cacheObj.hasOwnProperty(key) || userType == 'sup') {
                axios.post(url, params).then(res => {
                    // if (res.data) {空数据也要走resolve，不然不能触发promise的then回调
                        cacheObj[key] = (res.data) || [];
                        resolve(cacheObj[key]);
                    // }
                });
            } else {
                resolve(cacheObj[key]);
            }
        });
    },
    /**
     * 根据列表视图ID获取信息
     * @param tviewId
     * @param userType 当前登陆用户类型（开发者用户不走缓存）
     * @returns {*}
     */
    getAllListModel(listViewId,userType) {
        return new Promise(resolve => {
            let cacheObj = this.OBJ_LIST_MODEL;
            let key = `${listViewId}`;
            let url = apiForm.plListViews.getAllListModel;
            let params = {listViewId};
            if (!cacheObj.hasOwnProperty(key) || userType == 'sup') {
                axios.post(url, params).then(res => {
                    cacheObj[key] = (res.data) || [];
                    resolve(cacheObj[key]);
                });
            } else {
                resolve(cacheObj[key]);
            }
        });
    },

    /**
     * 清除列表视图缓存数据
     * @param listViewId
     */
    clearListModelByViewId(listViewId){
        delete this.OBJ_LIST_MODEL[listViewId];
    },

    clearAllListModel() {
        this.OBJ_LIST_MODEL = {};
    },

    /**
     * 根据tviewId重新刷新按钮对象
     * @param tviewId
     * @param buttonArr 最新缓存表单按钮
     */
    updateViewsButton(tviewId,buttonArr){
        let cacheObj = this.OBJ_VIEWS_BUTTONS;
        let key = `${tviewId}`;
        cacheObj[key] = buttonArr || []; //重新赋值按钮
    },

    /**
     * 根据tviewId重新刷新表单控件对象
     */
    updateControlConfig(tviewId,controlConfigArr){
        let cacheObj = this.OBJ_CONTROL_CONFIGS;
        let key = `${tviewId}`;
        cacheObj[key] = controlConfigArr || []; //重新赋值按钮
    },

    /**
     * 重新刷新刷新列表按钮
     * @param formId
     * @param listViewId
     * @param openMode
     * @param order
     * @param buttonArr
     */
    updateListViewsButton(formId, listViewId, openMode, order,buttonArr){
        let cacheObj = this.OBJ_LIST_VIEWS_BUTTONS;
        let key = `${formId}_${listViewId}_${openMode}_${order}`;
        cacheObj[key] = buttonArr || []; //重新
    },

    /**
     * 重新刷新搜索框
     * @param formId
     * @param listViewId
     * @param order
     * @param searchBoxArr
     */
    updateSearchBox(formId, listViewId, order,searchBoxArr){
        let cacheObj = this.OBJ_SEARCH_BOX;
        let key = `${formId}_${listViewId}_${order}`;
        cacheObj[key] = searchBoxArr;
    },

    /**
     * /重新刷新列表视图字段
     * @param listViewId
     * @param fieldArr
     */
    updateListFields(listViewId,fieldArr){
        let order = "FIELD_ORDER";
        let cacheObj = this.OBJ_LIST_FIELDS;
        let key = `${listViewId}_${order}`;
        cacheObj[key] = fieldArr || [];
    },

    /**
     * 加载所有最新的列表视图数据
     */
    loadAllNewList(){
        if(!this.LOAD_LAST_LIST_FINISH){
            this.LOAD_LAST_LIST_FINISH = true;
        }
        let url = apiForm.plListViews.loadAllNewList;
        axios.post(url).then(res => {
            (res.data || []).forEach(item => {
                this.OBJ_LAST_LIST_DATA[item.formDefineKey + "_" + item.defineKey] = item;
            })
        });
    },

    /**
     * 根据formDefineKey与defineKey获取最新的列表视图数据
     * @param params
     * @returns {Promise<unknown>}
     */
    findListNewVersion(params){
        if(!this.LOAD_LAST_LIST_FINISH){
            this.LOAD_LAST_LIST_FINISH = true;
            this.loadAllNewList();
        }
        if(!params){
            return;
        }
        let formDefineKey = params.formDefineKey;
        let listDefineKey = params.defineKey;
        let url = apiForm.plListViews.findNewVersion;
        return new Promise(resolve => {
            let result = {};
            let cachedListData = this.OBJ_LAST_LIST_DATA[formDefineKey + "_" + listDefineKey];
            if(!cachedListData){
                axios.post(url, params).then(res => {
                    let listViews = res.data || {};
                    this.OBJ_LAST_LIST_DATA[formDefineKey + "_" + listDefineKey] = listViews;
                    result.data = listViews;
                    resolve(result);
                });
            }else{
                result.data = cachedListData;
                resolve(result);
            }
        })
    },

    /**
     * 根据ID获取表单控件配置
     * @param tviewId
     * @param userType 当前登陆用户类型（开发者用户不走缓存）
     * @returns {*}
     */
    getControlConfig(tviewId,userType) {
        return new Promise(resolve => {
            let cacheObj = this.OBJ_CONTROL_CONFIGS;
            let key = `${tviewId}`;
            let url = apiForm.plControlConfig.findCacheByTviewId;
            let params = {tviewId};
            if (!cacheObj.hasOwnProperty(key) || userType == 'sup') {
                axios.post(url, params).then(res => {
                    // if (res.data) {空数据也要走resolve，不然不能触发promise的then回调
                    cacheObj[key] = (res.data) || [];
                    resolve(JSON.parse(JSON.stringify(cacheObj[key])));
                    // }
                });
            } else {
                resolve(JSON.parse(JSON.stringify(cacheObj[key])));
            }
        });
    },

    /**
     * 获取事件规则数据（异步）
     * @param userType 当前登陆用户类型（开发者用户不走缓存）
     * @param tableViewId
     */
    getEventRules(tableViewId,userType){
        return new Promise(resolve => {
            if(!this.OBJ_EVENT_RULES.hasOwnProperty(tableViewId) || userType == 'sup'){
                axios.post(apiForm.plTableviewsEvent.findEventRule,{tableViewId:tableViewId,order:"RULE_ORDER ASC"}).then(res => {
                    if(res && res.data){
                        this.OBJ_EVENT_RULES[tableViewId] = (res.data.operateObj || []);
                        let result = this.OBJ_EVENT_RULES[tableViewId];
                        resolve(JSON.parse(JSON.stringify(result)));
                    }else{
                        resolve([]);
                    }
                });
            }else{
                let result = this.OBJ_EVENT_RULES[tableViewId];
                resolve(JSON.parse(JSON.stringify(result)));
            }
        });
    },

    /**
     * 获取事件规则数据（同步）
     * @param tableViewId
     */
    async getEventRulesAsync(tableViewId,userType){
        if(!this.OBJ_EVENT_RULES.hasOwnProperty(tableViewId || userType == 'sup')){
            let res = await axios.post(apiForm.plTableviewsEvent.findEventRule,{tableViewId:tableViewId,order:"RULE_ORDER ASC"});
            if(res && res.data){
                this.OBJ_EVENT_RULES[tableViewId] = (res.data.operateObj || []);
            }
        }
        return this.OBJ_EVENT_RULES[tableViewId] || [];
    },

    // /**
    //  * 清除事件规则缓存
    //  * @param tableViewId
    //  */
    // clearEventByTableviewId(tableViewId){
    //     delete this.OBJ_EVENT_RULES[tableViewId];
    // },
    /**
     * 清除表单数据缓存
     * @param tableViewId
     */
    clearTableViewsInfo(tableViewId){
        delete this.OBJ_EVENT_RULES[tableViewId];
        delete this.OBJ_VIEWS_BUTTONS[tableViewId];
        delete this.OBJ_TABLE_VIEWS[tableViewId];
    },

    /**
     * 获取表单事件数据（同步）
     * @param formId
     * @param tableViewId
     * @param sourceType
     * @returns {Promise<*>}
     */
    async getEventSetsAsync(formId,tableViewId,sourceType){
        let key = formId + "_" + tableViewId + "_" + sourceType;
        if(!this.OBJ_EVENT_SETS.hasOwnProperty(key)){
            let res = await axios.post(apiForm.plEventSet.find,{formId:formId,tviewId:tableViewId,sourceType:sourceType});
            if(res && res.data){
                this.OBJ_EVENT_SETS[key] = (res.data || []);
            }
        }
        return JSON.parse(JSON.stringify(this.OBJ_EVENT_SETS[key]));
    }
}
