<template>
	<view class="content">
		<u-form :model="form"  ref="uForm" :error-type="['toast']"> 
			<u-form-item label="原邮箱:" labelWidth="160">{{baseInfo.email}}</u-form-item>
			
			<u-form-item label="新邮箱:" labelWidth="160"  prop="new_email">
				<u-input placeholder="请输入新邮箱" v-model="form.new_email" />
			</u-form-item>
			
			
			<u-form-item label="验证码:" labelWidth="160" prop="code">
				<u-input placeholder="请输入验证码" v-model="form.code" />
				<u-verification-code :seconds="seconds"  ref="uCode" 
						@change="codeChange"></u-verification-code>
				<u-button slot="right" type="primary" size="mini" @click="getCode">{{tips}}</u-button>
			</u-form-item>
			<u-button type="primary" @click="submit">确定</u-button>
		</u-form>
	</view>
	
</template>
<script>
import {toast, useRouter} from '@/utils/utils.js'	
export default {
	data() {
		return {
			baseInfo: {
			  email : '',
			},
			form: {
				new_email: '',
				code: ''
			},
			rules: {
				new_email: [
					{
						required: true,
						type: 'email',
						message: '邮箱格式错误',
						trigger: 'blur,change'
					}
				],
				code: [
					{
						required: true,
						min: 4,
						type: 'number',
						message: '验证码格式错误',
						trigger: 'change'
					}
				]
			},
			seconds: 60,
			refCode: null,
			tips:'获取验证码'
		};
	},
	onLoad(){
		this.getUserInfo()
	},
	onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
	methods: {
		getUserInfo() {
			this.$api.baseInfo().then(res => {
				this.baseInfo = res.data
			})
		},
		
		submit(){
			this.$refs.uForm.validate(valid => {
				if (valid) {
					//验证通过，执行TODO
					this.$api.emailBind(this.form).then(res => {
						if (res.code == 0) {
							toast(res.msg)
							setTimeout(()=>{
								uni.navigateBack()
							},500) 
						} else {
							toast(res.msg)
						}
					}) 
				} else {
					console.log('验证失败');
				}
			});
		},
		codeChange(text) {
			this.tips = text;
		},
		getCode() {
			if(this.$refs.uCode.canGetCode) {
				// 模拟向后端请求验证码
				uni.showLoading({
					title: '正在获取验证码'
				})
				setTimeout(() => {
					uni.hideLoading();
					// 这里此提示会被this.start()方法中的提示覆盖
					this.$u.toast('验证码已发送');
					// 通知验证码组件内部开始倒计时
					this.$refs.uCode.start();
				}, 2000);
			} else {
				this.$u.toast('倒计时结束后再发送');
			}
		}
	}
};
</script>

<style lang="scss" scoped>
	.content{padding:35rpx}
</style>