import { get,post } from "../../common/request.js"
import pathmap from "../../common/pathmap"

var app = getApp();	
export const logs = {
	openLog:function(){
		this.setData({openlog:true});
	},
	closeLog:function(){
		this.setData({openlog:false});
		if(typeof this.closeLogBack=="function"){
			this.closeLogBack();
		}
	},
	phoneInput:function(e){
		var number = e.detail.value;
		var newdata = {mobilenumber:number};
		if(number.length==11){
			if(/^[1][3|4|5|6|7|8|9][0-9]{9}$/.test(number)){
				if(this.data.codebtword=="获取验证码"){
					//this.setData({,codeenable:true})
					newdata.codeenable = true
				}
			}else{
				wx.showToast({
					title:"输入手机号不合法！",
					duration:1000,
					icon:"none"
				})
			}
		}
		this.setData(newdata)
	},
	codeInput:function(e){
		var code =  e.detail.value;
		this.setData({logcode:code});
	},
	getCode:function(){
		var _self = this;
		if(this.data.codeenable){
			get(pathmap.yzm,{mobile:this.data.mobilenumber},function(json){
				if(json.data.code=="验证码已发送"){
					wx.showToast({
						title:"验证码已发送！"
					})
					_self.startTimeing();
				}else{
					wx.showToast({
						title:json.data.message,
						icon:"none"
					})
				}
			})
			//_self.startTimeing();
		}
	},
	startTimeing:function(){
		var length = 60;
		var _self = this;
		this.timeingtool = setInterval(function(){
			length--;
			if(length>=0){
				_self.setData({codebtword:length+"s"});
			}else{
				_self.endTimeing();
			}
		},1000)
		this.setData({codeenable:false,logenable:true});
	},
	endTimeing:function(){
		try{
			clearTimeout(this.timeingtool);
		}catch(e){}
		if(/^[1][3|4|5|6|7|8|9][0-9]{9}$/.test(this.data.mobilenumber)){
			this.setData({codeenable:true,codebtword:"获取验证码"})
		}else{
			this.setData({codeenable:false,codebtword:"获取验证码"})
		}
	},
	logIn:function(){
		var _self = this;
		if(this.data.logenable){
			wx.request({
				url: app.globalData.serverpath+pathmap.login,
			    method: "POST",
			    header:{
			      "Content-Type": "application/x-www-form-urlencoded"
			  	},
			    data:{
			    	mobile:this.data.mobilenumber,
			    	code:this.data.logcode
			    },
			    success: function (res){
			    	//app.globalData.Authorization = res.data.authorization;
			    	if(res.data.authorization){
				    	try{
				    		wx.setStorageSync("mobile",_self.data.mobilenumber);
				    		wx.setStorageSync("authorization",res.data.authorization);
				    	}catch(e){

				    	}
						_self.setData({openlog:false});
				    	_self.endTimeing();
				    	if(typeof _self.loginback=="function"){
				    		_self.loginback();
				    	}
				    }else{
				    	wx.showToast({
				    		title:res.data.message,
				    		icon:"none"
				    	})
				    }
			    },
			    fail: function (error){
			      
			    }
			})
		}
	}
}

const bindLogs = function(pages){
	pages.setData({openlog:false,codeenable:false,logenable:false,codebtword:"获取验证码",mobilenumber:""});
	//Object.assign(pages,logs);
}

export default bindLogs;