import bus from "./bus.js"

//计算总时间
var getTotalTime = function(time){
	var totalTime = new Date();
	totalTime.setTime(totalTime.getTime()+time*1000);
	return totalTime;
}


//倒计时
var timer = function(that){
	that.verifyState=1;
	that.secondNum=60;
	clearInterval(that.countDown);//初始化计时器
	that.countDown = setInterval(function(){
		that.secondNum--;
		if (that.secondNum == 0) {
			clearInterval(that.countDown);
			that.verifyState = 2;//更改按钮状态
			that.secondNum = 60;
		}
	},1000);
}

//设置cookie
/**
 * [setcookie description]
 * @param  {[string]} key     [key]
 * @param  {[type]} value   [key的值]
 * @param  {[type]} expires [cookie的有效期]
 * @param  {[type]} path    [指定路径]
 * @param  {[type]} domain  [指定cookie的域名信息]
 * @param  {[boolean]} secure  [指定cookie只能在加密协议HTTPS下发送到服务器]
 * @return {[type]}         [description]
 */
var setcookie = function(key,value,expires,path,domain,secure){
	var cookieText = encodeURIComponent("block_fxees" + key) + '=' + encodeURIComponent(value);
	var time = getTotalTime(expires);
	if (time instanceof Date) {
		cookieText += ';expires=' + time;
	}
	if (path) {
		cookieText += ';path=' + path;
	}
	if (domain) {
		cookieText += ';domain' + domain;
	}
	if (secure) {
		cookieText += ';secure'+ secure;
	}
	document.cookie = cookieText;
	if (localStorage) {
    localStorage.setItem(key, value);
  }
}
//获取cookie
/**
 * [getcookie description]
 * @param  {[type]} key [description]
 * @return {[type]}     [key的值]
 */
var getcookie = function(key){
	var cookieName = encodeURIComponent("block_fxees" + key);
	var cookieStart = document.cookie.indexOf(cookieName);
	var cookieValue = null;
	if (cookieStart > -1) {
		var cookieEnd = document.cookie.indexOf(';',cookieStart);
		if (cookieEnd == -1) {
			cookieEnd = document.cookie.length;
		}
		cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + 1 + cookieName.length, cookieEnd));
	}else if(localStorage){
		cookieValue = localStorage.getItem(key);
	}
	return cookieValue;
}

//删除cookie
/**
 * [deletecookie description]
 * @param  {[type]} key [description]
 * @return {[type]}     [description]
 */
var deletecookie = function(key){
	document.cookie = "block_fxees" + key + "= ; expires=" + new Date(0).toUTCString();
	localStorage.removeItem(key);
}

//封装axios
/**
 * [getInfo description]
 * @param  {[type]} url     [接口地址]
 * @param  {[type]} method  [请求方式]
 * @param  {[type]} params  [请求数据]
 * @param  {[type]} success [成功后执行的操作]
 * @param  {[type]} failure [失败后执行的操作]
 * @return {[type]}         [description]
 */
var getInfo = function(that,url,method,params,success){
	var token = getcookie("token");
	var headerParam;
	if (token) {
		headerParam = {
			"Authorization":"Bearer " + token,
			'Content-Type':'application/x-www-form-urlencoded;'
		}
	}else{
		headerParam = {
			'Content-Type':'application/x-www-form-urlencoded;'
		}
	}
	console.log(that.$qs.stringify(params));
	that.$axios({
		url: url,
		method: method,
		params: method === 'GET' ? params :null,
		data: method === 'POST' ? that.$qs.stringify(params) : null,//将params序列化
		headers:headerParam
	})
	.then(function(response){

		if (typeof(success)==='function') {
			success(response.data);
		}
		if (response.data.code==='200'||response.data.code==200 || response.data.code == "-2") {

		}else{
	        that.$notify({
	          title: '提示',
	          message: response.data.message,//提示错误
	          type: 'warning',
	          duration:'2000'
	        });
      	}    
	})
	.catch(function(error){
		console.log(error);
	})
}

//发送邮件
/**
 * [sendEmail description]
 * @param  {[type]} that    [this]
 * @param  {[type]} params  [请求数据]
 * @return {[type]}         [description]
 */
var sendEmail = function(that,params,operation){
	var url;
	if (operation=='email') {
		url=that.urlApi.sendEmail;
	}else{
		url=that.urlApi.sendMessage;
	}

	getInfo(that,url,'POST',params,function(res){
		if (res.code===200) {
			that.$notify({
		        title: '提示',
		        message: '发送成功',
		        type: 'success',
		        duration:'2000'
		    });
		    timer(that);
		}else{
		}
	});
}

//发送短信
/**
 * [sendMessage description]
 * @param  {[type]} that   [this]
 * @param  {[type]} params [请求数据]
 * @return {[type]}        [description]
 */
var sendMessage = function(that,params){
	getInfo(that,that.urlApi.sendMessage,'POST',params,function(res){
		if (res.code===200) {//注意返回的200是数字还是字符串
			that.$notify({
		        title: '提示',
		        message: '发送成功',
		        type: 'success',
		        duration:'2000'
		    });
		    timer(that);
		}
	});
}


//验证手机号码或者邮箱的格式
/**
 * [typeVerify description]
 * @param  {[type]} str       [手机号或者邮箱地址]
 * @param  {[type]} operation [手机还是邮箱]
 * @param  {[type]} that      [this]
 * @return {[type]}           [description]
 */
var typeVerify = function(str,operation,that){
	var emailtype = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
	var phonetype = /^1[3|5|7|8][0-9]\d{4,8}$/;
	var res;
	if (operation=='email') {
		res = emailtype.test(str);
		if (!res) {
			that.$notify({
              title:'提示',
              message:"邮箱格式错误",
              type:'warning',
              duration:2000
            });
		}
		return !res;
	}else{
		res = phonetype.test(str);
		if (!res) {
			that.$notify({
              title:'提示',
              message:"手机号码格式错误",
              type:'warning',
              duration:2000
            });
		}
		return !res;
	}
}

//检测个输入框中是否有值存在
/**
 * [inputTest description]
 * @param  {[type]} that [this]
 * @return {[type]}      [description]
 */
var inputTest = function(that){
	switch(that.logintype){
		case 0:
		if (that.regInfo.intype == "") {
			that.$notify({
	            title: '提示',
	            message: that.tiptip,
	            type: 'warning',
	            duration:'1500'
	          })
			console.log("register");
			return false;
		};
		if (that.regInfo.verifyCode == "") {
			that.$notify({
	            title: '提示',
	            message: "验证码不能为空",
	            type: 'warning',
	            duration:'1500'
	          })
			console.log("这里呢？");
			return false;
		};
		if (that.regInfo.passWord == "") {
			that.$notify({
	            title: '提示',
	            message: "密码不能为空",
	            type: 'warning',
	            duration:'1500'
	          })
			return false;
		};
		if (that.regInfo.verifyCode == "") {
			that.$notify({
	            title: '提示',
	            message: "验证码不能为空",
	            type: 'warning',
	            duration:'1500'
	          })
			return false;
		};
		if (that.warnRead == false) {
			that.$notify({
	            title: '提示',
	            message: "请阅读风险警告",
	            type: 'warning',
	            duration:'1500'
	          })
			return false;
		};
		return true;
		case 1:
		if (that.loginInfo.intype == "") {
			that.$notify({
	            title: '提示',
	            message: that.tiptip,
	            type: 'warning',
	            duration:'1500'
	          })
			return false;
		}
		//密码是否正确不用在这里检测，后台会检测
		if (that.loginInfo.passWord == "") {
			that.$notify({
	            title: '提示',
	            message: "密码不能为空",
	            type: 'warning',
	            duration:'1500'
            })
            return false;
		};
		return true;
		case 2:
		if (that.operation == "mobile") {
			if (that.resetInfo.intype == "") {
				that.$notify({
		            title: '提示',
		            message: that.tiptip,
		            type: 'warning',
		            duration:'1500'
		          })
				return false;
			}
		}else{
			if (that.resetInfo.verifyCode == "") {
				that.$notify({
		            title: '提示',
		            message: "验证码不能为空",
		            type: 'warning',
		            duration:'1500'
		          })
				return false;
			}
			if (that.resetInfo.oldPassWord == "") {
				that.$notify({
		            title: '提示',
		            message: "请输入新密码",
		            type: 'warning',
		            duration:'1500'
		          })
				return false;
			}
			if (that.resetInfo.newPassWord == "") {
				that.$notify({
		            title: '提示',
		            message: "请再次输入新密码",
		            type: 'warning',
		            duration:'1500'
		          })
				return false;
			}
			if (that.resetInfo.oldPassWord == that.resetInfo.newPassWord) {
				that.$notify({
		          title: '提示',
		          message: '两次输入的密码不同',
		          type: 'warning',
		          duration:'1500'
		        })
		        return false;
			}
		}
		return true;
	}

}

//注册
/**
 * [goRegister description]
 * @param  {[type]} that     [this]
 * @param  {[type]} warnRead [是否阅读风险提示]
 * @return {[type]}          [description]
 */
var goRegister = function(that,flag){
	if (flag == false) {
		return false;
	}else{
		let params = {};
	    if (that.operation=="email") {
	      params={
	        "email":that.regInfo.intype,
	        "password":that.regInfo.passWord,
	        "code":that.regInfo.verifyCode,
	        "type":"email"
	      }
	    }else{
	      params={
	        "mobile":that.regInfo.intype,
	        "password":that.regInfo.passWord,
	        "code":that.regInfo.verifyCode,
	        "type":"sms",
	        "area":that.coutry
	      }
	    }
	    getInfo(that,that.urlApi.newRegist,"POST",params,function(res){
	    	if (res.code==200) {
	    		that.registered = false;//初始注册状态
	    		that.$notify({
	            title: '成功',
	            message: '注册成功！',
	            type: 'success',
	            duration:'1500'
	          })
	    		goLogin(that,"register",true);
	    	}else if (res.code == 1001 && that.operation == "email") {
	    		that.registered = true;
	    	}
	    })
	}
}

//登录
var goLogin = function(that,state,flag){
	if (flag != true) {
		return false;
	}
	let params = {
		"password":state=="register" ? that.regInfo.passWord : that.loginInfo.passWord,
		"redirect_uri":"http://33.cn",
		"os":"web",
		"platform":"fx66"
	};
	if (that.operation == "email") {
		params.email = state=="register" ? that.regInfo.intype : that.loginInfo.intype;
		params.type = "email";
	}else{
		params.area = that.coutry;
		params.mobile = state=="register" ? that.regInfo.intype : that.loginInfo.intype;
		params.type = "sms"
	}
	getInfo(that,that.urlApi.newLogin,"POST",params,function(res){
		if (res.code == 200) {
			that.$notify({
	            title: '成功',
	            message: '登录成功！',
	            type: 'success',
	            duration:'1500'
	          })
			that.loginInfo.userName = res.data.username;
			that.logintype = 3;
			setcookie("token",res.data.access_token,res.data.expires_in);
			setcookie("username",res.data.username,res.data.expires_in);
			bus.$emit("reUsername");
			getStatus(that);
		}
	});
}	

//退出
var loginOut = function(that){
	getInfo(that,that.urlApi.loginout,'GET','',function(res){
	    if (res.code == 200 || res.code == "-2") {
	        that.$notify({
	          title: '提示',
	          message: '退出成功',
	          type: 'success',
	          duration:'1500'
	        });
	        deletecookie("token");
	        deletecookie("username");
	        that.userstate=0;
	        that.$router.push({path:"/home"});
	        bus.$emit("goout");
	    }
    })
}

//找回密码发送信件
var resetCode = function(that){
	inputTest(that);
	if (that.resetInfo.intype == '') {
		return false;
	}
	let params = {
		"email":that.operation=="email"? that.resetInfo.intype:"",
		"mobile":that.operation=="mobile"? that.resetInfo.intype:"",
		"os":"web",
		"type":that.operation=="email"?"email":"sms",
		"platkey":"fx66",
		"ticket":"",
		"businessId":""
	}
	getInfo(that,that.urlApi.resetEmailPassword,"POST",params,function(res){
		console.log(res.code);
		if (res.code = 200) {
			that.$notify({
	          title: '成功',
	          message: '发送成功',
	          type: 'success',
	          duration:'1500'
	        });
	        timer(that);
		}
	})
}

//修改密码
var goReset = function(that,flag){
	if (!flag) {
		return false;
	}
	let params = {
		"type":"sms",
		"password":that.resetInfo.oldPassWord,
		"password2":that.resetInfo.newPassWord,
		"os":"web",
		"resettoken":that.resetInfo.verifyCode
	}
	getInfo(that,that.urlApi.resetPwd,"POST",params,function(res){
		if (res.code = 200) {
			that.$notify({
	            title: '提示',
	            message: '修改密码成功,请使用新密码登录',
	            type: 'success',
	            duration:'1500'
	          });
			that.logintype = 1;
		}
	})
}

//获取状态
var getStatus = function(that){
	getInfo(that,that.urlApi.applyStatus,"POST",'',function(res){
		if (res.code == 200) {
			if (res.data.isApply == 1) {
				switch (res.data.info.status){
					case 0:
					that.applicationStatus = 1;
					break;
					case 1:
					that.applicationStatus = 2;
					break;
					case -1:
					that.applicationStatus = -1;
					break;
				}
			}else{
				that.applicationStatus = 0;
			}
		}
	})
}


export{
	applyNow,
	getStatus,
	goReset,
	resetCode,
	loginOut,
	goLogin,
	goRegister,
	inputTest,
	sendMessage,
	sendEmail,
	setcookie,
	getcookie,
	deletecookie,
	getInfo,
	typeVerify
}