<template>
  <Card class="main-card">
    <div class="form">
      <Form ref="form" :model="form" :rules="rule">
        <FormItem prop="email">
          <i-input type="text" v-model="form.email" placeholder="Email">
            <Icon type="ios-mail-outline" slot="prepend"></Icon>
          </i-input>
        </FormItem>
        <FormItem prop="password">
          <i-input type="password" v-model="form.password" placeholder="Hasło"
                   @keyup.enter.native="handleSubmit('form')">
            <Icon type="ios-lock-outline" slot="prepend"></Icon>
          </i-input>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="handleSubmit('form')">Zarejestruj się</Button>
        </FormItem>
      </Form>
    </div>
  </Card>
</template>

<script>

  export default {
    data() {
      return {
        form: {
          email: '',
          password: ''
        },
        rule: {
          email: [
            {
              required: true,
              message: 'Proszę podać email',
              trigger: 'blur'
            },
            {
              type: 'email',
              message: 'Zły format!',
              trigger: 'blur'
            }
          ],
          password: [
            {
              required: true,
              message: 'Proszę podać hasło',
              trigger: 'blur'
            },
            {
              type: 'string',
              min: 8,
              message: 'Hasło jest zbyt krótkie!',
              trigger: 'blur'
            }
          ]
        }
      }
    },
    methods: {
      handleSubmit(name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.$axios.post('/user/register', {
              email: this.form.email,
              password: this.form.password

            })
              .then(() => {
                this.$Message.success('Sukces!');
                this.$auth.loginWith('local', {
                  data: {
                    email: this.form.email,
                    password: this.form.password
                  }
                })
              })
              .catch((error) => {
                this.$Message.error('Błąd!');
                console.log(error);
              })
          } else {
            this.$Message.error('Błąd!');
          }
        })
      }
    }
  }
</script>

<style scoped>

  .main-card {
    margin: 0;
    top: 50%
  }

  .form {
    display: inline-block;
  }

</style>
