<template>
	<view class="page">
		<cu-custom :isBack="true" title="修改手机">
		</cu-custom>
		<form>
			<view class="cu-form-group margin-top-sm">
				<input placeholder="请输入手机号" v-model="form.user_phone" @input="changePhone"/>
        <text class="text-cyan" :class="{'text-gray':disableSendMsgBtn}" :disabled="disableSendMsgBtn"
            @tap="getCode">{{sendMsg}}</text>
			</view>
			 <view class="cu-form-group">
				<input placeholder="请输入验证码"  v-model="form.captcha"/>
			</view>
			<view class="solids-bottom radius bg-student text-center padding text-white margin-top" @tap="save">
					保存
			</view>
		</form>
	</view>
</template>

<script>
import { _changePhone, _getCode } from '@/api/auth'
import validate from '@/common/utils/ys-validate'
export default {
  data() {
    return {
      sendTime: 60,
      disableSendMsgBtn: true,
      sendMsg: '获取验证码',
      leftTime: 0, // 倒计时
      form: {
        user_phone: '',
        captcha: ''
      },
      rules: [
        { name: 'user_phone', required: true, type: 'phone', errmsg: '请输入正确手机号' },
        { name: 'captcha', required: true, type: 'number', errmsg: '请输入正确的验证码' }
      ]
    }
  },
  methods: {
    save() {
      const validRes = validate.validate(this.form, this.rules)
      if (!validRes.isOk) {
        uni.showToast({
          icon: 'none',
          title: validRes.errmsg
        })
        return false
      }
      _changePhone(this.form).then(res => {
        this.$store.dispatch('setToken', res.data.token)
        uni.showToast({ title: '保存成功', icon: 'success' })
        setTimeout(() => {
          uni.navigateBack()
        }, 800)
      })
    },
    changePhone(e) {
      if (/^[1]([3-9])[0-9]{9}$/.test(e.detail.value)) {
        this.disableSendMsgBtn = false
      } else {
        this.disableSendMsgBtn = true
      }
    },
    getCode() {
      if (!this.disableSendMsgBtn) {
        this.leftTime = this.sendTime
        this.timing(this.leftTime)
        _getCode({ phone: this.form.user_phone }).then(res => {
          uni.showToast({
            title: '验证码发送成功! 请注意查收！',
            duration: 3000
          })
        })
      }
    },
    timing () {
      this.disableSendMsgBtn = true
      const temSendMsgText = this.sendMsg
      this.sendMsg = this.leftTime + '秒后重试'
      this.timeInterval = setInterval(() => {
        this.leftTime--
        this.sendMsg = this.leftTime + '秒后重试'
        if (this.leftTime <= 0) {
          this.sendMsg = temSendMsgText
          clearInterval(this.timeInterval)
          if (/^[1]([3-9])[0-9]{9}$/.test(this.form.phone)) {
            this.disableSendMsgBtn = false
          }
        }
      }, 1000)
    }
  }
}
</script>

<style lang="scss" scoped>
.page{
	height:100vh;
}
</style>
