<template>
  <div
    class="full-h is-flex is-justify-content-center is-align-items-center my-5"
  >
    <form class="box">
      <div class="has-text-centered">
        <h2 class="is-size-1">PC Puma</h2>
      </div>

      <b-field label="Usuario" :type="error">
        <b-input v-model="usuario" @keyup.enter.native="login()" />
      </b-field>

      <b-field label="Contraseña" :type="error">
        <b-input
          type="password"
          @keyup.enter.native="login()"
          v-model="password"
          password-reveal
        />
      </b-field>

      <div class="has-text-centered">
        <b-button
          @click="login()"
          type="is-success"
          :disabled="error || !usuario || !password"
        >
          Iniciar Sesión
        </b-button>
      </div>
    </form>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  props: {
    updateIsLoading: { type: Function, required: true },
  },
  data() {
    return {
      error: '',
      usuario: '',
      password: '',
    }
  },
  methods: {
    login() {
      if (this.usuario && this.password && !this.error) {
        const data = {
          operador: this.usuario,
          password: this.password,
        }

        this.updateIsLoading(true)
        axios
          .post(`${process.env.api}/auth/login-admin`, data)
          .then((res) => {
            const token = res.data.token
            const operador = JSON.stringify(res.data.operador)

            localStorage.setItem('operador', operador)
            localStorage.setItem('token', token)
            this.updateIsLoading(false)
            if (res.data.operador.tipoUsuario.id_tipo_usuario === 2)
              this.$router.push(
                '/admin/configuracion/instituciones/buscar_institucion'
              )
            else this.$router.push('/prestamo_devolucion')
          })
          .catch((err) => {
            this.error = 'is-danger'
            this.updateIsLoading(false)
            this.$alertsGenericos.imprimirError(
              this.$buefy,
              this.$router,
              err.response.data
            )
          })
      }
    },
  },
  watch: {
    password() {
      if (this.error) this.error = ''
    },
    usuario() {
      if (this.error) this.error = ''
    },
  },
}
</script>

<style scoped>
.full-h {
  height: 75vh;
}

form {
  width: 30rem;
}
</style>
