<template>
  <div>
    <b-row>
      <b-col md="12">
        <b-row>
          <b-form-group class="col-md-12 col-sm-12">
            <cpf title="CPF*" v-model="getCurrentValue.cpf" :submit="submit" />
          </b-form-group>

          <b-form-group class="col-md-12 col-sm-12">
            <text-input title="Nome Completo*" place-holder="Lucia Matias" v-model="getCurrentValue.name" />
            <div class="text-left" v-show="submit && !getCurrentValue.nameIsValid()">
              <small class="pt-2 text-danger">Nome completo</small>
            </div>
          </b-form-group>

          <b-form-group class="col-md-12 col-sm-12">
            <email title="E-mail*" email v-model="getCurrentValue.email" :submit="submit" />
          </b-form-group>

          <b-form-group class="col-md-12 col-sm-12">
            <email title="Confirmar e-mail*" email v-model="getCurrentValue.email_confirmation" />
            <div class="text-left" v-show="submit && !getCurrentValue.emailConfirmationIsValid()">
              <small class="pt-2 text-danger">Email de confirmação inválido</small>
            </div>
          </b-form-group>

          <b-form-group class="col-md-6">
            <phone-number
              title="Celular*"
              :phoneNumber="getCurrentValue.phone"
              :submit="submit"
              v-model="getCurrentValue.phone"
            />
          </b-form-group>

          <b-form-group class="col-md-6">
            <date-input title="Nascimento*" currentDate="1991-03-10" v-model="getCurrentValue.birth_date" />
            <div class="text-left" v-show="submit && !getCurrentValue.birthDateIsValid()">
              <small class="pt-2 text-danger">Cadastro aceito apenas para maiores de idade</small>
            </div>
          </b-form-group>

          <b-form-group class="col-md-6">
            <text-input
              title="CÓDIGO DE CONFIRMAÇÃO*"
              :disabled="!phoneCodeSended"
              v-model="getCurrentValue.phone_verification"
              place-holder
            />
            <span v-if="phoneCodeSended">Código de confirmação enviado via SMS.

<a href="#" @click.prevent="updateSelfSignup(true)">reenviar o código</a>

            </span>
          </b-form-group>

          <b-col md="6" v-if="!phoneConfirmed">
            <p style="line-height: 5em;" class="text-left text-middle">
              <b-button
                variant="primary"
                class="col-md-6"
                size="larger"
                @click="store()"
                :disabled=" (submit && !getCurrentValue.isValid()) || loading"
              >  <b-spinner small type="grow" v-show="loading"></b-spinner> Enviar Código</b-button>
            </p>
          </b-col>

          <b-col md="6" v-if="phoneConfirmed">
            <p style="line-height: 5em;" class="text-left text-middle">
              <b-button
                variant="warning"
                class="col-md-6"
                size="larger"
                :disabled="loading"
                @click="updateSelfSignup(false)"
              > <b-spinner small type="grow" v-show="loading"></b-spinner> CONTINUAR</b-button>
            </p>
          </b-col>
        </b-row>
      </b-col>
    </b-row>


    <!-- #################### Modals #################### -->

    <message-modal :message="alertMessage" />
  </div>
</template>

<script>
import TextInput from "@/components/shared-components/inputs/TextInput.vue";
import Cpf from "@/components/shared-components/inputs/Cpf.vue";
import PhoneNumber from "@/components/shared-components/inputs/PhoneNumber.vue";
import Email from "@/components/shared-components/inputs/Email.vue";
import DateInput from "@/components/shared-components/inputs/DateInput.vue";
import SelfSignUp from "@/services/resources/SelfSignUpService";

import MessageModal from "@/components/modals/MessageModal.vue";

import moment from "moment";
import SelfSignupModel from "@/models/SelfSignupModel.js";

const service = SelfSignUp.build();

export default {
  props:{
    form:{
      type: SelfSignupModel
    }
  },
  model:{
    prop: 'form',
    event: 'change'
  },
  components: {
    TextInput,
    Cpf,
    Email,
    PhoneNumber,
    DateInput,
    MessageModal,
  },
  data() {
    return {
      submit: false,
      phoneConfirmed: false,
      phoneCodeSended: false,
      alertMessage: "",
      id: 11,
      token: "",
    loading: false
    };
  },
  computed:{
getCurrentValue: {
      get() {
        return this.form;
      },
      set(value) {
        this.$emit('change', value);
      },
    }
  },
  methods: {
    getdate() {
      return moment().format("YYYY-MM-DD");
    },
    searchCPF() {
      if (this.cpf.length === 11) {
        this.searchCPFOnSalesConsultant();
      }
    },
    store() {
      if (!this.getCurrentValue.isValid()) {
        this.submit = true;
        this.alertMessage = `Não foi possível enviar o código de confirmação.
                        Por favor, verifique o formulário.`;
        this.$bvModal.show("message-modal");
        return;
      }

      var vm = this;
      this.loading = true;
      service
        .create(this.getCurrentValue)
        .then(response => {
        vm.token = response.data.token;
        vm.id = response.data.id;
          vm.sendConfirmationCode();
          vm.loading = false;
          vm.saveToken();
        })
        .catch(err => {
         
          let resp = JSON.parse(err.response.data);
          vm.alertMessage = resp.msg;
          vm.$bvModal.show("message-modal");
          vm.loading = false;
        });
    },
    updateSelfSignup(sendNewCode = false){
       var vm = this;
       let formToSend = {
         token: this.token,
         id: this.id,
         _method: 'PUT'
       };

if(sendNewCode){

formToSend['send_new_code'] = true;

}

       Object.assign(formToSend, this.getCurrentValue);
this.loading = true;
      service
        .update(formToSend)
        .then(response => {

if(!sendNewCode){

         vm.$emit('next',{token: vm.token, id: vm.id, cpf: vm.getCurrentValue.cpf});
}else{
   vm.alertMessage = response.msg;
          vm.$bvModal.show("message-modal");
}

         vm.loading = false;
        })
        .catch(err => {
            let resp = JSON.parse(err.response.data);
          vm.alertMessage = resp.msg;
          vm.$bvModal.show("message-modal");
          vm.loading = false;
        });
    },
    searchCPFOnSelfSignup() {},
    sendConfirmationCode() {
      this.phoneConfirmed = true;
      this.phoneCodeSended = true;
    },
    saveToken(){
       localStorage.setItem(
        "self-signup",
        JSON.stringify({
          id: this.id,
          token: this.token,
          cpf: this.getCurrentValue.cpf,
          stepActive: 1
        })
      );
    }
  },
};
</script>

