<template>
	<view class="phone-code">
		<view class="i-code" @tap="$tools.throttle(getCode)" :class="{disabled:isCountDown}">
			{{countDownOrGetCodeText}}
		</view>
	</view>
</template>

<script>
export default {
	name: 'phoneCode',
	props: {
		mobile: {
			type: String,
			default: ''
		},
		event: {
			type: String,
			default: ''
		},
	},
	data() {
		return {
			isCountDown:false,     //如倒计时,更改countDownOrGetCodeText
			countDownOrGetCodeText:"获取验证码",
			countTime:60,
			isOut:false,//去除定时
			timer:'',
		}
	},
	beforeDestroy() {
		this.isOut=true;
		// console.log('phoneCode 调一次')
		if(this.timer){
		    clearTimeout(this.timer);
		    this.timer=null;				
		}
	},
	methods: {
		countDown(){
		    if(this.isOut){
		        return;
		    }
		    console.log('countDown定时一次')
		    this.countDownOrGetCodeText="重新获取("+this.countTime+")";
		    this.countTime--;
		    if (this.countTime > 0) {
		            this.timer=setTimeout(this.countDown, 1000);
		    }else{
		        this.countDownOrGetCodeText="获取验证码";
		        this.isCountDown=false;
		        this.countTime=60;
		    }
		},
		async getCode(){
		    // console.log('===',props.mobile)
		    if(! this.$tools.match( this.mobile,'mobile')){
		        return;
		    }
		    if(this.isCountDown==true){
		        return;
		    }
		    this.isCountDown=true;
		    try{
		        await this.$request('user.sms',{mobile:this.mobile,event:this.event});
		    }catch(err){
				// console.log('err---',err)
				this.$tools.msg(err.msg || '请求失败')
		        this.isCountDown=false;
				this.countDownOrGetCodeText="获取验证码"
				this.countTime=60;
		    }
			if(this.isCountDown){
				this.countDown(); 
			}
			   
			
		},
	}
}
</script>
<style lang="scss" scoped>
	.i-code{
		margin-left: auto;
		font-size: 26rpx;
		color: $base-color;
		&.disabled{
			color:#999;
		}
	}
</style>
