function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function (n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
/**
 * 把数字超过1万的值转成 “1.23万”格式
 * @param num   数值
 * @returns {string}
 */
function format_num(num){
    if (num == 0){
        return num;
    }
    if ((''+num).indexOf('.') != -1){
        var nums = (''+num).split('.');
        if ((''+nums[0]).length > 4){
            return (parseInt(nums[0]) / 10000).toFixed(2) + "万";
        }
        return num;
    } else {
        if ((''+num).length > 4){
            return (parseInt(num) / 10000).toFixed(2)+ "万";
        }
        return num;
    }
}

function InitTime(endtime, type){
    var dd,hh,mm,ss = null;
    var time = parseInt(endtime) - parseInt(new Date().getTime() / 1000);
    if(time<=0){
        return '结束'
    }else{
        dd = Math.floor(time / 60 / 60 / 24);
        hh = Math.floor((time / 60 / 60) % 24);
        mm = Math.floor((time / 60) % 60);
        ss = Math.floor(time  % 60);
		var str = '';
		if (dd > 0)
			str = dd+"天"+hh+"小时"+mm+"分"+ss+"秒";
		else{
			str = type == 1 ? hh+"小时"+mm+"分"+ss+"秒" : hh+":"+mm+":"+ss;
		}
        return str;
    }
}

var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function (milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function (dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function (number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function (str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

function dumpUrl(url)
{
	var page = getCurrentPages();
	if (page.length >= 9){
		uni.reLaunch({
			url: url
		})
	} else {
		uni.navigateTo({
			url: url
		})
	}
}

function tbAuth(_this, callback){
	uni.request({
		url: _this.serviceUrl + "App/Login/hasTbAuth",
		data: {uid: _this.userInfo.id},
		success(ress) {
			console.log(ress)
			if (!ress.data.status){
				if (ress.data.data.nologin){
					uni.showToast({
						title: ress.data.msg,
						icon: 'none'
					})
				} else {
					let url = _this.serviceUrl+"Index/Auth/taobaoOauth?uid="+_this.userInfo.id+"&code="+_this.userInfo.verify_code;
					callback({isauth: false, url: url});
					// #ifdef APP-PLUS
					// uni.showModal({
					// 	title: "提示",
					// 	content:"请授权，否则无法获取订单信息",
					// 	confirmText:"立即授权",
					// 	cancelText: "暂时跳过",
					// 	success: (res) => {
					// 		if (res.confirm) {
					// 			plus.runtime.openURL(url)
					// 		}else if (res.cancel) {
					// 			callback({isauth: false, url: url});
					// 		}
					// 	}
					// })
					// #endif
					// #ifdef MP-WEIXIN
					// callback({isauth: false, url: url});
					// #endif
				}
				
			} else {
				callback({isauth:true});
			}
		}
	})
}
function login(_this, code, userInfo, puid){
	let platform = 'App';
	// #ifdef MP-WEIXIN
	platform = '小程序'
	// #endif
	uni.request({
		url: _this.serviceUrl + '/App/Login/wxLogin',
		data:{
			code: code,
			wxInfo: JSON.stringify(userInfo),
			puid: puid,
			platform: platform
		},
		method:'POST',
		header:{
			'content-type': 'application/x-www-form-urlencoded'
		},
		success(res) {
			// console.log("wxLogin="+JSON.stringify(res.data));
			// console.log(res.data)
			if (res.data.status){
				
				_this.doLogin({provider:'weixin', userInfo:res.data.data}); //改变保存在store里的登录状态
				
				// uni.showToast({
				// 	title:'登录成功'
				// })
				// #ifdef APP-PLUS
				let date = new Date();
				uni.setStorage({
					key: 'yx_userinfo',
					data: {time: Math.ceil(date.getTime() / 1000), info: JSON.stringify(res.data.data)}
				})
				// #endif
				// setTimeout(function(){
					uni.hideToast();
					// console.log(JSON.stringify(res.data.data))
					// #ifdef APP-PLUS
					// if (res.data.data.phone == ''){
					// 	uni.reLaunch({
					// 		url: '/pages/index/login-bangding'
					// 	})
					// } else {
						uni.reLaunch({
							url: decodeURIComponent(_this.backurl) 
						})
						
					// }
					// #endif
					// #ifdef MP-WEIXIN
					_this.closeOauth();
					// #endif
				// },300);
				
			} else {
				uni.showModal({
					title:"登录提示",
					content: "登录失败"+res.data.msg,
					showCancel: false
				})
			}
		},
		fail(res) {
			// console.log(JSON.stringify(res))
		}
	})
}

function wxOauth(e, _this) {
	console.log('util.wxoauth' + !_this.hasLogin);
	// #ifdef MP-WEIXIN
	if (!_this.hasLogin){
		_this.showOauth = true;
	}
	// #endif
	
}

function wxOauthClose(_this) {
	_this.showOauth=false
}

module.exports = {
	formatTime: formatTime,
	formatLocation: formatLocation,
	dateUtils: dateUtils,
	InitTime: InitTime,
	dumpUrl: dumpUrl,
	tbAuth: tbAuth,
	login: login,
	wxOauth: wxOauth
}
