import CryptoJS from './aes.js';
import $http from "./https.js";
import httpConfig from "./httpConfig.js";
import QQMapWX from "./qqmap-wx-jssdk.min.js";
import {
    bem
} from './bem.js';
import {
    addUnit
} from './add-unit.js';
import {
    memoize
} from './memoize.js';
import Cache from "./cache.js";
const Utils = {
    resetGlobalDataParams(app, keys) {
        keys.map(item => {
            app.globalData[item] = ''
        })
    },
  //   setData: function(self, obj, callback) {
  //       let that = self;
  //       let keys = [];
  //       let val, data;
		// console.log('setData obj', obj)
  //       obj && Object.keys(obj).forEach(function(key) {
  //           keys = key.split('.');
  //           val = obj[key];
  //           data = that.$data;
		// 	console.log('setData data', data)
  //           keys.forEach(function(key2, index) {
  //               if (index + 1 == keys.length) {
  //                   that.$set(data, key2, val);
  //               } else {
  //                   if (!data[key2]) {
  //                       that.$set(data, key2, {});
  //                   }
  //               }
  //               data = data[key2];
  //           })
  //       });
  //       typeof callback == 'function' && callback()
  //   },
    showToast(title, icon, duration, callback) {
        uni.showToast({
            title: title,
            icon: icon ? icon : 'none',
            duration: duration ? duration : 2000,
            success() {
                typeof callback == 'function' && callback()
            }
        })
    },
    bem: memoize(bem),
    memoize: memoize,
    addUnit: addUnit,
	
	// 百度获取当前城市
	getBDCurrentCity(location) {
	    const self = this;
	    return new Promise((resolve, reject) => {
	        // 新建百度地图对象
	        var BMap = new bmap.BMapWX({
	            ak: httpConfig.bdMapAK
	        });
	        BMap.regeocoding({
	            location: location,
	            fail: function (data) {
	                // console.log('regeocoding', data)
	                reject(data);
	            },
	            success: function (res) {
	                // console.log(res)
	                if (res.originalData.result) {
	                    const province = res.originalData.result && res.originalData.result.addressComponent && res.originalData.result.addressComponent.province;
	                    const obj = {
	                        ...res.originalData.result.addressComponent,
	                        currentLatlng: location,
	                        province_short: province
	                    };
	                    Cache.set('currentLocationData', {currentLocation: obj});
	                    resolve(obj);
	                } else {
	                    reject(res);
	                }
	            },
	            iconPath: '../../img/marker_red.png',
	            iconTapPath: '../../img/marker_red.png'
	        });
	    });
	},
	// QQ获取当前城市
	getQQCurrentCity(location) {
	    const self = this;
	    return new Promise((resolve, reject) => {
	        // 实例化API核心类
	        const qqmapsdk = new QQMapWX({
	            key: httpConfig.qqmapKey // 必填
	        });
	
	        qqmapsdk.reverseGeocoder({
	            location: location || '',
	            //获取表单传入的位置坐标,不填默认当前位置,示例为string格式
	            //get_poi: 1, //是否返回周边POI列表：1.返回；0不返回(默认),非必须参数
	            sig: httpConfig.qqmapSk,
	            success: function (res) {
	                //成功后的回调
	                if (res.result) {
	                    const province = res.result && res.result.ad_info && res.result.ad_info.province;
	                    const obj = {
	                        ...res.result.ad_info,
	                        currentLatlng: location,
	                        province_short: province
	                    };
	                    Cache.set('currentLocationData', {currentLocation: obj});
	                    resolve(obj);
	                } else {
	                    reject(res);
	                }
	            },
	            fail(err) {
	                // console.log('geQQCurrentCity', err)
	                reject(err);
	            }
	        });
	    });
	},
	getIpLocationCityQQ() {
		const self = this;
		return new Promise((resolve, reject) => {
		    // 实例化API核心类
		    const qqmapsdk = new QQMapWX({
		        key: httpConfig.qqmapKey // 必填
		    });
			
		    qqmapsdk.getIpCity({
				ip: '',
		        sig: httpConfig.qqmapSk,
		        success: function (res) {
					console.log('getIpCity====', res)
		            //成功后的回调
		            if (res.result) {
		                const province = res.result && res.result.ad_info && res.result.ad_info.province;
		                const obj = {
		                    ...res.result.ad_info,
		                    currentLatlng: res.result.location.lat +','+ res.result.location.lng,
		                    province_short: province
		                };
		                Cache.set('currentLocationData', {currentLocation: obj});
		                resolve(obj);
		            } else {
		                reject(res);
		            }
		        },
		        fail(err) {
		            // console.log('geQQCurrentCity', err)
		            reject(err);
		        }
		    });
		});
	},
	// 获取当前位置
	getPositionLocation() {
	    const self = this;
	    return new Promise((resolve, reject) => {
	        self.getLocation()
	            .then((obj) => {
	                resolve(obj);
	            })
	            .catch((err) => {
	                console.log('startLocationUpdate error', err);
	                // 获取当前定位权限授权情况
	                uni.getSetting({
	                    success(resp) {
	                        console.log(resp.authSetting);
	                        if (resp.authSetting && resp.authSetting.hasOwnProperty('scope.userLocation') && !resp.authSetting['scope.userLocation']) {
	                            uni.showModal({
	                                title: '温馨提示',
	                                content: '您拒绝了定位权限，将无法获取当前城市就近医院推荐服务，点击去设置，及可设置再次设置。',
	                                cancelText: '取消',
	                                confirmText: '去设置',
	                                complete: (btn) => {
	                                    if (btn.confirm) {
	                                        // 打开设置页面
	                                        uni.openSetting({
	                                            success(respose) {
	                                                console.log(res.authSetting);
	                                                if (res.authSetting && res.authSetting.hasOwnProperty('scope.userLocation') && res.authSetting['scope.userLocation']) {
	                                                    // 再次获取定位数据
	                                                    self.getLocation()
	                                                        .then((obj) => {
	                                                            resolve(obj);
	                                                        })
	                                                        .catch((err) => {
	                                                            reject(err);
	                                                        });
	                                                } else {
	                                                    reject();
	                                                }
	                                            }
	                                        });
	                                    } else if (btn.cancel) {
	                                        reject(err);
	                                    }
	                                }
	                            });
	                        } else {
	                            reject();
	                        }
	                    }
	                });
	            });
	    });
	},
	// 再次获取定位数据
	getLocation() {
	    const self = this;
	    return new Promise(async (resolve, reject) => {
			//小程序使用小程序自带方法进行定位
			// #ifdef MP
	        uni.getLocation({
	            type: 'gcj02',
	            success: async (res) => {
	                const curentLatLng = res.latitude + ',' + res.longitude;
					// 腾讯
	                await self.getQQCurrentCity(curentLatLng).then((obj) => {
	                    resolve(obj);
	                });
	            },
	            fail(err) {
					console.log('fail', err)
	                reject(err);
	            }
	        });
			// #endif
			
			//web通过IP地址进行定位
			// #ifdef H5 
			await self.getIpLocationCityQQ()
				.then((obj) => {
					console.log('obj ===', obj)
					resolve(obj);
				})
				.catch(error => {
					console.log('error ===', error)
					reject(error)
				})
			// #endif
		});
	},

    // 获取URL参数
    getQueryString(url) {
        const params = url && url.split('?')[1]; // 获取查询字符串  
        const paramArr = params && params.split('&'); // 将查询字符串分割为参数数组  
        const paramObj = {};

        paramArr && paramArr.forEach((param) => {
            const [key, value] = param.split('='); // 将每个参数分割为键和值  
            paramObj[key] = value;
        });
        return paramObj
    },

    // 手机号隐藏中间四位
    phoneNumberEncryption(phoneNum) {
        return phoneNum.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    },

    // 身份证显示前三位以及后四位，中间用 * 代替
    identityCardEncryption(_Id_Card) {
        var _str_Start = _Id_Card.substr(0, 3);
        var _str_End = _Id_Card.substr(14, 4);
        var _ss = function() {
            var s = "";
            for (var i = 0; i < 18 - 7; i++) s += "*";
            return s;
        };
        var _str_Res = _str_Start + _ss() + _str_End;
        return _str_Res;
        // 身份证显示前两位以及出生年月
        // return IDCord.replace(/(\w)/g,function(a,b,c,d){return ((c>1&&c<6)||c>(IDCord.length-5))?'*':a});
    },

    // 去除字符串中的空格
    removeSpacesFromString(phoneNum) {
        if (!phoneNum) {
            return "";
        }
        return phoneNum.replace(/\s+/g, '');
    },

    // 给手机号添加空格
    phoneAddGap(phoneNum) {
        let regPhoneNum = phoneNum.replace(/(\d{3})(\d{4})/, "$1 $2 "); //添加空格
        return regPhoneNum;
    },

    // 通过身份证号获取年龄大小
    calculateAge(certificateNum, isDay) {
        let len = certificateNum ? certificateNum.length : 0
        let birthYearSpan = len === 15 ? 2 : 4;
        let year = (birthYearSpan === 2 ? '19' : '') + certificateNum.substr(6, birthYearSpan);
        let month = certificateNum.substr(6 + birthYearSpan, 2);
        let day = certificateNum.substr(8 + birthYearSpan, 2);

        let now = new Date();
        let monthFloor = ((now.getMonth() + 1) < parseInt(month, 10) || ((now.getMonth() + 1) === parseInt(month, 10) && now.getDate() < parseInt(day, 10))) ? 1 : 0;
        let age = now.getFullYear() - parseInt(year, 10) - monthFloor;

        if (isDay === "yes") { // 如果龄小于1岁需要输出天数则   isDay   传   yes
            if (age === 0) {
                //年龄小于1岁，计算天数。注意：此处必须使用new Date('yyyy/mm/dd')这种格式，将字符串转换为Date类型。
                // 如果用 new Date('yyyy-mm-dd')这种，会存在兼容性问题，在Chrome下好使，其它浏览器不好使。
                // 可以采用new Date(Date.parse(str.replace(/-/g,"/")))将yyyy-mm-dd转换为yyyy/mm/dd。
                let diffDay = Math.floor((new Date().getTime() - new Date(year + '/' + month + '/' + day + " 00:00:00").getTime()) / (24 * 60 * 60 * 1000));
                return diffDay + "天";
            } else {
                return age + "岁";
            }
        } else {
            return age
        }
    },

    // 截取出字符冲中route、code以及start对应的值
    interceptTheValueOfTheURL(url, type, symbol, childSymbol) {
        if (url && url.indexOf(symbol) !== -1) {
            let arr = url.split(symbol);
            for (var i = 0; i < arr.length; i++) {
                if (arr[i].split(childSymbol)[0] === type) {
                    if (url.indexOf("#") !== -1) {
                        return arr[i].split(childSymbol)[1].split("#")[0];
                    } else {
                        return arr[i].split(childSymbol)[1];
                    }
                }
            }
        } else {
            if (url && url.indexOf(":") !== -1) {
                return url.split(":")[1]
            } else {
                return ""
            }
        }
    },

    // 将时间戳转化为 YYYY-MM-DD hh:mm:ss格式 如果需要年月日时分秒则 type === YYYY-MM-DD hh:mm:ss 否则为年月日格式
    timestampToDateFormat(timeStamp, type) {
        var date = new Date(timeStamp),
            Y = date.getFullYear(),
            M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1),
            D = date.getDate(),
            h = date.getHours(),
            m = date.getMinutes(),
            s = date.getSeconds();
        if (type === "YYYY-MM-DD HH:mm:ss") {
            return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s;
        } else if (type === "年月") {
            return Y + '年' + M + '月';
        } else if (type === "YYYY-MM") {
            return Y + '-' + M;
        } else if (type === "YYYY-MM-DD") {
            return Y + '-' + M + '-' + D
        } else {
            return Y + '-' + M + '-' + D;
        }
    },

    // 获取近三月提起
    getLast3Month() {
        var now = new Date();
        var year = now.getFullYear();
        var month = now.getMonth() + 1; //0-11表示1-12月
        var day = now.getDate();
        var dateObj = {};
        if (parseInt(month) < 10) {
            month = "0" + month;
        }
        if (parseInt(day) < 10) {
            day = "0" + day;
        }
        dateObj.now = year + '-' + month + '-' + day;
        if (parseInt(month) == 1) { //如果是1月份，则取上一年的10月份
            dateObj.last = (parseInt(year) - 1) + '-10-' + day;
            return dateObj;
        }
        if (parseInt(month) == 2) { //如果是2月份，则取上一年的11月份
            dateObj.last = (parseInt(year) - 1) + '-11-' + day;
            return dateObj;
        }
        if (parseInt(month) == 3) { //如果是3月份，则取上一年的12月份
            dateObj.last = (parseInt(year) - 1) + '-12-' + day;
            return dateObj;
        }
        var preSize = new Date(year, parseInt(month) - 3, 0).getDate(); //开始时间所在月的总天数
        if (preSize < parseInt(day)) {
            // 开始时间所在月的总天数<本月总天数，比如当前是5月30日，在2月中没有30，则取下个月的第一天(3月1日)为开始时间
            let resultMonth = parseInt(month) - 2 < 10 ? ('0' + parseInt(month) - 2) : (parseInt(month) - 2);
            dateObj.last = year + '-' + resultMonth + '-01';
            return dateObj;
        }
        if (parseInt(month) <= 10) {
            dateObj.last = year + '-0' + (parseInt(month) - 3) + '-' + day;
            return dateObj;
        } else {
            dateObj.last = year + '-' + (parseInt(month) - 3) + '-' + day;
            return dateObj;
        }
    },

    // 近一个月日期
    getLastMonth() {
        var now = new Date();
        var year = now.getFullYear();
        var month = now.getMonth() + 1; //0-11表示1-12月
        var day = now.getDate();
        var dateObj = {};
        dateObj.now = year + '-' + month + '-' + day;
        var nowMonthDay = new Date(year, month, 0).getDate(); //当前月的总天数
        if (month - 1 <= 0) { //如果是1月，年数往前推一年<br>　　　　 
            dateObj.last = (year - 1) + '-' + 12 + '-' + day;
        } else {
            var lastMonthDay = new Date(year, (parseInt(month) - 1), 0).getDate();
            if (lastMonthDay < day) { //1个月前所在月的总天数小于现在的天日期
                if (day < nowMonthDay) { //当前天日期小于当前月总天数
                    dateObj.last = year + '-' + (month - 1) + '-' + (lastMonthDay - (nowMonthDay - day));
                } else {
                    dateObj.last = year + '-' + (month - 1) + '-' + lastMonthDay;
                }
            } else {
                dateObj.last = year + '-' + (month - 1) + '-' + day;
            }
        }
        return dateObj;
    },

    // 近一周
    getLastWeek() {
        var now = new Date();
        var year = now.getFullYear();
        var month = now.getMonth() + 1; //0-11表示1-12月
        var day = now.getDate();
        var dateObj = {};
        dateObj.now = year + '-' + month + '-' + day;
        if (day - 7 <= 0) { //如果在当月7日之前
            var lastMonthDay = new Date(year, (parseInt(month) - 1), 0).getDate(); //1周前所在月的总天数
            if (month - 1 <= 0) { //如果在当年的1月份
                dateObj.last = (year - 1) + '-' + 12 + '-' + (31 - (7 - day));
            } else {
                dateObj.last = year + '-' + (month - 1) + '-' + (lastMonthDay - (7 - day));
            }
        } else {
            dateObj.last = year + '-' + month + '-' + (day - 7);
        }
        return dateObj;
    },

    // 根据对象中的某个属性过滤数组对象
    uniqArr(data, keys) {
        let newArr = [];
        let objTemp = {};
        for (let i = 0; i < data.length; i++) {
            if (!objTemp[data[i][keys]]) {
                objTemp[data[i][keys]] = true;
                newArr.push(data[i]);
            }
        }
        return newArr;
    },

    // 函数节流
    throttle(fn, interval) {
        var enterTime = 0; //触发的时间
        var gapTime = interval || 300; //间隔时间，如果interval不传，则默认300ms
        return function() {
            var context = this;
            var backTime = new Date(); //第一次函数return即触发的时间
            var args = arguments; //保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
            if (backTime - enterTime > gapTime) {
                fn.call(context, ...args);
                enterTime = backTime; //赋值给第一次触发的时间，这样就保存了第二次触发的时间
            }
        };
    },

    // 函数防抖
    debounce(fn, interval) {
        var timer;
        var gapTime = interval || 300; //间隔时间，如果interval不传，则默认300ms
        return function() {
            clearTimeout(timer);
            var context = this;
            var args = arguments; //保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
            timer = setTimeout(function() {
                fn.call(context, ...args);
            }, gapTime);
        };
    },

    // AES字符串解密方法
    decrypt(str) {
        var key = CryptoJS.enc.Utf8.parse("1008615920908325");
        var iv = CryptoJS.enc.Utf8.parse("1008615920908325");
        var encryptedHexStr = CryptoJS.enc.Hex.parse(str);
        var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
        var decrypt = CryptoJS.AES.decrypt(srcs, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        })
        var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
        return decryptedStr.toString();
    },

    encrypt(str) {
        var key = CryptoJS.enc.Utf8.parse("1008615920908325");
        var iv = CryptoJS.enc.Utf8.parse("1008615920908325");
        var encrypted = '';
        var srcs = CryptoJS.enc.Utf8.parse(str);
        encrypted = CryptoJS.AES.encrypt(srcs, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        })
        return encrypted.ciphertext.toString();
    },

    // 将数字转换成周
    digitalConversionWeek(num) {
        switch (num) {
            case 1:
                return '一'
                break;
            case 2:
                return '二';
                break;
            case 3:
                return '三';
                break;
            case 4:
                return '四';
                break;
            case 5:
                return '五';
                break;
            case 6:
                return '六';
                break;
            default:
                return '日'
                break;
        }
    },

    ///修改消息状态并跳转
    changeStatus(ID, type) {
        let data = {
            params: [{
                data: [ID],
                userID: "P",
                statusID: '2'
            }]
        }
        $http.post("urlS", this, {
            namespace: "Y",
            code: "03100098",
            data: data,
            namespace: "Y",
            success: function(res) {
                if (+res.errorCode === 0) {
                    let homeMsgData = uni.getStorageSync('homeMsgData');
                    if (type === 'D') {
                        Cache.set('homeMsgData', {
                            ...homeMsgData,
                            isNewMsg: 'N',
                            statusID: '2'
                        });
                    }
                }
            }
        })
    },

    jumpLink(app, path, entertype) {
        // 跳转挂号问诊需要设置reservationEntrance
        if (path.indexOf("videoConsultation") > -1) {
            app.globalData.reservationEntrance = entertype;
        }
        if (path.indexOf("tabBar") !== -1) {
            uni.switchTab({
                url: path,
            })
        } else {
            uni.navigateTo({
                url: path,
            });
        }
    },
    // 通用的计算navBar高度的方法
    calNavBarHeight() {
        // 之前的高度都是(height*2 + 20)*2 - 2 rpx 所以 (x / 2 - 20 ) / 2就是计算后rpx
        const {
            statusBarHeight,
            screenWidth
        } = uni.getSystemInfoSync();
        const {
            top, // 胶囊上边到顶部距离
            bottom, // 胶囊下边到顶部距离
            height, // 胶囊高度
        } = uni.getMenuButtonBoundingClientRect();
        console.log('屏幕相关', statusBarHeight, screenWidth, top, bottom, height)
        // px转换为rpx
        const rate = 750 / screenWidth;
        // 计算真实的头部高度px为单位 操作按钮 + 上下间距 + 状态栏
        let navHeight = (top - statusBarHeight) * 2 + height + statusBarHeight;

        // 头部高度，真实高度
        navHeight = navHeight;
        console.log('头部高度', rate, navHeight)
        return {
            navHeight: navHeight, // (navHeight / 2 - 20) / 2 + 2
            statusBarHeight: statusBarHeight,
            //和右侧胶囊居中对齐的高度PX
            // (top - statusBarHeight) * 2  胶囊与标题栏上下边距和PX
            // (17 * rate / 2) 标题文字的高度PX
            navBottom: statusBarHeight % 2 > 0 ? statusBarHeight + 1 : statusBarHeight,
            navTitleHeight: (top - statusBarHeight) * 2 + height
        };
    },
    // 页面loading是否显示
    checkLoadStatus(arr) {
        if (arr.length == 0) return false;
        if (arr.indexOf(false) > -1) return true;
        return false
    },
    // 设置页面loading
    checkLoadStatusOpt(index, self) {
        self.checkLoadStatus[index] = true
        self.pageLoading = this.checkLoadStatus(self.checkLoadStatus)
        if (!self.pageLoading) {
            uni.hideLoading()
        }
    },
    toQueryPair(index, key, value) {
        if (typeof value == 'undefined') {
            return `${key}=`
        }
        if (index == 0) {
            return `?${key}=${value}`
        }
        return `&${key}=${value}`
    },
    // 医保移动支付获取授权码
    getAuthCode(app, detailParams) {
        console.log(app)
        return new Promise((resolve, reject) => {
            const userData = uni.getStorageSync('userData')
            const {
                platform,
                appId
            } = app.globalData;
            if (platform == 'alipay') {
                // 支付宝获取用户授权
                uni.getAuthCode({
                    scopes: ['nhsamp', 'auth_user'], // 主动授权：auth_user，静默授权：auth_base。或者其它scopes
                    success: (res) => {
                        if (res.authCode) {
                            const data = {
                                "params": [{
                                    "appID": appId,
                                    "authCode": res.authCode,
                                    "openID": userData.openID,
                                    "hospCode": userData.hisHospID,
                                    "patName": userData.patDesc,
                                    "idCardNo": userData.idCardNo,
                                    "callurl": 'alipays://platformapi/startapp?appId=2021004100602607&page=pages/order/pages/distributionInfo/distributionInfo?detailparams=' +
                                        detailParams
                                }]
                            }
                            // 请求医保业务授权接口，第一次请求获得授权页面链接，如果同意授权，第二次请求将获得auth_no、pay_auth_no、medicalCardInstId、medicalCardId
                            console.log('130996 params', data)
                            $http.post("urlS", self, {
                                code: '130996',
                                data: data,
                                namespace: "UPP",
                                HISFlag: "UPP",
                                UPPFlag: "Y",
                                success(res) {
                                    console.log('130996:', res)
                                    // my.ap.navigateToAlipayPage({
                                    //     path: encodeURI(
                                    //         'https://render.alipay.com/p/s/medical-card-online/www/online-pay.html?returnUrl=https%3A%2F%2Fnp.h03.p0551.com%2FUPP%2FUPPCallBack%2FALICallBack&openapiAppId=2021004100602607&reqBizNo=LTu7WLY2wPgecQ460x8vM2VkGZKZ930'
                                    //     )
                                    // })
                                    // return
                                    if (+res.errorCode == 0 && res.result.pay_auth_no) {
                                        app.globalData.authCode = res.result.accesstoken
                                        resolve()
                                    } else if (+res.errorCode == 0 && !res.result.pay_auth_no) {
                                        // 如果获得的是授权链接，则跳转到授权页进行授权
                                        my.ap.navigateToAlipayPage({
                                            path: encodeURI(res.result.auth_url)
                                        })
                                    }
                                }
                            })
                        }
                    },
                });
            } else {
                // 微信
                // 'auth/pages/bindcard/auth/index?openType=getAuthCode&bizType=04107&cityCode=520100&channel=AAGbUVPe4-yrNPoKWb89glCi&orgChnlCrtfCodg=BqK1kMStlhVDgN2uHf4EsLK/F2LjZPYJ81nK2eYQqxtZjEBBEZElR763esCd+Ia+&orgCodg=H52010200067&orgAppId=1GGTNBFT21BS3F60C80A00006F27AE4A'
                const pagePath = 'auth/pages/bindcard/auth/index'
                const userData = uni.getStorageSync('userData')
                if (!userData) {
                    uni.showToast({
                        icon: 'none',
                        title: '医保配置信息不存在，请退出重试！',
                    })
                    return
                }
                console.log(userData)
                const params = {
                    openType: 'getAuthCode',
                    bizType: userData.bizType,
                    cityCode: userData.cityCode, // 区域编码
                    channel: userData.channel, // 渠道号
                    orgChnlCrtfCodg: userData.orgChnlCrtfCodg, // 线上核验渠道线上编码
                    orgCodg: userData.orgCodg, // 线上核验定点医药机构编码
                    orgAppId: userData.orgAppId, // 线上核验业务类型编码
                    sourceapp: userData.sourceapp, // 当前应用AppID
                }
                console.log(params)
                let queryParam = ''
                const keys = Object.keys(params)
                for (let i = 0; i < keys.length; i++) {
                    console.log(this.toQueryPair(i, keys[i], params[keys[i]]))
                    queryParam += this.toQueryPair(i, keys[i], params[keys[i]])
                }
                console.log(pagePath + queryParam)
                uni.navigateToMiniProgram({
                    appId: 'wxe183cd55df4b4369',
                    path: pagePath + queryParam,
                    envVersion: userData.insuTestFlag == 'Y' ? 'trial' : 'release'
                });
            }
        })
    },
    // 处理异常订单
    abnormalOrderDeal(obj) {
        return new Promise((resolve, reject) => {
            const userData = uni.getStorageSync('userData')
            if (!userData) return
            let data = {
                params: [{
                    hospCode: userData.hisHospID,
                    userCode: 'wxsf'
                }]
            }
            if (obj.payTradeNum) data.params[0]['payTradeNum'] = obj.payTradeNum
            if (obj.prescribeTradeNum) data.params[0]['prescribeTradeNum'] = obj.prescribeTradeNum
            console.log('撤销订单入参')
            console.log(data)
            $http.post("urlS", this, {
                code: "130994",
                data: data,
                namespace: "UPP",
                success: function(res) {
                    console.log('撤销订单返回结果')
                    console.log(res)
                    if (+res.errorCode === 0) {
                        console.log('异常订单取消成功')
                        resolve()
                    } else {
                        uni.showToast({
                            icon: 'none',
                            title: res.errorMessage
                        });
                        reject()
                    }
                },
                error: function(error) {
                    reject(error)
                }
            });
        })
    },
    // 由于跳转到系统设置页无法监听用户最终是否打开系统定位及对支付宝授权位置信息，因此请在生命周期 onShow 中调用定位授权准备方法。
    authGuideLocation: async () => {
        const myGetSystemInfo = () => {
            return new Promise((resolve, reject) => {
                my.getSystemInfo({
                    success: resolve,
                    fail: reject
                });
            });
        };

        const myGetSetting = () => {
            return new Promise((resolve, reject) => {
                my.getSetting({
                    success: resolve,
                    fail: reject
                });
            });
        };

        const myOpenSetting = () => {
            return new Promise((resolve, reject) => {
                my.openSetting({
                    success: resolve,
                    fail: reject
                });
            });
        };

        const myAlert = (content) => {
            return new Promise((resolve, reject) => {
                my.alert({
                    content,
                    success: resolve,
                    fail: reject
                });
            });
        };

        // 获取用户是否开启系统定位及授权支付宝使用定位
        const isLocationEnabled = async () => {
            const systemInfo = await myGetSystemInfo();
            return !!(systemInfo.locationEnabled && systemInfo.locationAuthorized);
        };

        // 若用户未开启系统定位或未授权支付宝使用定位，则跳转至系统设置页
        const showAuthGuideIfNeeded = async () => {
            if (!(await isLocationEnabled())) {
                my.showAuthGuide({
                    authType: "LBS"
                });
                return false;
            }
            return true;
        };

        // 获取用户是否授权过当前小程序使用定位
        const isLocationMPAuthorized = async () => {
            const settingInfo = await myGetSetting();
            return settingInfo.authSetting.location === undefined || settingInfo.authSetting.location;
        };

        // 若用户未授权当前小程序使用定位，则引导用户跳转至小程序设置页开启定位权限
        const requestLocationPermission = async () => {
            await myAlert("如果用户之前拒绝授权当前小程序获取地理位置权限，将会弹出此弹窗，请根据需要替换文案。");
            const openSettingInfo = await myOpenSetting();
            return openSettingInfo.authSetting.location;
        };

        try {
            if (!(await showAuthGuideIfNeeded())) {
                return false;
            }
            if (await isLocationMPAuthorized()) {
                return true;
            }
            if (await requestLocationPermission()) {
                return true;
            }
            return false;
        } catch (error) {
            console.error(error);
            return false;
        }
    },
    getLatLong() {
        return new Promise((resolve, reject) => {
            this.authGuideLocation().then(res => {
                console.log(res);
                if (res === true) {
                    my.getLocation({
                        type: 0, // 获取经纬度和省市区县数据
                        success: (res) => {
                            resolve(res)
                        },
                        fail: (res) => {
                            reject(res)
                            my.alert({
                                title: '定位失败',
                                content: JSON.stringify(res)
                            });
                        },
                        complete: () => {},
                    });
                }
            })
        })
    },
	
	// 医保参数到设置缓存
	setInsuStorage(hospData) {
	    let userData = Cache.get('userData')
	    // 医保相关配置
	    let insuObj = {
	      insuType: hospData.insuType,
	      bizType: hospData.bizType,
	      cityCode: hospData.cityCode,
	      channel: hospData.channel,
	      orgChnlCrtfCodg: hospData.orgChnlCrtfCodg,
	      orgCodg: hospData.orgCodg,
	      orgAppId: hospData.orgAppId,
	      sourceapp: hospData.sourceapp,
	      insuTestFlag: hospData.insuTestFlag,
	      insuAcctSelect: hospData.insuAcctSelect,
	    }
	    userData = {
	      ...userData,
	      ...insuObj
	    }
	    // console.log('设置医保信息后的userData：', userData)
	    Cache.set('userData', userData)
	},
}
export default Utils;