import axios from 'axios';
// 对象的合并
export const containObject = function(...obj1) {
    let obj = Object.assign(...obj1)
    return obj
}
// 获取页面自适应高度
export function resizeHeight(cMinusHeight = 152, iMinuxHeight = 210, refHeightId = 'slidebar-container', 
    containerHeightId = 'screenSet'){
    let containerHeight = p_getElm(refHeightId).getBoundingClientRect().height - 15
    p_getElm(containerHeightId).style.height = containerHeight - cMinusHeight + 'px'
    window.onresize = function() {
        containerHeight = p_getElm(refHeightId).getBoundingClientRect().height - 15
        p_getElm(containerHeightId).style.height = containerHeight - cMinusHeight + 'px'
    }
}

function p_getElm(elmId){
    return document.getElementById(elmId)
}
//共通函数
Array.prototype.contains = function (obj) {
    if (this.length > 0) {
        for (let i = 0; i < this.length; i++) {
            if (obj === this[i]) {
                return true;
            }
        }
    }
    return false;
};

Array.prototype.remove = function (obj) {
    if (this.contains(obj)) {
        for (let i = 0; i < this.length; i++) {
            if (obj === this[i]) {
                this.splice(i, 1);
                break;
            }
        }
    }
    return this;
};

// 时间处理
Date.prototype.format = function (fmt) { // author: meizz
    let o = {
        "M+": this.getMonth() + 1, // 月份
        "d+": this.getDate(), // 日
        "h+": this.getHours(), // 小时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
        "S": this.getMilliseconds()
        // 毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
            .substr(4 - RegExp.$1.length));
    for (let k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

/**
 * base64编码
 * @param {Object} str
 */
export const base64encode = (str) => {
    let base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let out, i, len;
    let c1, c2, c3;
    len = str.length;
    i = 0;
    out = "";
    while (i < len) {
        c1 = str.charCodeAt(i++) & 0xff;
        if (i == len) {
            out += base64EncodeChars.charAt(c1 >> 2);
            out += base64EncodeChars.charAt((c1 & 0x3) << 4);
            out += "==";
            break;
        }
        c2 = str.charCodeAt(i++);
        if (i == len) {
            out += base64EncodeChars.charAt(c1 >> 2);
            out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            out += base64EncodeChars.charAt((c2 & 0xF) << 2);
            out += "=";
            break;
        }
        c3 = str.charCodeAt(i++);
        out += base64EncodeChars.charAt(c1 >> 2);
        out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
        out += base64EncodeChars.charAt(c3 & 0x3F);
    }
    return out;
};
/**
 * base64解码
 * @param {Object} str
 */
export const base64decode = (str) => {
    let base64DecodeChars = new Array(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);
    let c1, c2, c3, c4;
    let i, len, out;
    len = str.length;
    i = 0;
    out = "";
    while (i < len) {
        /* c1 */
        do {
            c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
        }
        while (i < len && c1 == -1);
        if (c1 == -1)
            break;
        /* c2 */
        do {
            c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
        }
        while (i < len && c2 == -1);
        if (c2 == -1)
            break;
        out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
        /* c3 */
        do {
            c3 = str.charCodeAt(i++) & 0xff;
            if (c3 == 61)
                return out;
            c3 = base64DecodeChars[c3];
        }
        while (i < len && c3 == -1);
        if (c3 == -1)
            break;
        out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
        /* c4 */
        do {
            c4 = str.charCodeAt(i++) & 0xff;
            if (c4 == 61)
                return out;
            c4 = base64DecodeChars[c4];
        }
        while (i < len && c4 == -1);
        if (c4 == -1)
            break;
        out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
    }
    return out;
};

/**
 * 时间秒数格式化
 * @param s 时间戳（单位：秒）
 * @returns {*} 格式化后的时分秒
 */
export const secToTime = (s) => {
    let t = "";
    if (s > -1) {
        // let hour = Math.floor(s/3600);
        let min = Math.floor(s / 60) % 60;
        let sec = s % 60;
        // if(hour < 10) {
        //     t = '0'+ hour + ":";
        // } else {
        //     t = hour + ":";
        // }

        if (min < 10) {
            t += "0";
        }
        t += min + ":";
        if (sec < 10) {
            t += "0";
        }
        t += sec.toFixed(0);
    }
    return t;
};

/**
 * 校验对象是否为空
 * */
export const isNotEmptyUtils = (obj) => {
    if ("" == obj || null == obj || undefined == obj || "null" == obj) {
        return false;
    }
    return true;
};

/**
 * 校验对象是否为空
 * */
export const isEmptyUtils = (obj) => {
    return !isNotEmptyUtils(obj);
};

/**
 * 校验数组是否为空
 * */
export const isEmptyList = (list) => {
    return (isEmptyUtils(list) || !(list instanceof Array) || list.length === 0);
};

/**
 * 校验数组是否为空
 * */
export const isNotEmptyList = (list) => {
    return !isEmptyList(list);
};


/**
 * 校验对象是否只包含数字0~9
 * * @param {String} [obj] 校验对象
 * */
export const isNumber = (obj) => {
    return (obj != null && obj.toString().match('^[0-9]*$') != null);
};

// 获取用户系统信息start
const detectOS = () => {
    let sUserAgent = navigator.userAgent;
    let isWin = (navigator.platform == "Win32")
        || (navigator.platform == "Windows");
    let isMac = (navigator.platform == "Mac68K")
        || (navigator.platform == "MacPPC")
        || (navigator.platform == "Macintosh")
        || (navigator.platform == "MacIntel");
    if (isMac)
        return "Mac";
    let isUnix = (navigator.platform == "X11") && !isWin && !isMac;
    if (isUnix)
        return "Unix";
    let isLinux = (String(navigator.platform).indexOf("Linux") > -1);
    if (isLinux)
        return "Linux";
    let isIos = (sUserAgent.indexOf("Mac OS X") > -1);
    if (isIos)
        return "Mac";
    if (isWin) {
        let isWinXP = sUserAgent.indexOf("Windows NT 5.1") > -1
            || sUserAgent.indexOf("Windows XP") > -1;
        if (isWinXP)
            return "WinXP";
        let isWinVista = sUserAgent.indexOf("Windows NT 6.0") > -1
            || sUserAgent.indexOf("Windows Vista") > -1;
        if (isWinVista)
            return "WinVista";
        let isWin7 = sUserAgent.indexOf("Windows NT 6.1") > -1
            || sUserAgent.indexOf("Windows 7") > -1;
        if (isWin7)
            return "Win7";
        let isWin8_1 = sUserAgent.indexOf("Windows NT 6.2") > -1
            || sUserAgent.indexOf("Windows 8") > -1;
        let isWin8_2 = sUserAgent.indexOf("Windows NT 6.3") > -1
            || sUserAgent.indexOf("Windows 8.1") > -1;
        if (isWin8_1 || isWin8_2)
            return "Win8";
        let isWin10_1 = sUserAgent.indexOf("Windows NT 6.4") > -1
            || sUserAgent.indexOf("Windows 10") > -1;
        let isWin10_2 = sUserAgent.indexOf("Windows NT 10.0") > -1
            || sUserAgent.indexOf("Windows 10") > -1;
        if (isWin10_1 || isWin10_2)
            return "Win10";
    }
    return "other";
};

// 获取用户浏览器信息
const getBrowser = () => {
    // let OsObject = "未知";
    // if (navigator.userAgent.indexOf("MSIE") > 0) {
    //     return "IE";
    // }
    // if (navigator.userAgent.indexOf("Firefox") > 0) {
    //     return "Firefox";
    // }
    // if (navigator.userAgent.indexOf("Chrome") > 0) {
    //     return "Chrome";
    // }
    // if (navigator.userAgent.indexOf("Safari") > 0) {
    //     return "Safari";
    // }
    // if (navigator.userAgent.indexOf("Gecko") > 0) {
    //     return "Gecko";
    // }
    return navigator.userAgent;
};

const GetLocalIPAddress = () => {
    // let url ='http://counter.sina.com.cn/ip/';
    // let url ='http://chaxun.1616.net/s.php?type=ip&output=json&callback=?&_='+Math.random();
    // let ip = "";
    // $.getJSON(url, function(data){
    //     localStorage.setItem("ipAddress",data.Ip);
    //     // check();
    // });
    // $.getScript('http://pv.sohu.com/cityjson?ie=utf-8', function () {
    return returnCitySN["cip"];
    // });
    // return ip;
};

// 获取用户终端信息
const getTerminalType = () => {
    let brow = "未知";
    // alert(navigator.userAgent);
    if (navigator.userAgent.indexOf('iPad') > -1) {
        // alert("iPad");
        return brow = "iPad";
    }
    if (navigator.userAgent.indexOf('Android') > -1
        || navigator.userAgent.indexOf('Linux') > -1) {
        // alert("Android");
        return brow = "android手机";
    }
    if (navigator.userAgent.indexOf('iPhone') > -1
    // || navigator.userAgent.indexOf('Mac') > -1
    ) {
        // alert("iPhone");
        return brow = "iPhone手机";
    }
    if (navigator.userAgent.indexOf('Trident') > -1) {
        // alert("Trident");
        return brow = "电脑";
    }
    if (navigator.userAgent.indexOf('Presto') > -1) {
        // alert("Presto");
        return brow = "电脑";
    }
    if (navigator.userAgent.indexOf('Chrome') > -1) {
        // alert("Chrome");
        return brow = "电脑";
    }
    if (navigator.userAgent.indexOf('AppleWebKit') > -1) {
        // alert("AppleWebKit");
        return brow = "iPad";
    }
    if (navigator.userAgent.indexOf('Gecko') > -1
        && navigator.userAgent.indexOf('KHTML') == -1) {
        // alert("Gecko");
        return brow = "电脑";
    }
    if (navigator.userAgent.indexOf("Mac OS X") > -1) {
        // alert("ios");
        return brow = "ios";
    }
    if (navigator.userAgent.indexOf('Safari') == -1) {
        // alert("Safari");
        return brow = "电脑";
    }
    return brow;
};

const initEnvironment = () => {
    let OS = detectOS();
    let browser = getBrowser();
    let ip = GetLocalIPAddress();
    let terminalType = getTerminalType();
    localStorage.setItem("OS", OS);
    localStorage.setItem("browser", browser);
    localStorage.setItem("ipAddress", ip);
    localStorage.setItem("terminalType", terminalType);
};

/**
 * str数据字符串,split分隔符
 * @param {String} [str] 当前vue对象
 * @param {String} [split] 当前vue对象
 * @return{Array} [array]
 * */
export const stringToArr = (str, split) => {
    if (isEmptyUtils(str) || isEmptyUtils(split) || str.indexOf(split) === -1) {
        return [str];
    } else {
        return str.split(split);
    }
};

//单点登录--start
/**
 * str数据字符串,split分隔符
 * @param {String} [str] url参数部分
 * @param {String} [split] 分隔符
 * @return{Array} [parArr] 返回键值对list
 * */
const getUrlParams = (str, split) => {
    let parArr = [];
    if (isEmptyUtils(str) || isEmptyUtils(split) || str.indexOf(split) === -1) {
        return parArr;
    } else {
        let parMapArray = str.split(split);
        if (parMapArray.length > 0) {
            for (let i = 0; i < parMapArray.length; i++) {
                if (parMapArray[i].indexOf("=") > -1) {
                    let item = parMapArray[i].split("=");
                    let par = {};
                    par[item[0]] = item[1];
                    parArr.push(par);
                }
            }
        }
        return parArr;
    }
};

/**
 * str数据字符串,split分隔符
 * @param {String} [str] url参数部分
 * @param {String} [split] 分隔符
 * @return{Map} [parMap] 返回键值对Map
 * */
export const getUrlParamsMap = (str, split) => {
    let parMap = new Map();
    if (isEmptyUtils(str) || isEmptyUtils(split) || str.indexOf(split) === -1) {
        return parMap;
    } else {
        let parMapArray = str.split(split);
        if (parMapArray.length > 0) {
            for (let i = 0; i < parMapArray.length; i++) {
                if (parMapArray[i].indexOf("=") > -1) {
                    let item = parMapArray[i].split("=");
                    parMap[item[0]] = item[1];
                }
            }
        }
        return parMap;
    }
};

export const ssoLogin = (href, paramMap) => {
    console.log("ssoLogin开始");
    if (isNotEmptyUtils(paramMap)) {
        if (isNotEmptyUtils(paramMap)) {
            for (var param in paramMap) {
                localStorage.setItem(param, paramMap[param]);
            }
        }
        //获取用户系统信息
        initEnvironment();
    }
};


//单点登录--end

//退出登录,跳转到登录页面
export const logout = () => {
    let url = localStorage.getItem("Url");
    let logoutUrl = localStorage.getItem("logoutUrl");
    let ssoLoginUrl = localStorage.getItem("ssoLogin");
    let ssoOriginUrl = localStorage.getItem("ssoOrigin");
    console.log('logoutUrl:'+logoutUrl)
/*    alert("ssoLogin Url:"+ ssoLoginUrl)
    alert("logOut url:" + logoutUrl)
    alert("ssoOrigin url:" + ssoOriginUrl);*/
    localStorage.clear();
    localStorage.setItem("Url", url);
    localStorage.setItem("logoutUrl", logoutUrl);
    localStorage.setItem("ssoLogin", ssoLoginUrl);
    localStorage.setItem("ssoOrigin", ssoOriginUrl);
    if (isEmptyUtils(logoutUrl)) {
        if(isEmptyUtils(ssoLoginUrl)){
            window.location.href =  localStorage.getItem("ssoOrigin")
                + "/PICA_SSO_FE/html/pica_login.html";
        }else{
            window.location.href = localStorage.getItem("ssoLogin");
        }
    } else {
        // window.location.href = logoutUrl;
        window.location.href =  localStorage.getItem("ssoOrigin")
            + "/PICA_SSO_FE/html/pica_login.html";
    }
};

/**
 * 消息提示 确定或取消
 * @param {Object} [self] 当前vue对象
 * @param {String} [title] 标题
 * @param {String} [content] 内容
 * @param {String} [confirmButton] 确认按钮文字
 * @param {Function} [confirmFunction] 按下确按钮认时,执行的函数
 * @param {String} [cancelButton] 取消按钮文字
 * @param {Function} [cancelFunction] 按取消按钮认时,执行的函数
 * @param {String} [messageType] 消息类型 success,info,warning,error
 * */
export const messageBox = (self, title, content, confirmButton, confirmFunction, cancelButton, cancelFunction, messageType) => {
    let titleText = title ? title : '提示';
    let contentText = content ? content : '';
    let confirmButtonText = confirmButton ? confirmButton : '确定';
    let type = messageType ? messageType : 'info';
    let typeArray = ["error", "warning", "info", "success"];
    if (!typeArray.contains(type)) {
        type = "info";
    }

    if (isNotEmptyUtils(cancelButton)) {
        self.$confirm(contentText, titleText, {
            confirmButtonText: confirmButtonText,
            cancelButtonText: cancelButton,
            type: type
        }).then(() => {
            // self.$message({
            //     type: 'success',
            //     message: '删除成功!'
            // });
            if (confirmFunction instanceof Function) {
                confirmFunction();
            }
        }).catch(() => {
            // self.$message({
            //     type: 'info',
            //     message: '已取消删除'
            // });
            if (cancelFunction instanceof Function) {
                cancelFunction();
            }
        });
    } else {
        self.$alert(contentText, titleText, {
            confirmButtonText: confirmButtonText,
            type: type,
            callback: action => {
                // self.$message({
                //     type: 'info',
                //     message: `action: ${ action }`
                // });
                if (confirmFunction instanceof Function) {
                    confirmFunction();
                }
            }
        });
    }
};

/**
 * 消息提示(支持html内容) 确定或取消
 * @param {Object} [self] 当前vue对象
 * @param {String} [title] 标题
 * @param {String} [content] 内容
 * @param {String} [confirmButton] 确认按钮文字
 * @param {Function} [confirmFunction] 按下确按钮认时,执行的函数
 * @param {String} [cancelButton] 取消按钮文字
 * @param {Function} [cancelFunction] 按取消按钮认时,执行的函数
 * @param {String} [messageType] 消息类型 success,info,warning,error
 * */
export const htmlMessageBox = (self, title, content, confirmButton, confirmFunction, cancelButton, cancelFunction, messageType) => {
    let titleText = title ? title : '提示';
    let contentText = content ? content : '';
    let confirmButtonText = confirmButton ? confirmButton : '确定';
    let type = messageType ? messageType : 'info';
    let typeArray = ["error", "warning", "info", "success"];
    if (!typeArray.contains(type)) {
        type = "info";
    }

    // debugger
    if (isNotEmptyUtils(cancelButton)) {
        self.$confirm(contentText, titleText, {
            confirmButtonText: confirmButtonText,
            cancelButtonText: cancelButton,
            dangerouslyUseHTMLString: true,//是否将 message 属性作为 HTML 片段处理
            type: type
        }).then(() => {
            if (confirmFunction instanceof Function) {
                confirmFunction();
            }
        }).catch(() => {
            if (cancelFunction instanceof Function) {
                cancelFunction();
            }
        });
    } else {
        self.$alert(contentText, titleText, {
            confirmButtonText: confirmButtonText,
            dangerouslyUseHTMLString: true,//是否将 message 属性作为 HTML 片段处理
            type: type,
            callback: action => {
                // self.$message({
                //     type: 'info',
                //     message: `action: ${ action }`
                // });
                if (confirmFunction instanceof Function) {
                    confirmFunction();
                }
            }
        });
    }
};


/**
 *请求失败时判断
 *
 * @param {Object} [error] 后台返回的信息
 * @param {Object} [self] 当前vue对象
 * */
export const errorResponseCheck = (error, self) => {
    closeLoading(self);
    console.log(error);
    setTimeout(function () {
        let code = error ? (error.response ? error.response.data : 0) : 0;
        // console.log("请求失败:%s", code);
        if (code == '40011') {
            messageBox(self, "登录", "登录失效，请重新登录！", "是", function () {
                logout();
            }, "", null);
            setTimeout(function () {
                logout();
            }, 2000);
        } else if (code == '40013') {
            messageBox(self, "提示", "刷新太过频繁，休息一下！", "是", function () {

            }, "", null);
            // setTimeout(function () {
            //
            // }, 2000);
        } else {
            //sendErrorReport(code);
            // messageBox(self, "提示", "操作失败！", "确定", function () {
            //
            // }, "", null, "error");
            self.$message.error("操作失败");
        }
    }, 100)

};

//截位
export const subString = (obj, int) => {
    if (isEmptyUtils(obj) || isEmptyUtils(int)) {
        return "";
    }
    if (obj.length <= int) {
        return obj;
    } else {
        obj = obj.substring(0, int);
    }

    return obj;
};

/**
 * 打开loading
 * @param {Object} [self] 当前this对象
 * @return 当前loading对象
 * */
export const openLoading = (self, customClass) => {
    const options = {
        lock: true,
        text: 'Loading',
        // target:'#bodyContent',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
    };
    if(customClass){
        options.customClass = customClass;
    }
    self.elLoadingId = self.$loading(options);
    return self.elLoadingId;
};

/**
 * 关闭loading
 * @param {Object} [self] 当前this对象
 * @return 当前loading对象
 * */
export const closeLoading = (self) => {
    if (self.elLoadingId) {
        self.elLoadingId.close();
    }
};

/**
 * 获取常量集合
 *
 *
 * @param {Object} [self] 当前this对象
 * @param {Object} [codeObject] 例如:codeObject={list1:"P097",list2:"P097"}
 * */
export const getConstantList = (self, codeObject) => {
    if (!codeObject instanceof Object) {
        return;
    }
    let req = {
        params: {
            numMap: JSON.stringify(codeObject)
        }
    };
    self.$axios.get(
        localStorage.getItem("msUrl") + "constants"
        , req
    ).then(function (res) {
        let map = JSON.parse(JSON.stringify(res.data.data));//通过这个实现深拷贝
        for (let key  in map) {
            self[key] = map[key];
        }
    });
};


export const initDepartment = (self, obj, type) => {
    if (!obj instanceof Object) {
        return;
    }
    var num = {
        id: obj,
        type: type
    }
    axios.create().post(
        localStorage.getItem("kfUrl") + "PICAAddressHospitalServiceImpl/postDepartmentList",
        num
    ).then(function (res) {
        let list = JSON.parse(JSON.stringify(res.data.departmentList));//通过这个实现深拷贝
        if (obj == -1) {
            self.departmentListP = list;
        } else {
            self.departmentList = list;
        }

        if (type == 'childGetChildList') {
            self.departmentPid = getPdepartmentId(self,'model','departmentId');
        }
    });
};

export const getPdepartmentId = (self) =>{
    if(isNotEmptyList(self.model.departmentId)
        || !self.departmentList instanceof  Array) {
        return null;
    }
    if(self.departmentList.length>0) {
        return self.departmentList[0].parent_id;
    }else{
        return -1;
    }
};


export const getObjectIdsStr = (list, key) => {
    if (isEmptyUtils(list)) {
        return ''
    }
    let strRet = '';
    for (let temp of list) {
        strRet = strRet + temp[key] + ',';
    }
    return strRet;
}


export const getPositionList = (provinceId,cityId,countyId,townId) => {
    return new Promise(function (resolve, reject) {
        var num = {
            provinceId,
            cityId,
            countyId,
            townId
        }
        axios.create().post(
            localStorage.getItem("kfUrl") + "combineHospital/getPositionList",
            num
        ).then(function (res) {
            resolve(res);
        }).then(function (res) {
            reject(res);
        });
    });
};

export const setOptionLabel = (self,selfModel,selfEId,selfEName,list,listEId,listEName) => {
    if (isEmptyList(list) || isEmptyUtils(listEId) || isEmptyUtils(listEName)) {
        return ;
    }
    for (let i = 0; i < list.length; i++) {
        if(list[i][listEId] == self[selfModel][selfEId]){
            self[selfModel][selfEName] = list[i][listEName];
            break;
        }
    }
    return;
};
