<template>
  <Form ref="wx-login-bind-form" :model="registerForm" :rules="rules" class="v-component wx-login-bind-form">
    <div class="title">账号绑定</div>
    <FormItem prop="userName">
      <Input v-model.trim="registerForm.userName" placeholder="用户姓名" :maxlength="20"></Input>
    </FormItem>
    <FormItem prop="phone">
      <Input v-model.trim="registerForm.phone" placeholder="手机号" :maxlength="11"></Input>
    </FormItem>
    <FormItem prop="code">
      <Input v-model.trim="registerForm.code" placeholder="验证码" class="code" :maxlength="6" @keyup.enter.native="checkForm('wx-login-bind-form', register)"></Input>
      <verifycode-btn ref="verifycode-btn" class="code-btn" :auto="false" :limit="false" :disabled="codeBtnDisabled" @on-click="getCode"></verifycode-btn>
    </FormItem>
    <div class="action-wrap">
      <Button type="primary" class="submit-btn full" @click="checkForm('wx-login-bind-form', register)">立即绑定</Button>
    </div>
    <Spin size="large" fix v-if="loading"></Spin>
  </Form>
</template>

<script>
import formMixin from '../../mixins/form'
import VerifycodeBtn from '../verifycode-btn'
import validate from '../../utils/validate'
import login from '../../apis/login'
import rule from '../../utils/rule'
import storage from '../../utils/storage'
export default {
  name: 'WxLoginBind',
  mixins: [formMixin],
  props: {
    registerId: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      loginUrl: window.$CONFIG.loginUrl,
      registerForm: {
        userName: '',
        phone: '',
        code: '',
        checkId: ''
      },
      rules: {
        userName: [
          rule.name
        ],
        phone: [
          rule.phone
        ],
        code: [
          rule.code
        ]
      },
      loading: false
    }
  },
  computed: {
    codeBtnDisabled () {
      return !validate.isPhone(this.registerForm.phone)
    }
  },
  created () {
  },
  methods: {
    async getCode () {
      if (this.codeBtnDisabled) return false
      try {
        this.loading = true
        let res = await login.sms(this.registerForm.phone, this.registerId)
        this.$emit('send-code')
        this.registerForm.checkId = res.data.checkId
        this.$refs['verifycode-btn'].start()
        this.loading = false
      } catch (e) {
        this.loading = false
      }
    },
    async register () {
      let { userName, phone, code, checkId } = this.registerForm
      if (!checkId) {
        this.$Message.error('请获取验证码')
        return false
      }
      try {
        this.loading = true
        let res = await login.register({ userName, phone, code, checkId })
        this.$emit('register-success', res.data.accessCode)
      } catch (e) {
        this.loading = false
      }
    }
  },
  components: {
    VerifycodeBtn
  }
}
</script>