<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"
          password-reveal
          v-model="password"
          @keyup.enter.native="login()"
        />
      </b-field>

      <b-field label="Institucion" :type="error">
        <b-select v-model="idInstitucion" expanded>
          <option value="" disabled>Institucion</option>
          <option
            v-for="(ins, i) in instituciones"
            :key="i"
            :value="ins.id_institucion"
          >
            {{ ins.institucion }}
          </option>
        </b-select>
      </b-field>

      <b-field label="Modulo" :type="error">
        <b-select v-model="idModulo" expanded>
          <option value="" disabled>Módulo</option>
          <option v-for="(m, i) in modulos" :key="i" :value="m.id_modulo">
            {{ m.modulo }}
          </option>
        </b-select>
      </b-field>

      <b-field>
        <recaptcha />
      </b-field>

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

<script>
import axios from 'axios'

export default {
  props: {
    updateIsLoading: { type: Function, required: true },
  },
  data() {
    return {
      error: '',
      usuario: '',
      password: '',
      idModulo: '',
      idInstitucion: '',
      modulos: [],
      instituciones: [],
    }
  },
  methods: {
    async login() {
      const token = await this.$recaptcha.getResponse().catch((err) => {
        this.$alertsGenericos.imprimirError(
          this.$buefy,
          this.$router,
          'Favor de completar el recaptcha.'
        )
      })

      if (this.usuario && this.password && token && !this.error) {
        const data = {
          operador: this.usuario,
          password: this.password,
          id_modulo: this.idModulo,
        }

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

            localStorage.setItem('operador', operador)
            localStorage.setItem('token', token)
            localStorage.setItem('idModulo', this.idModulo)
            await this.$recaptcha.reset()
            this.updateIsLoading(false)
            this.$router.push('/prestamo_devolucion')
          })
          .catch((err) => {
            this.error = 'is-danger'
            this.updateIsLoading(false)
            this.$alertsGenericos.imprimirError(
              this.$buefy,
              this.$router,
              err.response.data
            )
          })
      }
    },
    obtenerCatalogoInstitucion() {
      axios
        .get(`${process.env.api}/institucion/instituciones-activas`)
        .then((res) => {
          this.instituciones = res.data
        })
        .catch((err) => {
          this.$alertsGenericos.imprimirError(
            this.$buefy,
            this.$router,
            err.response.data
          )
        })
    },
    obtenerCatalogoModulo() {
      axios
        .get(
          `${process.env.api}/modulo/modulos-activos?id_institucion=${this.idInstitucion}`
        )
        .then((res) => {
          this.modulos = res.data
        })
        .catch((err) => {
          this.$alertsGenericos.imprimirError(
            this.$buefy,
            this.$router,
            err.response.data
          )
        })
    },
  },
  watch: {
    password() {
      if (this.error) this.error = ''
    },
    usuario() {
      if (this.error) this.error = ''
    },
    idInstitucion() {
      this.obtenerCatalogoModulo()
    },
  },
  created() {
    this.obtenerCatalogoInstitucion()
  },
  beforeDestroy() {
    this.$recaptcha.destroy()
  },
}
</script>

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

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