<script>
import qs from 'qs'
export default {
  data() {
    const regPhone = /^1[3456789]\d{9}$/
    const regEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
    return {
      form: {
        username: '',
        password: '',
        passwordConfirm:'',
        verifyCode: '',
        // phone_zone: '86'
      },
      errMsg: '',
      sending: false,
      clock: 60,
      showVcode: false,
      regEmail,
      regPhone,
    }
  },
  computed: {
    loginBtnDisabled() {
      return !(this.form.username && this.form.password && this.form.passwordConfirm)
    }
  },
  methods: {
// 点击注册前置校验
    vailidate() {
      if(!this.regPhone.test(this.form.username) && !this.regEmail.test(this.form.username)) {
        this.errMsg = '手机号/邮箱格式不对'
      }else if(this.form.password !== this.form.passwordConfirm) {
        this.errMsg = '两次输入的密码不一致'
      }else if(this.form.password.length < 6) {
        this.errMsg = '密码位数不能少于6位'
      }else if(this.form.password.length> 16){
        this.errMsg = '密码位数不能大于16位'
      }else {
        this.errMsg = ''
        this.handlerRegisterUser()
      }
    },
    handlerRegisterUser() {
      this.$axios.post('members/register',this.form).then((res)=> {
        if(res.code === 200) {
          this.handlerLogin(this.form)
        }
      })
    },
    handlePostCode() {
      if(this.sending) return
      const params = {
        action: '0', // 注册用户
        receiver: this.form.username
      }
      if(this.regPhone.test(this.form.username)) params.type = '1'
      if(this.regEmail.test(this.form.username)) params.type = '0'
      this.$axios.get('auth/getVerifyCode', {params}).then((res)=> {
        if(res.code === 200) {
          this.sending = true
          let interval = setInterval(() => {
            this.clock--
            if(this.clock === 0) {
              this.$once('hook:beforeDestroy',()=> {
                clearInterval(interval)
                interval = null
              })
              this.clock = 60
              this.sending = false
            }
          }, 1000);
        }
      })
    },
    handlerLogin() {
      this.$axios.post('login',qs.stringify(this.form)).then((res)=> {
        this.$store.dispatch('login',res.result).then((token)=> {
          this.$axios.setToken(token, 'Bearer')
          this.handlerClose()
          this.getUserInfo()
        })
      })
    },
    getUserInfo()  {
      this.$axios.get('members/getMemberInfo').then((res)=> {
        if(res.code === 200) {
          this.$store.commit('setUser',res.result)
          localStorage.setItem('userInfo',JSON.stringify(res.result))
        }
      })
    },
    handlerUsernameBlur(e) {
      this.showVcode = this.regPhone.test(e.target.value)
    },
    // 弹窗关闭，初始化注册面板
    resetInterfaceStatus() {
      this.errMsg = '';
      this.form.username = ''
      this.form.password = ''
      this.form.passwordConfirm = ''
      this.form.verifyCode = ''
      this.showVcode = false
    },
    handlerChangeLogin() {
      this.$emit('login','login')
    },
    handlerClose() {
      this.$emit('close')
    }
  }
}
</script>

<template>
  <div class="user-login">
    <div class="logo">
      <h4 id="loginModalLabel" class="logo_PDF"></h4>
    </div>
    <div class="login_content">
      <input id="signup_account" v-model="form.username" class="login_input_user" type="text" placeholder="手机号/邮箱" @blur="handlerUsernameBlur">
      <br />
      <input id="signup_pwd1" v-model="form.password" class="login_input_password" type="password" placeholder="密码（6-16个字符，区分大小写）">
      <br />
      <input id="signup_pwd2" v-model="form.passwordConfirm" class="login_input_password" type="password" placeholder="确认密码">
      <br />
      <div v-show="showVcode" class="vcode_content">
        <input v-model="form.verifyCode" class="input_vcode_signup" placeholder="验证码">
        <span class="sent-vcode sent-vcode-signup" :class="{'sent-vcode-disabled': sending}" @click="handlePostCode"><a>{{sending ? clock+'秒' : '发送验证码'}}</a></span>
      </div>
      <div v-show="errMsg !== ''" class="error-mess error-mess-signup">
        <span id="error-message error-tip">{{errMsg}}</span>
      </div>
      <button id="btn-signup" type="submit" class="logging" :class="{'btn-signin': loginBtnDisabled}" :disabled="loginBtnDisabled" @click="vailidate">注册</button>
      <div class="login-now">
        <div class="term">
          <span>轻触上面的“注册”按钮，即表示你同意我们的<a target="_blank" href="/terms">条款</a></span>
        </div>
        <div class="switch_login">
          <span>已经有账号？<a class="cursor-pointer" @click="handlerChangeLogin">登录</a></span>
        </div>
      </div>
    </div>
  </div>
</template>

