<template>
  <Form ref="loginForm" :model="form" :rules="rules" @keydown.enter.native="handleSubmit">
    <FormItem prop="mobile">
      <Input v-model="form.mobile" placeholder="请输入手机号">
        <span slot="prepend">
          <Icon :size="16" type="ios-person"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem prop="vcode">
      <Input v-model="form.vcode" placeholder="请输入收到的验证码">
        <span slot="prepend">
          <Icon :size="14" type="md-lock"></Icon>
        </span>
        <span slot="append">
          <Button type="primary" v-if="!isshowtime" @click="sendVCode">发送验证码</Button>
          <span v-if="isshowtime">{{ leftseconds }}秒</span>
        </span>
      </Input>
    </FormItem>
    <FormItem>
      <Button @click="handleSubmit" type="primary" long>登录</Button>
    </FormItem>
  </Form>
</template>
<script>
export default {
  name: "PhoneForm",
  props: {
    mobileRules: {
      type: Array,
      default: () => {
        return [
          { required: true, message: "电话号码不能为空", trigger: "blur" }
        ];
      }
    },
    vcodeRules: {
      type: Array,
      default: () => {
        return [{ required: true, message: "验证码不能为空", trigger: "blur" }];
      }
    }
  },
  data() {
    return {
      form: {
        mobile: "",
        vcode: ""
      },
      isshowtime: false,
      leftseconds: 60
    };
  },
  computed: {
    rules() {
      return {
        mobile: this.mobileRules,
        vcode: this.vcodeRules
      };
    }
  },
  methods: {
    sendVCode() {
      if (this.form.mobile.trim() != "") {
        let tmp = 60;
        this.isshowtime = true;
        var th = setInterval(() => {
          this.leftseconds = tmp--;
          if (tmp == 0) {
            clearInterval(th);
            this.isshowtime = false;
          }
        }, 1000);
        this.$emit("onsendvcode", { mobile: this.form.mobile});
      }
    },
    handleSubmit() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.$emit("on-success-valid", {
            mobile: this.form.mobile,
            vcode: this.form.vcode
          });
        }
      });
    }
  }
};
</script>
