<template>
  <div class="login">
    <van-form ref="loginForm" validate-first @submit="onSubmit">
      <div @click="(loginType=== 3) ? loginType = 1  : loginType = 3;" style="text-align:right;color:#353535;font-size: 16px;margin-bottom:36px;">{{loginType === 3? '手机' : '邮箱'}}登录</div>
      <section v-if="loginType === 1" :key="loginType">
        <van-field 
          v-model="phone" 
          :rules="[{ pattern: /1\d{10}/, message: '请输入正确的手机号' }]"
          name="phone"
          label="手机号" 
          placeholder="手机号"
          label-align="right"
        />
        <van-field
          v-model="code"
          :rules="[{ pattern: /\d{6}/, message: '请输入验证码' }]"
          label="短信验证码"
          placeholder="验证码"
          label-align="right"
        >
          <template #button>
            <van-button @click="sendCode" plain size="small" color="#3F79FE" type="primary" native-type="button">{{btnStr}}</van-button>
          </template>
        </van-field>
      </section>
      <section v-if="loginType === 0" :key="loginType">
        <van-field 
          v-model="phone" 
          :rules="[{ pattern: /1\d{10}/, message: '请输入正确的手机号' }]"
          name="phone"
          label="手机号" 
          placeholder="手机号"
          label-align="right"
        />
        <van-field
          v-model="pwd"
          type="password"
          :rules="[{ pattern: /[0-9a-z]{6,16}/i, message: '密码6-16位由字母或数字组成' }]"
          label="密码"
          placeholder="密码"
          label-align="right"
        />
      </section> 
      <section v-if="loginType === 3" :key="loginType">
        <van-field 
          v-model="email" 
          :rules="[{ pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱' }]"
          name="email"
          label="邮箱" 
          placeholder="邮箱"
          label-align="right"
        />
        <van-field
          v-model="code"
          :rules="[{ pattern: /\d{6}/, message: '请输入验证码' }]"
          label="邮箱验证码"
          placeholder="验证码"
          label-align="right"
        >
          <template #button>
            <van-button @click="sendCode" plain size="small" color="#3F79FE" type="primary" native-type="button">{{btnStr}}</van-button>
          </template>
        </van-field>
      </section>
      <section v-if="loginType === 2" :key="loginType">
        <van-field 
          v-model="email" 
          :rules="[{ pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱' }]"
          name="email"
          label="邮箱" 
          placeholder="邮箱"
          label-align="right"
        />
        <van-field
          v-model="pwd"
          type="password"
          label="密码"
          :rules="[{ pattern: /[0-9a-z]{6,16}/i, message: '密码6-16位由字母或数字组成' }]"
          placeholder="密码"
          label-align="right"
        />
      </section>
      <van-button block color="#3F79FE"  type="primary" native-type="submit" style="margin-top: 60px;">确定</van-button>
      <div @click="loginType = loginType === 1 || loginType === 3 ?  --loginType  :  ++loginType" style="margin-top:15px;color:#3F79FE;">{{ loginType === 1 || loginType === 3 ? '密码' : '验证码'}}登录</div>
    </van-form>
  </div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { Form, Field, CellGroup, Button } from 'vant';
import { Action } from 'vuex-class';
import md5 from 'blueimp-md5';
@Component({
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [Button.name]: Button,
  },
})
export default class Login extends Vue {
  @Action('getUserInfo') private getUserInfo!: () => void;
  private phone: string = '';
  private email: string = '';
  private code: string = '';
  private pwd: string = '';
  private count: number = 0;
  private loginType: number = 1; // 0：手机号密码 1:手机号验证码 2:邮箱密码 3：邮箱验证码

  private async onSubmit() {
    const res = await this.$api.user.login({
      login_type: this.loginType,
      phone: this.phone,
      code: this.code,
      pwd: md5(this.pwd + md5(this.pwd.length)),
      email: this.email,
    });
    localStorage.setItem('userInfo', JSON.stringify(res));
    await this.getUserInfo();
    this.$router.replace({path: '/'});
  }
  get btnStr() {
    return this.count <= 0 ? '发送验证码' : `${this.count}s`;
  }
  private sendSms() {
    return this.$api.user.sendSms(this.phone);
  }
  private sendEmail() {
    return this.$api.user.sendEmail(this.email);
  }
  private sendCode() {
    if ( this.count > 0 ) { return; }
    const validatePromise: any  = this.loginType === 3
                                    ? (this.$refs.loginForm as any).validate('email')
                                    : (this.$refs.loginForm as any).validate('phone');
    validatePromise.then(() => {
      this.count  = 60;
      const countTimer = setInterval(() => {
        this.count--;
        if (this.count <= 0) {
          clearInterval(countTimer);
        }
      }, 1000);
      this.$once('hook:beforeDestroy', () => { clearInterval( countTimer ); });
      if (this.loginType === 1) {
        this.sendSms();
      } else if (this.loginType === 3) {
        this.sendEmail();
      }
    }).catch((err: any) => {
      this.$toast(err.message || err);
    });
  }
}
</script>
<style scoped lang="scss">
  .login{
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column; 
    padding: 30px 30px;
    box-sizing: border-box;
    ::v-deep .van-field--error .van-field__control{
      color: #353535;
    }
  }
</style>