import axios from 'axios';
import $ from 'jquery';
import Cookies from 'js-cookie';
import md5 from 'js-md5';
import { Modal } from 'view-ui-plus'

// async synchro

let caseMethod = {};

let OmdUrl = {};
OmdUrl.eid = '0';
OmdUrl.uid = '0';
OmdUrl.uname = 'future';
OmdUrl.format = 'json';
OmdUrl.appKey = 'mall';
OmdUrl.portalkey = 'congou';
OmdUrl.checktoken = 'Y';
OmdUrl.ver = '1.0';
OmdUrl.signMethod = 'MD5';
OmdUrl.secret = '';
OmdUrl.omp = '/mall-work-webin/rest';
OmdUrl.mall = '/mall-work-webin/rest';
OmdUrl.mss = '/mall-work-webin/rest';
OmdUrl.portal = '/mall-portal-rest/portalesb/ocmrest';
OmdUrl.mdm = '/ocm-mdm-webin/rest';
OmdUrl.omc = '/omc-tags-webin/rest';
OmdUrl.member = '/omc-membership-webin/rest';
OmdUrl.accnt = '/omc-accnt-webin/rest';
OmdUrl.work = '/omc-work-webin/rest';
OmdUrl.investment = '/mall-investment-webin/rest';
OmdUrl.uploadfile ='/mss-sysconf-boot/upload';
OmdUrl.delfile ='/mss-sysconf-boot/delete?filekey=';
OmdUrl.downfile = '/mss-sysconf-boot/download?filekey=';
OmdUrl.getfile = '/mss-sysconf-boot/filedata?';
OmdUrl.amp = '/ampOpenapiService/';
OmdUrl.uidespath = OmdUrl.amp;
OmdUrl.helpUrl = 'docs.sjhgo.com';
OmdUrl.mallmdm = '/mall-mdm-webin/rest';
OmdUrl.mallmaster = '/mall-master-webin/rest';
OmdUrl.portal = OmdUrl.mallmdm;
OmdUrl.uiConfigExpire = 24;
OmdUrl.fairyConfigExpire = 24;
OmdUrl.dictExpire = 24;
OmdUrl.operbilllog = '/mss-sysconf-query/rest';
//测试
//OmdUrl.startHelp = 'Y';
//OmdUrl.helpType = '13';
//OmdUrl.portal = '/mall-master-webin/rest';
//OmdUrl.mdm = '/mall-master-webin/rest';

OmdUrl.getCurHelpUrl = function (that) {
    var curHelpUrl = '';
    if (that.OmdUrl.startHelp === 'Y') {
        if (that.OmdUrl.helpType) {
            var modulecodeHelp = that.$Method.getUrlParam('helpindex');
            var modulecodeHelpUrl = that.$Method.getLocalStorage('modulecodeHelp_' + that.OmdUrl.helpType + '_' + modulecodeHelp);
            if (modulecodeHelpUrl) {
                return modulecodeHelpUrl;
            }
            if (modulecodeHelp) {
                var helpUrl = that.OmdUrl.helpUrl;
                if (!helpUrl) {
                    if (that.getHelpdocumenturl) {
                        helpUrl = that.getHelpdocumenturl();
                    }
                }
                if (helpUrl) {
                    let helpId = that.getHelpId(that.OmdUrl.helpType, modulecodeHelp);
                    if (helpId) {
                        curHelpUrl ='http://' + helpUrl + '/web/#/p/' + helpId;
                    } else {
                        curHelpUrl = 'http://' + helpUrl + '/web/#/' + that.OmdUrl.helpType + '?page_id=' + modulecodeHelp;
                    }
                }
                that.$Method.setLocalStorage('modulecodeHelp_' +that.OmdUrl.helpType + '_' + modulecodeHelp,curHelpUrl,that.OmdUrl.uiConfigExpire)
            }
        }
    }
    return curHelpUrl;
};

caseMethod.OmdUrl = OmdUrl;

caseMethod.alert = function (_strerr, _title, _flag) {
    if (!_flag) {
        _flag = '1';
    }
    if (_strerr && typeof _strerr === 'string') {
        _strerr = _strerr.replace(new RegExp('</xmp>', 'gi'), '</txmp>');
        _strerr = _strerr.replace(new RegExp('<xmp', 'gi'), '<txmp');
        _strerr = '<xmp style="margin: 0;white-space:break-spaces;">' +_strerr + '</xmp>';
    }
    _flag = _flag + '';
    if (_flag === '2') {
        Modal.error({
            title: '系统警告',
            content: '<div style="word-wrap:break-word">' + _strerr + '</div>'
        });
    } else if (_flag === '3') {
        if (!_title) {
            _title = '成功';
        }
        Modal.success({
            title:_title,
            content: '<div style="word-wrap:break-word">' + _strerr + '</div>'
        });
    } else {
        if (!_title) {
            _title = '提醒';
        }
        Modal.warning({
            title: _title,
            content: '<div style="word-wrap:break-word">' + _strerr + '</div>'
        });
    }
};




function getCommonUrlParam (_self, _param, _type) {
    let token = caseMethod.getToken();
    let end_id = caseMethod.getEnt_id();
    let para = _param;
    if (!para) {
        para = {};
    }
    let portalkey = _self.OmdUrl.portalkey;
    if (!caseMethod.getUrlParam('portalkey'))  {
        portalkey = caseMethod.getUrlParam('portalkey');
    }
    if (caseMethod.getUrlParam('srvkey') === 'cloud')  {
        portalkey = 'cloud';
    }
    if (_type === '1') {
        let url = '';
        if (token && token.trim() !== '') {
            url = url + '&ent_id=' + end_id + '&token=' + token + '&timestamp=' + new Date().getTime() + '&format=' + _self.OmdUrl.format + '&app_key=' + _self.OmdUrl.appKey + '&portalkey=' + portalkey + '&ver=' + _self.OmdUrl.ver;
            if (_self.OmdUrl.signMethod.trim().length !== 0  && _self.OmdUrl.secret.trim().length != 0) {
                url = url + '&sign_method=' + _self.OmdUrl.signMethod + '&sign=';
                let secret =  _self.OmdUrl.appKey+'='+_self.OmdUrl.secret+'&body='+JSON.stringify(para).toString()+'&token='+token;
                if (_self.OmdUrl.getMd5 !== undefined) {
                    secret =  _self.OmdUrl.getMd5(para, token);
                }
                url = url+ md5(secret);
            }
        } else {
            let _session = { 'ent_id': end_id, 'user_id': _self.OmdUrl.uid, 'user_code': _self.OmdUrl.uid, 'user_name': _self.OmdUrl.uname };
            url = url + '&session=' + JSON.stringify(_session);
        }
        return url;
    } else {
        let temp = {};
        if (token && token.trim() !== '') {
            temp.ent_id = end_id;
            temp.token = token;
            temp.timestamp = new Date().getTime();
            temp.format = _self.OmdUrl.format;
            temp.app_key = _self.OmdUrl.appKey;
            temp.ver = _self.OmdUrl.ver;
            temp.portalkey = portalkey;
            temp.sign_method = _self.OmdUrl.signMethod;
            let secret =  _self.OmdUrl.appKey+'='+_self.OmdUrl.secret+'&body='+JSON.stringify(para).toString()+'&token='+token;
            if (_self.OmdUrl.getMd5 !== undefined) {
                secret =  _self.OmdUrl.getMd5(para, token);
            }
            temp.sign = md5(secret);
        } else {
            let _session = { 'ent_id': end_id, 'user_id': _self.OmdUrl.uid,'user_code': _self.OmdUrl.uid, 'user_name': _self.OmdUrl.uname };
            temp.session = JSON.stringify(_session);
        }
        return temp;
    }
}
function basePost (url, method, postdata, _self , _type) {
    let temp = {};
    if (method) {
        temp.method = method;
    }
    let comtemp = getCommonUrlParam(_self, postdata, '2');
    for (let v in comtemp) {
        temp[v]=comtemp[v];
    }
    if (!postdata) {
        postdata = {};
    }

    let menuCode = caseMethod.getUrlParam('menuCode');
    if (menuCode) {
        temp.menuCode = menuCode;
    }
    if (_type === 'get') {
        return new Promise((resolve, reject) => {
            axios.get(url, postdata, {
                params: temp
            })
                .then(response => {
                    resolve(response.data);
                }, err => {
                    reject(err);
                })
                .catch((error) => {
                    reject(error);
                });
        });
    } else {
        return new Promise((resolve, reject) => {
            axios.post(url, postdata, {
                params: temp
            })
                .then(response => {
                    resolve(response.data);
                }, err => {
                    reject(err);
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }

}

function successRequest (data, _successFunc, _failFunc, _errorFunc, _self) {
    let obj = null;
    try {
        if (typeof data === 'string') {
            obj = JSON.parse(data);
        } else {
            obj = data;
        }
        if (parseInt(obj.returncode) === 0) { // 请求处理成功
            try {
                if (_successFunc) {
                    _successFunc(obj.data);
                }
            } catch (e) {
                if (_self.$Spin) {
                    _self.$Spin.hide();
                }
                _self.$nextTick(() => {
                    setTimeout(() => {
                        _self.alert(e, null, 2);
                    }, 1000);
                });
            }
            return;
        } else if (parseInt(obj.returncode) > 0) {
            if (_failFunc) {
                try {
                    _failFunc(obj.data);
                } catch (e) {
                    if (_self.$Spin) {
                        _self.$Spin.hide();
                    }
                    _self.$nextTick(() => {
                        setTimeout(() => {
                            _self.alert(e, null, 2);
                        }, 1000);
                    });
                }
                return;
            } else {
                throw obj.data; // 业务处理错误
            }
        } else {
            if (_errorFunc) {
                try {
                    _errorFunc(obj.data);
                } catch (e) {
                    if (_self.$Spin) {
                        _self.$Spin.hide();
                    }
                    _self.$nextTick(() => {
                        setTimeout(() => {
                            _self.alert(e, null, 2);
                        }, 1000);
                    });
                }
                return;
            } else {
                throw obj.data; // 系统异常
            }
        }
    } catch (e) {
        if (_self.$Spin) {
            _self.$Spin.hide();
        }
        _self.$nextTick(() => {
            setTimeout(() => {
                if (typeof data === 'string') {
                    _self.alert(e + '<br/>' + data, null, 2);
                } else {
                    _self.alert(e, null, 2);
                }
            }, 1000);
        });
    }
}
caseMethod.asyncPost = function (url, method, postdata, _successFunc, _failFunc, _errorFunc, _type) {
    let _self = this;
    if (!url.startsWith('/')) {
        url = '/' + url;
    }
    basePost(url, method, postdata, _self, _type).then(function (data) {
        return successRequest(data, _successFunc, _failFunc, null, _self);
    }, function (err) {
        if (_failFunc) {
            _failFunc(err);
        } else {
            if (_self.$Spin) {
                _self.$Spin.hide();
            }
            _self.$nextTick(() => {
                setTimeout(() => {
                    _self.alert(err.message + '<br/>' + err.response.data, null, '2');
                }, 1000);
            });
        }
    }).catch((err) => {
        if (_errorFunc) {
            _errorFunc(err);
        } else {
            if (_self.$Spin) {
                _self.$Spin.hide();
            }
            let error = JSON.stringify(err);
            _self.$nextTick(() => {
                setTimeout(() => {
                    _self.alert(error, null, '2');
                }, 1000);
            });
            return false;
        }
    });
};
// 判断是否为IE浏览器
// function isIE () { return !!(window.ActiveXObject || 'ActiveXObject' in window); }

function getresturl (_baseUrl, _method, _param, _self) {
    let url = '';
    if (_method) {
        url = 'method=' + _method;
    } else {
        url = 'method=';
    }
    let tempUrl = getCommonUrlParam(_self, _param, '1');
    url = url + tempUrl;
    if (_baseUrl && _baseUrl.indexOf('?') != -1) {
        url = _baseUrl + '&' + url;
    } else {
        url = _baseUrl + '?' + url;
    }

    let menuCode = caseMethod.getUrlParam('menuCode');
    if (menuCode) {
        url = url + '&menuCode=' + menuCode;
    }

    return encodeURI(url);
}

caseMethod.getResturl = getresturl;
caseMethod.synchroPost = function ( _baseUrl, _method, _param, _successFunc, _failFunc, _errorFunc, _type) {
    let _self = this;
    let tempType = 'POST';
    if (_type) {
        tempType = _type;
    }
    let url = getresturl(_baseUrl, _method, _param, _self);
    if (!url.startsWith('/')) {
        url = '/' + url;
    }
    $.ajaxSetup({cache: false});
    let post  =  {
        type: tempType,
        contentType: 'text/plain; charset=UTF-8',
        async: false,
        dataType: 'JSON',
        processData: false,
        success: function (data) {
            return successRequest(data, _successFunc, _failFunc, _errorFunc, _self);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (_self.$Spin) {
                _self.$Spin.hide();
            }
            try {
                let error = JSON.stringify(errorThrown);
                _self.alert(error, null, '2');
            } catch (e) {
                setTimeout(() => {
                    _self.alert(errorThrown, null, '2');
                }, 1000);
            }

            return false;// 系统异常
        }
    };
    if (!_param) {
        _param = {};
    }
    if (tempType === 'POST') {
        post.data = JSON.stringify(_param);
    } else {
        delete post.data;
    }
    $.ajax(url, post);
};
caseMethod.getOmdUrlConfig = function (_self) {
    $.ajax({
        url: '/amp-glod/config.json',
        type: 'GET',
        dataType: 'json',
        success: function(data) {
            let pageData=data;
            let obj = {};
            if (pageData) {
                for (let pro in pageData) {
                    if (pageData[pro] instanceof Array) {
                        pageData[pro].forEach(el => {
                            obj[el.name] = el.value;
                        });
                    } else {
                        obj[pro] = pageData[pro];
                    }
                }
            }
            _self.config.globalProperties.OmdUrl = Object.assign({}, _self.config.globalProperties.OmdUrl, obj);
        }
    });
};
caseMethod.getPortalConfig = function (_self) {
    $.ajax({
        url: '/ampOpenapiService?method=usercenter.portal.getConfig',
        type: 'POST',
        data: {},
        dataType: 'json',
        success: function(res) {
            if (res.returncode == 0) {
                if (res.data) {
                    if (res.data.OmdUrl) {
                        let OmdUrl = JSON.parse(res.data.OmdUrl);
                        _self.config.globalProperties.OmdUrl = Object.assign({}, _self.config.globalProperties.OmdUrl, OmdUrl);
                    }
                    _self.config.globalProperties.portalConfig = res.data;
                }
            }
        }
    });
}

function getCongouCookie(value) {
    if (!value)
        return '';
    try {
        let v = JSON.parse(value);
        v = v.state;
        if (v) {
            return v.split(':')[1];
        } else {
            return value;
        }
    } catch (e) {
        return value;
    }
}

caseMethod.getUserCode = function (v) {
    let that = null;
    if (!v) {
        that = this;
    } else {
        that = v;
    }
    let token = caseMethod.getToken(v);
    let portalkey = '';
    let usercode = '';
    portalkey = that.portalkey;
    usercode = that.OmdUrl.uid;
    if (token) {
        if(portalkey == 'congou'){
            usercode =  getCongouCookie(Cookies.get('user_code'));
        }
        else
        {
            if (Cookies.get('user_code')) {
                usercode =  Cookies.get('user_code');
            }
        }
    }
    return usercode;
};

caseMethod.getUserName = function (v) {
    let that = null;
    if (!v) {
        that = this;
    } else {
        that = v;
    }
    let token = caseMethod.getToken(v);
    let portalkey = '';
    let username = '';
    portalkey = that.portalkey;
    username = '[' + that.OmdUrl.uid + ']' + that.OmdUrl.uname;
    if (token) {
        if(portalkey == 'congou'){
            username = '[' + getCongouCookie(Cookies.get('user_code')) + ']' +	getCongouCookie(Cookies.get('user_name'));
        }
        else
        {
            if (Cookies.get('user_code')) {
                username = '[' + Cookies.get('user_code') + ']' +Cookies.get('user_name');
            }
        }
    }
    return username;
};

caseMethod.getPortalMkt =function() {
    let obj = {};
    obj.shopId = Cookies.get('shopId');
    obj.shopCode = Cookies.get('shopCode');
    obj.shopName = Cookies.get('shopName');
    return obj;
},
    caseMethod.getSession = function() {
        let obj = {};
        let user_name = caseMethod.getUserName();
        let user_code = caseMethod.getUserCode();
        let user_id = Cookies.get('user_id');
        let ent_id = caseMethod.getEnt_id();
        let token = caseMethod.getToken();
        if (user_name) {
            obj['user_name'] = user_name;
        } else {
            obj['user_name'] = '';
        }
        if (user_code) {
            obj['user_code'] = user_code;
        } else {
            obj['user_code'] = '';
        }
        if (user_id) {
            obj['user_id'] = user_id;
        } else {
            obj['user_id'] = '';
        }
        if (ent_id) {
            obj['ent_id'] = ent_id;
        } else {
            obj['ent_id'] = '';
        }
        if (token) {
            obj['token'] = token;
        } else {
            obj['token'] = '';
        }
        return JSON.stringify(obj);
    };

caseMethod.getUrlParam = function (name) {
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)'); // 构造一个含有目标参数的正则表达式对象

    let list = window.location.href.split('?');
    let r = '';
    if (list.length > 1) {
        r = list[1].match(reg);  // 匹配目标参数
    }
    if (!r) {
        if (list.length > 2) {
            r = list[2].match(reg);  // 匹配目标参数
        }
    }
    if (r) return decodeURI(r[2]); return ''; // 返回参数值
};

caseMethod.initGlobal  = function (_self, _obj, isInitUser)  {
    let OmdUrl = {};
    if (!_self.config.globalProperties.OmdUrl) {
        _self.config.globalProperties.OmdUrl = {};
    }
    if (_obj) {
        OmdUrl = Object.assign({},_self.config.globalProperties.OmdUrl, _obj);
    }
    let portalkey = caseMethod.getUrlParam('portalkey');
    if (portalkey) {
        OmdUrl.portalkey = portalkey;
    }
    OmdUrl.eid = caseMethod.getEnt_id(_self.config.globalProperties);

    OmdUrl.modulecode = caseMethod.getUrlParam('modulecode');
    if (! OmdUrl.modulecode) {
        OmdUrl.modulecode = caseMethod.getUrlParam('billmoduleid');
    }
    OmdUrl.helpindex = caseMethod.getUrlParam('helpindex');
    OmdUrl.billmoduleid =_self.config.globalProperties.modulecode;
    OmdUrl.openbillno = caseMethod.getUrlParam('billno');
    OmdUrl.opentaskid = caseMethod.getUrlParam('taskid');
    OmdUrl.nocheck = caseMethod.getUrlParam('nocheck')?caseMethod.getUrlParam('nocheck'):'N';
    _self.config.globalProperties.OmdUrl = Object.assign({}, _self.config.globalProperties.OmdUrl, OmdUrl);
    // caseMethod.getOmdUrlConfig(_self);
    caseMethod.getPortalConfig(_self);

};

caseMethod.getUserModuleMethod = function (curlmodulecode) {
    let reModuleMethod = null;
    let token = caseMethod.getToken();
    if (!token) {
        return reModuleMethod;
    }

    let modulecode = '';
    if (curlmodulecode) {
        modulecode = curlmodulecode;
    } else {
        modulecode = caseMethod.getUrlParam('modulecode');
        if (!modulecode) {
            return reModuleMethod;
        }
    }
    let portalUrl = '/mall-portal-rest/portalesb/ocmrest';
    if (this.OmdUrl && this.OmdUrl.portal) {
        portalUrl = this.OmdUrl.portal;
    }
    let srvkey = caseMethod.getUrlParam('srvkey');
    if (srvkey === 'cloud') {
        portalUrl = this.OmdUrl.mdm;
    }

    let param = {};
    param.token = token;
    param.modulecode = modulecode;
    this.synchroPost(portalUrl, 'runtime.modulesrivce.getUserModuleMethod',param, function(data) {
        reModuleMethod = data;
    }, null);
    return reModuleMethod;

};
caseMethod.checkModuleByToken = function () {
    let powerflag = false;
    let token = caseMethod.getToken();
    if (!token) {
        return powerflag;
    }
    let modulecode = caseMethod.getUrlParam('modulecode');
    if (!modulecode) {
        return powerflag;
    }
    if (!location.pathname) {
        return powerflag;
    }
    if(this.portalkey != 'congou') {
        return powerflag;
    }

    let portalUrl = '/mall-portal-rest/portalesb/ocmrest';
    if (this.OmdUrl.portal) {
        portalUrl = this.OmdUrl.portal;
    }

    let pathname = location.pathname;

    let searchParam = {
        'token': token,
        'modulecode': modulecode,
        'execmodule': pathname
    };
    let srvkey = caseMethod.getUrlParam('srvkey');
    if (srvkey === 'cloud') {
        portalUrl = this.OmdUrl.mdm;
    }
    let method = 'runtime.modulesrivce.checkmodulebytoken';
    this.synchroPost(portalUrl, method, searchParam, function(data) {
        if (data.flag === '-1') {
            powerflag = true;
        }
    }, null);
    return powerflag;
};

/*
caseMethod.getDict = function(str, _fields) {
    let fields = 'code,name';
    if (_fields) {
        fields = _fields;
    }
    let dictkey = str.split(',');
    let _dicData = {};
    let  str2 = [];
    for (let pro of dictkey) {
        let data = this.$Method.getLocalStorage('dictkey_' + pro);
        if (data) {
            _dicData[pro] = data;
        } else {
            str2.push(pro);
        }
    }
    if (str2.length > 0) {
        let searchParam = {
            fields: fields,
            dict_group_code: str2.join(',')
        };
        let self = this;
        this.synchroPost(this.OmdUrl.omp, 'omp.work.dict.getbydictgroupcode', searchParam,function(data) {
            for (let pro of str2) {
                self.$Method.setLocalStorage('dictkey_' + pro , data[pro], self.OmdUrl.dictExpire);
                _dicData[pro] = data[pro];
            }
        }, null);
    }
    return _dicData;
};
*/

caseMethod.getDict = function(str, _fields) {
    let fields = 'code,name';
    if (_fields) {
        fields = _fields;
    }
    let _dicData = {};
    let searchParam = {
        fields: fields,
        dict_group_code:str
    };
    this.synchroPost(this.OmdUrl.omp, 'omp.work.dict.getbydictgroupcode', searchParam,function(data) {
        _dicData = data;
    }, null);
    return _dicData;
};

caseMethod.setQueryConfig = function(obj) {
    Object.assign(this.query.Config, obj);
};
caseMethod.getQueryConfig = function (selectkey) {
    let config = null;
    if (this.query.Config[selectkey]) {
        config = JSON.parse(JSON.stringify(this.query.Config[selectkey]));
    } else {
        config = {};
    }
    if (config.width === undefined) {
        if (config.isTree) {
            config.width = 0.3;
        } else {
            config.width = 0.4;
        }
    }
    if (config.height === undefined) {
        config.height = 0.6;
    }
    if (config.responseId === undefined) {
        config.responseId = config.responseCode;
    }
    if (config.manualLoad === undefined) {
        config.manualLoad = true;
    }
    if (config.multiSelect === undefined) {
        config.multiSelect = false;
    }

    if (config.showCondition === undefined) {
        config.showCondition = true;
    }
    /*if (config.isTree) {
        config.popControl = 'SimpleTree';
    } else {
        config.popControl = 'SimpleViewGrid';
    }*/
    if (config.isConfig) {
        return config;
    } else {
        if (this.query.customQueryConfig) {
            return this.query.customQueryConfig(config);
        } else {
            return config;
        }
    }

};
caseMethod.getBillmoduleid = function(billtype) {
    let billmoduleid = '';
    let searchParam = {'billtype':billtype,'order_field' : 'modeid'};
    let method = 'mss.base.billmain.search';
    this.synchroPost(this.OmdUrl.mall, method,searchParam, function(data) {
        if(data && data.billmain && data.billmain.length >0){
            billmoduleid =data.billmain[0].modeid;
        }
    },null);
    return billmoduleid;
};
caseMethod.getBilltype = function(billmoduleid) {
    let billtype = '';
    let searchParam = {'modeid':billmoduleid};
    let method = 'mss.base.billmain.search';
    this.synchroPost(this.OmdUrl.mall, method,searchParam, function(data) {
        if(data && data.billmain && data.billmain.length >0){
            billtype =data.billmain[0].billtype;
        }
    },null);
    return billtype;
};
caseMethod.getHelpdocumenturl = function() {
    let url = '';
    let searchParam = {'queryid':'select_fgetmanapara','mpmkt':'00','mpcode':'HELPDOCUMENTURL'};
    let method = 'mss.work.report.query';
    this.synchroPost(this.OmdUrl.mall, method,searchParam, function(data) {
        if(data && data.report && data.report.length >0){
            url =data.report[0].mpvalue;
        }
    },null);
    return url;
};
caseMethod.getHelpId = function(helpType,helpIndex) {
    let helpId = '';
    let para = {};
    para.helpType = helpType;
    para.helpIndex = helpIndex;
    this.synchroPost(this.OmdUrl.amp, 'usercenter.helpconfig.getHelpId', para, function(data) {
        if(data && data.helpId){
            helpId = data.helpId
        }
    },function(data) {
        helpId= '';
    },function(data) {
        helpId= '';
    });
    return helpId;
};


caseMethod.getConditionValue = function (name, value, calculator, config) {
    let condition = {};
    if (calculator === '==') {
        if (config.type === 'DateBox') {
            condition[name] = {};
            let temp = {};
            temp['>='] = value;
            if (config.vtype === 'month') {
                temp['<'] = this.$Method.getNextMonthFirstDay(value);
            } else {
                temp['<'] = this.$Method.getTomorrow(value);
            }
            condition[name] = temp;
        } else {
            if (name === 'inputer' || name === 'auditor' || name === 'canceler') {
                let temp1 = {};
                temp1[name] = {'==':value};
                let temp2 = {};
                temp2[name+'_name'] = {'LIKE': '[%]' + value};
                condition['$or'] = [];
                condition['$or'].push(temp1);
                condition['$or'].push(temp2);
            } else {
                condition[name] = {};
                if (value.value !== undefined) {
                    condition[name][calculator] = value.value;
                } else {
                    condition[name][calculator] = value;
                }
            }
        }
    }

    if (calculator === 'LIKE') {
        condition[name] = {};
        condition[name][calculator] = '%' + value + '%';
    }

    if (calculator !== 'LIKE' && calculator !== '==') {
        condition[name] = {};
        condition[name][calculator] = value;
    }
    return condition;
};
caseMethod.getHelpUrl = function() {
    let url = '';
    if (this.helpindex) {
        let helpUrl = '';
        if (this.OmdUrl.helpUrl) {
            helpUrl = this.OmdUrl.helpUrl;
        } else {
            helpUrl = this.getHelpdocumenturl();
        }
        if (helpUrl) {
            url = 'http://'+helpUrl+'/web/#/'+this.OmdUrl.helpType+'?page_id='+ this.helpindex;
        }
    }
    return url;

};
caseMethod.getEnt_id = function(_self) {
    let ent_id = '';
    let portalkey = '';
    if (_self) {
        ent_id = _self.OmdUrl.eid;
        portalkey = _self.OmdUrl.portalkey;
    } else {
        ent_id = this.OmdUrl.eid;
        portalkey = this.OmdUrl.portalkey;
    }
    if (Cookies.get('ent_id') !== undefined && Cookies.get('ent_id') !== '') {
        ent_id = Cookies.get('ent_id');
    } else {
        let temp = caseMethod.getUrlParam('ent_id');
        if (temp !== undefined && temp !== '') {
            ent_id = temp;
        }
    }
    if (portalkey === 'cloud') {
        let lock_entid = caseMethod.getUrlParam('lock_entid');
        if (lock_entid !== undefined && lock_entid !== '') {
            ent_id = lock_entid;
        }
    }

    return ent_id;
};
caseMethod.getToken = function(_self) {
    let  token = '';
    if (!_self) {
        if (this.token) {
            token = this.token;
        }
    } else {
        if (_self.token) {
            token = _self.token;
        }
    }
    if (Cookies.get('token')) {
        token = Cookies.get('token');
    } else {
        let temp = caseMethod.getUrlParam('token');
        if (temp) {
            token = temp;
        }
    }
    return token;
};



caseMethod.getModulecode= function () {
    let  modulecode = '';
    modulecode = caseMethod.getUrlParam('modulecode');
    if (!modulecode) {
        modulecode = caseMethod.getUrlParam('billmoduleid');
    }
    return modulecode;
};
caseMethod.downloadFile = function(url, that) {

    if (!url) {
        return;
    }

    let xhr = new XMLHttpRequest();

    xhr.open('GET', url, true);    // 也可以使用POST方式，根据接口

    xhr.responseType = 'blob';  // 返回类型blob

    // 定义请求完成的处理函数，请求前也可以增加加载框/禁用下载按钮逻辑

    xhr.onload = function () {
        // 请求完成
        if (this.status === 200) {
            // 返回200
            let blob = this.response;
            let reader = new FileReader();
            let headerStr = decodeURI(this.getResponseHeader('content-disposition'));
            let filename = headerStr.replace('attachment;filename*=UTF-8\'\'','');
            filename = filename.replace('attachment;filename=','');
            // let filename = this.getAllResponseHeaders().split(';')[2].split('\n')[0].split('filename=')[1];
            reader.readAsDataURL(blob);  // 转换为base64，可以直接放入a表情href
            filename = decodeURIComponent(filename);
            //去除空格
            filename = filename.replace(/\ +/g,'');
            //去除换行回车
            filename = filename.replace(/[\r\n]/g,'');
            reader.onload = function () {

                // 转换完成，创建一个a标签用于下载

                let a = document.createElement('a');

                a.download = filename;


                //a.href = e.target.result;
                a.href = URL.createObjectURL(blob);

                $('body').append(a);  // 修复firefox中无法触发click
                that.$Spin.hide();
                a.click();

                $(a).remove();

            };

        } else {
            that.$Spin.hide();
            that.alert('导出失败');
        }

    };

    // 发送ajax请求

    xhr.send(new Blob());

};

caseMethod.exportExcelback = function (that) {
    if (that.child) {
        setTimeout(that.exportExcelback(that),100);
    } else {
        that.$Spin.hide();
    }
};

caseMethod.doExportExcel = function(_baseUrl,_method,_param,exportType,that){
    let url = _baseUrl;
    //filetyep:1 导出文件XlS filetype:2 导出文件XLSX 默认为2
    //_param.filetype = "1";
    if (!_param) {
        _param = {};
    }
    url = getresturl(url, _method, _param, that);
    let _paramStr = JSON.stringify(_param);
    _paramStr = _paramStr.replaceAll('#','%23');
    _paramStr = _paramStr.replaceAll('&','%26');
    _paramStr = _paramStr.replaceAll('+','%2B');
    //_paramStr = _paramStr.replaceAll(':','%3A');
    url = encodeURI(url + '&param=' + _paramStr);
    let userid = Cookies.get('user_id');
    let user_code = Cookies.get('user_code');
    if (userid) {
        url=url+encodeURI('&user_id='+userid);
    }
    if (user_code) {
        url=url+encodeURI('&user_code='+user_code);
    }
    that.$Spin.show({
        render: (h) => {
            return h('div', '导出中...,请勿关闭!');
        }
    });
    if (!exportType) {
        exportType = '2';
    }
    if(exportType === '2'){
        caseMethod.downloadFile(url, that);
    } else {
        const child = window.open(url,'_blank');
        var loop = setInterval(function () {
            if (child.closed) {
                that.$Spin.hide();
                clearInterval(loop);
            }
        }, 100);
        // setTimeout(caseMethod.exportExcelback(that),100);
    }
};

caseMethod.doExportReport= function(_baseUrl,_method,_param,that){
    let url = _baseUrl;
    if (!_param) {
        _param = {};
    }
    url = getresturl(url, _method, _param, that);
    let _paramStr = JSON.stringify(_param);
    _paramStr = _paramStr.replaceAll('#','%23');
    _paramStr = _paramStr.replaceAll('&','%26');
    _paramStr = _paramStr.replaceAll('+','%2B');
    url = encodeURI(url + '&param=' + _paramStr);
    that.$Spin.show({
        render: (h) => {
            return h('div', '导出中...,请勿关闭!');
        }
    });
    caseMethod.downloadFile(url, that);
};

caseMethod.doBillExport = function (baseUrl, method, param, ctx) {
    // 拼 URL
    const _param = Object.assign({}, param);
    const url = encodeURI(
        getresturl(baseUrl, method, _param, ctx) + '&param=' + JSON.stringify(_param)
    );

    // 显示加载动画
    ctx.$Spin.show({
        render: h => h('div', '导出中...,请勿关闭!')
    });

    caseMethod.downloadExcel(url, ctx, param);
};


caseMethod.downloadExcel = function (url, ctx, postObj = {}) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.responseType = 'blob';
    xhr.setRequestHeader('Content-Type', 'application/json');

    xhr.onload = function () {
        ctx.$Spin.hide();

        if (this.status !== 200) {
            ctx.alert(`导出失败：${this.status} ${this.statusText}`);
            return;
        }

        const blob = this.response;

        const reader = new FileReader();
        reader.onload = () => {
            let text = reader.result;

            try {
                const json = JSON.parse(text);
                if (json.returncode && json.returncode !== '0') {
                    ctx.alert(json.data || '导出失败');
                    return;
                }
            } catch (e) {
            }

            let filename = buildFilename(postObj, xhr);
            const a = document.createElement('a');
            a.href = URL.createObjectURL(blob);
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            setTimeout(() => document.body.removeChild(a), 120);
        };

        reader.readAsText(blob);
    };

    xhr.onerror = () => {
        ctx.$Spin.hide();
        ctx.alert('网络错误，导出失败');
    };

    xhr.send(JSON.stringify(postObj));
};

function buildFilename(postObj, xhr) {
    // 优先使用后端返回的 Content-Disposition 文件名
    let cd = xhr.getResponseHeader('content-disposition');
    if (cd && cd.includes('filename=')) {
        let match = cd.match(/filename\*=UTF-8''(.+)/i);
        if (match && match[1]) return decodeURIComponent(match[1]);

        let tmp = cd.split('filename=')[1];
        if (tmp) return tmp.replace(/["']/g, '');
    }

    // 默认文件名
    const now = new Date();
    const t = [
        now.getFullYear(),
        String(now.getMonth() + 1).padStart(2, '0'),
        String(now.getDate()).padStart(2, '0'),
        String(now.getHours()).padStart(2, '0'),
        String(now.getMinutes()).padStart(2, '0'),
        String(now.getSeconds()).padStart(2, '0')
    ].join('');

    const billmoduleid = postObj.billmoduleid || 'export';
    return `${t}${billmoduleid}.xls`;
}

caseMethod.getFilesInfo = function(billno, billmoduleid,notdelfile,scenetype, callBackMethod) {
    let usercode = caseMethod.getUserCode();
    let username = caseMethod.getUserName();
    let token =  caseMethod.getToken();
    let url = OmdUrl.getfile + 'billno=' + billno + '&billmoduleid=' + billmoduleid+'&scenetype=' + scenetype;
    let userInfo = '&usercode=' + usercode + '&username=' + username+'&token=' + token;
    if (notdelfile !== 'Y') {
        userInfo = userInfo + '&notdelfile=N';
    } else  {
        userInfo = userInfo + '&notdelfile=Y';
    }
    userInfo = encodeURI(userInfo);
    caseMethod.synchroPost(url, '', {}, (result) => {
        let data = [];
        if (result && result.length > 0) {
            result.forEach(el => {
                let obj = Object.assign({},{},el);
                obj.filename = el.filename;
                obj.filekey = el.filekey;
                obj.downUrl = OmdUrl.downfile + obj.filekey + userInfo;
                obj.delUrl = OmdUrl.delfile + obj.filekey + userInfo;
                obj.title = obj.filename;
                obj.url = obj.downUrl;
                obj.modflag = el.modflag;
                data.push(obj);
            });
        }
        callBackMethod(data);
    }, null, null, 'get');
};

caseMethod.getFilesInfoByIdkey = function(idkey, callBackMethod) {
    let usercode = caseMethod.getUserCode();
    let username = caseMethod.getUserName();
    let token =  caseMethod.getToken();
    let url = OmdUrl.getfile + 'idkey=' + idkey;
    let userInfo = '&usercode=' + usercode + '&username=' + username +'&token=' + token;
    userInfo = encodeURI(userInfo);
    caseMethod.synchroPost(url, '', {}, (result) => {
        let data = [];
        if (result && result.length > 0) {
            result.forEach(el => {
                let obj = Object.assign({},{},el);
                obj.filename = el.filename;
                obj.filekey = el.filekey;
                obj.downUrl = OmdUrl.downfile + obj.filekey + userInfo;
                obj.delUrl = OmdUrl.delfile + obj.filekey + userInfo;
                obj.title = obj.filename;
                obj.url = obj.downUrl;
                obj.modflag = el.modflag;
                data.push(obj);
            });
        }
        callBackMethod(data);
    }, null, null, 'get');
};
caseMethod.getFileInfo = function(filekey,callBackMethod) {
    let usercode = caseMethod.getUserCode();
    let username = caseMethod.getUserName();
    let token =  caseMethod.getToken();
    let url = OmdUrl.getfile + 'filekey=' + filekey;
    let userInfo = '&usercode=' + usercode + '&username=' + username +'&token=' + token;
    userInfo = encodeURI(userInfo);
    caseMethod.synchroPost(url, '', {}, (result) => {
        let data = [];
        if (result && result.length > 0) {
            result.forEach(el => {
                let obj = Object.assign({},{},el);
                obj.filename = el.filename;
                obj.filekey = el.filekey;
                obj.downUrl = OmdUrl.downfile + obj.filekey + userInfo;
                obj.delUrl = OmdUrl.delfile + obj.filekey + userInfo;
                obj.title = obj.filename;
                obj.url = obj.downUrl;
                obj.modflag = el.modflag;
                data.push(obj);
            });
        }
        callBackMethod(data);
    }, null, null, 'get');
};
caseMethod.setUrlSuffix = function(url,self) {
    let srvkey = caseMethod.getUrlParam('srvkey');
    let token = caseMethod.getUrlParam('token');
    let user_code = caseMethod.getUrlParam('usercode');
    let portalkey =  caseMethod.getUrlParam('portalkey')
    if (url) {
        if (url.indexOf('?') != -1) {
            return url +'&token='+token + '&srvkey=' + srvkey + '&app_key=' +self.OmdUrl.appKey + '&secret=' + self.OmdUrl.secret + '&portalkey=' + portalkey + '&usercode=' + user_code;
        } else {
            return url +'?token='+token + '&srvkey=' + srvkey + '&app_key=' +self.OmdUrl.appKey + '&secret=' + self.OmdUrl.secret + '&portalkey=' + portalkey + '&usercode=' + user_code;
        }
    }
    return url;
}
export default caseMethod;
