import * as API from './API';

let APP = getApp();
let FUNCTION_TEXT = 'function';
/*判断是否iphonex*/
function isIPhoneX() {
	let screenHeight = wx.getSystemInfoSync().screenHeight
	let bottom = wx.getSystemInfoSync().safeArea.bottom
	return screenHeight !== bottom
}
	
/*获取当前页url*/
function getCurrentPageUrl() {
	var pages = getCurrentPages()
	var currentPage = pages[pages.length - 1]
	var url = currentPage.route
	return url
}

/*获取当前页带参数的url*/
function getCurrentPageUrlWithArgs() {
	var pages = getCurrentPages()
	var currentPage = pages[pages.length - 1]
	var url = currentPage.route
	var options = currentPage.options
	var urlWithArgs = url + '?'
	for (var key in options) {
		var value = options[key]
		urlWithArgs += key + '=' + value + '&'
	}
	urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
	return urlWithArgs
}

/**
 * 无图标，纯文本Toast提示
 */
function showToastNoneIcon(title) {
	if (title == undefined || title == '') {
		title = '';
	}
	return wx.showToast({
		title: title,
		icon: 'none',
	});
}
/**
 * 显示Modal弹框（无取消按钮，只显示）
 * @param {标题} title 
 * @param {内容} content 
 * @param {按钮文字，默认确定} confirmText 
 */
function showModalNoneCancel(title, content, confirmText) {
	wx.showModal({
		title: title,
		showCancel: false,
		content: content,
		confirmText: (typeof confirmText == 'undefined' || confirmText == '') ? '确定' : confirmText,
		success: function (e) {

		}
	})
}
/**
 * 显示完整的Modal弹框提示
 * @param {标题} title 
 * @param {内容} content 
 * @param {确认} confirmText 
 * @param {取消} cancelText 
 * @param {回调} param4 
 */
function showModalOnClick(title, content, confirmText, cancelText, { confirm, cancel }) {
	wx.showModal({
		title: title,
		content: content,
		confirmText: (typeof confirmText == 'undefined' || confirmText == '') ? '确定' : confirmText,
		cancelText: (typeof cancelText == 'undefined' || cancelText == '') ? '取消' : cancelText,
		success: function (e) {
			if (e.confirm) {
				confirm();
			} else if (e.cancel) {
				cancel();
			}

		}
	})
}
/**
 * 有背景图层的loading
 *  * @param {内容} content 
 */
function showLoadingHaveMask(content) {
	wx.showLoading({
		title: (typeof content == "undefined" || content == '') ? '加载中...' : content,
		mask: true
	})
}
/**
 * 隐藏loading
 */
function hideLoadingHaveMask() {
	wx.hideLoading();
}

/**
 * 全局通用网络请求方法,默认post传输
 */
function httpRequest(url, data, {
	success,
	fail,
	complete
}) {
	wx.showNavigationBarLoading();
	let finalData = {};
	Object.assign(finalData, data);

  finalData.token = getApp().globalData.userInfo.token;
	wx.request({
		url,
    	data: finalData,
		method:data.method,
		timeout: 60000,
		header: {
      'Authorization':'Bearer '+getApp().globalData.userInfo.token
		},
		success: function (response) {
			if (response.data && response.data._code == API.INVALID_USER_TOKEN_CODE) {
				//微信登陆失效
				showToastNoneIcon(API.MSG_INVALID_USER_TOKEN);
				wx.navigateTo({
					url: API.USER_LOGIN_PAGE_PATH,
				})

			} else if (typeof success === FUNCTION_TEXT) {
				success(response.data);
			}
		},
		fail: function (response) {
			if (typeof fail === FUNCTION_TEXT) {
				fail(handleFail(response));
			} else {
				showToastNoneIcon(API.MSG_FAIL_HTTP);
			}
		},
		complete: function (response) {
			if (typeof complete === FUNCTION_TEXT) {
				if (response.data && response.data._code == API.SUCCESS_CODE) {
					complete(response.data);
				} else {
					complete(handleFail(response.data));
				}
			}
			wx.hideNavigationBarLoading();
		}
	})
}
/**
 * 网络访问（无其他处理）
 * @param {地址} url 
 * @param {参数} data 
 * @param {方法 get or post} method 
 * @param {回调} param3 
 */
function httpRequestNoneDetal(url, data, method, {
	success,
	fail,
	complete
}) {
	wx.showNavigationBarLoading();
	wx.request({
		url,
		data: data,
		method: method,
		success: function (response) {
			if (typeof success === FUNCTION_TEXT) {
				success(response.data);
			}
		},
		fail: function (response) {
			if (typeof fail === FUNCTION_TEXT) {
				fail(handleFail(response));
			} else {
				showToastNoneIcon(API.MSG_FAIL_HTTP);
			}
		},
		complete: function (response) {
			if (typeof complete === FUNCTION_TEXT) {
				if (response.data && response.data._code == API.SUCCESS_CODE) {
					complete(response.data);
				} else {
					complete(handleFail(response.data));
				}
			}
			wx.hideNavigationBarLoading();
		}
	})

}
/**
 * 调用失败
 */
function handleFail(data = '') {
	let { _msg = API.MSG_FAIL_HTTP, _code = 10001, _data = '', } = data;
	return {
		_code,
		_data,
		_msg
	}
}
/**
 * 微信授权  获取信息
 */
// function initSQFromWX() {
// 	let that = this;
// 	wx.getSetting({
// 		success(res) {

// 			// if (res.authSetting['scope.userInfo']) {
// 			// 	console.log('个人信息：authSetting 已授权');
// 			// } else {
// 			// 	console.log('个人信息：authSetting 未授权');
// 			// }
// 			if (res.authSetting['scope.userLocation']) {
// 				//定位已开启,暂不做功能处理
// 				console.log('定位：authSetting 已授权');
// 				getApp().globalData.setInfo.locationOpenIdWX = true;
// 			} else {
// 				//定位未开启，申请授权
// 				wx.authorize({
// 					scope: 'scope.userLocation',
// 					success() {
// 						//定位已开启，暂不做功能处理
// 						console.log('定位：wx.authorize success');
// 						getApp().globalData.setInfo.locationOpenIdWX = true;
// 					}
// 					,
// 					fail() {
// 						//如果之前已经拒绝过，直接返回fail 不弹窗
// 						console.log('定位：wx.authorize fail');
// 						getApp().globalData.setInfo.locationOpenIdWX = false;
// 						wx.navigateTo({
// 							url: '/pages/wxAuth/wxAuth',
// 						})

// 					}

// 				})

// 			}
// 		},
// 		fail(e) {
// 		},
// 		complete() {
// 		}
// 	});
// }

/**
 * 获取微信Code  
 */
function getCOdeFromWX({ complate }) {
	showLoadingHaveMask('正在加载数据..');
	wx.login({
		success: function (data) {
			complate(data.code);
			hideLoadingHaveMask()
		},
		fail: function (err) {
			hideLoadingHaveMask();
			showModalNoneCancel("温馨提示", "登陆失败，建议请重新打开小程序")
		}
	})
}
/**
 * ，获取到的微信用户信息（昵称、头像、省市 赋值给globalData.wxUserInfo)
 */
function getUserInfoFomWX() {
	wx.getUserProfile({
		desc: '用于完善会员资料',
		success: res => {
			getApp().globalData.wxUserInfo.nickName = res.userInfo.nickName;
			getApp().globalData.wxUserInfo.avatarUrl = res.userInfo.avatarUrl;
			//不再返回 强制返回“”
			// getApp().globalData.wxUserInfo.province = res.userInfo.province;
			// getApp().globalData.wxUserInfo.city = res.userInfo.city;
			console.log("获取到个人信息：" + res.userInfo.nickName);
			success(res);
		},
		complete: res => {
		}

	})
}
/**
 * 获取地理位置
 * @param {回调} param0 
 */
function getLocationFromWX({ success, fail }) {
	// wx.getLocation({
	// 	type: 'wgs84',
	// 	success(res) {
	// 		getApp().globalData.setInfo.latitude = res.latitude;
	// 		getApp().globalData.setInfo.longitude = res.longitude;
	// 		success();
	// 	}
	// 	, fail(res) {
	// 		showToastNoneIcon('获取地理信息失败');
	// 		fail(res);
	// 	}
	// })

}


function convert_length(length) {
	return Math.round(wx.getSystemInfoSync().windowWidth * length / 750);
}
/**
 * 比较版本号（参数'1.11.0', '1.9.9'，返回1）
 * @param {*} v1 
 * @param {*} v2 
 */
function compareVersion(v1, v2) {
	v1 = v1.split('.')
	v2 = v2.split('.')
	const len = Math.max(v1.length, v2.length)
  
	while (v1.length < len) {
	  v1.push('0')
	}
	while (v2.length < len) {
	  v2.push('0')
	}
  
	for (let i = 0; i < len; i++) {
	  const num1 = parseInt(v1[i])
	  const num2 = parseInt(v2[i])
  
	  if (num1 > num2) {
		return 1
	  } else if (num1 < num2) {
		return -1
	  }
	}
	return 0
  }
  /**
   * 获取当前年-月-日 时:分:秒
   */
function js_date_time(unixtime) {
  var date = new Date(unixtime);
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  m = m < 10 ? ('0' + m) : m;
  var d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  var h = date.getHours();
  h = h < 10 ? ('0' + h) : h;
  var minute = date.getMinutes();
  var second = date.getSeconds();
  minute = minute < 10 ? ('0' + minute) : minute;
  second = second < 10 ? ('0' + second) : second;
  // return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;//年月日时分秒
  return y + '-' + m + '-' + d + ' ' + h + ':' + minute;
}
/**
 * 获取当前年-月-日
 */
function formatDate(unixtime) {
  var date = new Date(unixtime);
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  m = m < 10 ? ('0' + m) : m;
  var d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  var h = date.getHours();
  h = h < 10 ? ('0' + h) : h;
  var minute = date.getMinutes();
  var second = date.getSeconds();
  minute = minute < 10 ? ('0' + minute) : minute;
  second = second < 10 ? ('0' + second) : second;
  // return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;//年月日时分秒
  return y + '-' + m + '-' + d;
}
/**
 * 获取当前年-月-日
 */
function formatDates(unixtime) {
	var date = new Date(unixtime);
	var y = date.getFullYear();
	var m = date.getMonth() + 1;
	m = m < 10 ? ('0' + m) : m;
	var d = date.getDate();
	d = d < 10 ? ('0' + d) : d;
	var h = date.getHours();
	h = h < 10 ? ('0' + h) : h;
	var minute = date.getMinutes();
	var second = date.getSeconds();
	minute = minute < 10 ? ('0' + minute) : minute;
	second = second < 10 ? ('0' + second) : second;
	// return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;//年月日时分秒
	return y + '-' + m;
}
/**
 * 将数字（整数）转为汉字
 * @param num 
 * @description 从零到一亿亿，需要小数的可自行截取小数点后面的数字直接替换对应arr1的读法就行了
 */
function convertToChinaNum (num) {
  var arr1 = new Array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
    var arr2 = new Array('', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千','万', '十', '百', '千','亿');//可继续追加更高位转换值
    if(!num || isNaN(num)){
        return "零";
    }
    var english = num.toString().split("")
    var result = "";
    for (var i = 0; i < english.length; i++) {
        var des_i = english.length - 1 - i;//倒序排列设值
        result = arr2[i] + result;
        var arr1_index = english[des_i];
        result = arr1[arr1_index] + result;
    }
    //将【零千、零百】换成【零】 【十零】换成【十】
    result = result.replace(/零(千|百|十)/g, '零').replace(/十零/g, '十');
    //合并中间多个零为一个零
    result = result.replace(/零+/g, '零');
    //将【零亿】换成【亿】【零万】换成【万】
    result = result.replace(/零亿/g, '亿').replace(/零万/g, '万');
    //将【亿万】换成【亿】
    result = result.replace(/亿万/g, '亿');
    //移除末尾的零
    result = result.replace(/零+$/, '')
    //将【零一十】换成【零十】
    //result = result.replace(/零一十/g, '零十');//貌似正规读法是零一十
    //将【一十】换成【十】
    result = result.replace(/^一十/g, '十');
    return result;
}
function getTransform(dictValue,options){
  var dictLabel2 = "";
  options.map(item=>{
    if(item.dictValue == dictValue){
      dictLabel2 = item.dictLabel
    }
  })
  return dictLabel2;
}
export {
	getCurrentPageUrl,
	getCurrentPageUrlWithArgs,
	showToastNoneIcon,
	showModalNoneCancel,
	showModalOnClick,
	showLoadingHaveMask,
	hideLoadingHaveMask,
	httpRequest,
	httpRequestNoneDetal,
	getCOdeFromWX,
	getLocationFromWX,
	getUserInfoFomWX,
	convert_length,
  isIPhoneX,
  js_date_time,
  formatDate,
	formatDates,
  convertToChinaNum,
  getTransform
}
