<template>
  <ElForm :model="model" :size="loginVm.size" class="x-login-sms" @submit.native.prevent>
    <ElFormItem prop="username">
      <ElInput v-model="model.username" ref="username"
               autocomplete="on"
               maxlength="30"
               @change="handleNameChange"
               :placeholder="texts.usernameForSmsPlaceholder"
      ></ElInput>
    </ElFormItem>
    <SmsCodeInput :phone="model.username" v-model="model.msgCode"
                  :sendSmsMethod="sendSmsMethod"></SmsCodeInput>
    <ElFormItem>
      <ElButton @click="handleSubmit" native-type="submit" type="primary" class="x-login-sms__submit">
        {{texts.submitButtonText}}
      </ElButton>
    </ElFormItem>
  </ElForm>
</template>

<script>
import {
  Form as ElForm,
  FormItem as ElFormItem,
  Input as ElInput,
  Button as ElButton,
  Notification
} from 'element-ui';
import SmsCodeInput from './SmsCodeInput';
import {isMobilePhone} from '@newpearl/utils/lib/regex';

export default {
  components: {
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
    SmsCodeInput
  },
  inject: ['loginVm'],
  data() {
    return {
      model: {
        loginType: 'msgcode',
        username: '',
        msgCode: ''
      },
      verifyId: '',
      verifyUrl: '',
      showImageCode: false
    };
  },
  computed: {
    texts() {
      return this.loginVm.texts;
    }
  },
  watch: {
    'loginVm.username': {
      immediate: true,
      handler(val) {
        this.model.username = val;
      }
    }
  },
  methods: {
    handleNameChange(val) {
      this.loginVm.username = val;
    },
    sendSmsMethod(data) {
      return this.loginVm.sendSmsCode(data);
    },
    validate() {
      const {msgCode, username} = this.model;
      if (!isMobilePhone(username)) {
        Notification({
          message: '请输入正确的手机号码',
          type: 'warning'
        });
        return false;
      }
      if (!msgCode || msgCode.length < 6) {
        Notification({
          message: '请输入验证码',
          type: 'warning'
        });
        return false;
      }
      return true;
    },
    handleSubmit() {
      if (!this.validate()) return;
      this.loginVm.userLogin(this.model);
    }
  }
};
</script>
