<template>
  <div>
    <b-row>
      <b-col md="12">
        <h2 class="text-left">Endereço de entrega</h2>
      </b-col>
      <b-col md="12">
        
        <address-form v-model="shipping_address" :submit="submit" />

        <div v-if="hasBillingAddress">
          <hr class="col-md-6" />

            <address-form v-model="billing_address" :submit="submit" />
        
        </div>

        <b-row>
          <b-col md="6">
            <p
              class="link-hasBillingAddres text-danger"
              v-if="!hasBillingAddress"
              @click="showBilliAddress(true)"
            >
              + Se você quiser um outro endereço
              para cobrança - clique aqui!
            </p>

            <p
              class="link-hasBillingAddres text-danger"
              v-if="hasBillingAddress"
              @click="showBilliAddress(false)"
            >- Clique aqui para remover o endereço de Cobrança!</p>
          </b-col>
          <b-col md="6" v-if="enabledToNext">
            <p style="line-height: 5em;" class="text-right text-middle">
              <b-button
                variant="warning"
                class="col-md-6"
                size="larger"
                @click="$emit('next')"
              > <b-spinner small type="grow" v-show="loading"></b-spinner> CONTINUAR</b-button>
            </p>
          </b-col>

<b-col md="6"  v-if="!enabledToNext">
            <p style="line-height: 5em;" class="text-right text-middle">
              <b-button
                variant="primary"
                class="col-md-6"
                size="larger"
                @click="attachFile"
                :disabled="submit && (!shipping_address.isValid() || (hasBillingAddress && !billing_address.isValid()))"
              >ANEXAR COMPROVANTE DE ENDEREÇO 
              
              <span v-if="shipping_address.proof.length === 0"> (ENTREGA)</span>
              <span v-else-if="hasBillingAddress && billing_address.proof.length === 0"> (COBRANÇA)</span>

              </b-button>
            </p>
          </b-col>


        </b-row>
      </b-col>
    </b-row>
    <shipping-modal  @modalClosed="storeAddress" />
    <billing-modal  @modalClosed="storeAddress($event,'billing_address')"/>
    <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 PostalCode from "@/components/shared-components/inputs/PostalCode.vue";
import NumberInput from "@/components/shared-components/inputs/NumberInput.vue";
import shippingModal from "@/components/modals/selfSignUp/addressShipping";
import billingModal from "@/components/modals/selfSignUp/addressBilling";
import {objectToFormData} from "@/utils/convert.js"
import SelfSignUp from "@/services/resources/SelfSignUpService";
import MessageModal from "@/components/modals/MessageModal.vue";
import AddressForm from "@/components/shared-components/forms/address"
import axios from "axios";

import AddressModel from "@/models/AddressModel.js";

const service = SelfSignUp.build();

export default {
  props:{
    id:{
      default(){
        return 0;
      }
    },
    token:{
      default(){
        return "";
      }
    },
    cpf:{
      default(){
        return "";
      }
    }
  },
  components: {
    TextInput,
    Cpf,
    Email,
    PhoneNumber,
    DateInput,
    PostalCode,
    NumberInput,
    billingModal,
    shippingModal,
    MessageModal,
    AddressForm
  },
  data() {
    return {
      shipping_address: new AddressModel(),
      billing_address: new AddressModel(),
      alertMessage: "",
      hasBillingAddress: false,
     loading: false,
     submit:false
    };
  },
  computed:{
     enabledToNext(){

if(this.hasBillingAddress){

return this.shipping_address.proof.length > 0 &&  this.billing_address.proof.length > 0;

}else{
    return this.shipping_address.proof.length > 0 ;
}
        
     }
  },
  methods: {
    showBilliAddress(hasBillingAddress) {
      this.hasBillingAddress = hasBillingAddress;
    },

    storeAddress(file, address = 'shipping_address'){
      this[address].proof = file;

  let formToSend = {
    token: this.token,
    id: this.id,
    cpf: this.cpf,
    };

    formToSend[address] = {};

      Object.assign(formToSend[address], this[address]);

      let formData = objectToFormData(formToSend);

this.store(formData);

},
    store(form){
   var vm = this;
  form.append('_method','PUT');
      service
        .update(form)
        .then(response => {
       vm.next();
        })
        .catch(err => {
          console.log(err);
            let resp = JSON.parse(err.response.data);
          vm.alertMessage = resp.msg;
          vm.$bvModal.show("message-modal");
        });
    

    },
    next(){

if(this.hasBillingAddress && this.billing_address.proof != ""
||
!this.hasBillingAddress && this.shipping_address.proof != ""
){

  this.$emit('next',{token: this.token, id: this.id, cpf: this.cpf});
}

    },
    attachFile(){
      
if(!this.shipping_address.isValid() || (this.hasBillingAddress && !this.billing_address.isValid())){
  this.alertMessage = `Por favor preencha o endereço corretamente`;
        this.$bvModal.show("message-modal");
        this.submit = true;
  return;
}
      
if( this.shipping_address.proof === "" ){
        
        this.$modal.show("address-shipping");
    }else if( this.billing_address.proof === "" ){
        
        this.$modal.show("address-billing");
    }

    },
    buscaCEP( teste, address = 'shipping_address') {
    
      if (this[address].postal_code.length >= 8) {
        let vm = this;

        axios
          .get(
            "https://viacep.com.br/ws/" +
              this[address].postal_code +
              "/json"
          )
          .then(response => {
            console.log(response);
            if (
              typeof response.data.erro != "undefined" &&
              response.data.erro
            ) {
              //  vm.marketDefinitions.push("NÃO ENCONTRADO");
            } else {
              console.log("ok");
              vm[address].code_ibge = response.data.ibge;
                vm[address].street = response.data.logradouro;
                vm[address].city = response.data.localidade;

                vm[address].neighborhood = response.data.bairro;

                vm[address].uf = response.data.uf;
            }
          })
          .catch(error => {
            console.log(error);
          });
      }
    },
    processNeighborhood(text) {
      var neighborhood = text
        .normalize("NFD")
        .replace(/[\u0300-\u036f]/g, "")
        .toUpperCase();
      neighborhood = neighborhood.replace("BAIRRO", "BR");
      neighborhood = neighborhood.replace("SETOR", "ST");
      neighborhood = neighborhood.replace("JARDIM", "JD");
      neighborhood = neighborhood.replace("JARDINS", "JD");
      neighborhood = neighborhood.replace("VILA", "VL");
      neighborhood = neighborhood.replace("RESIDENCIAL", "RES");
      neighborhood = neighborhood.replace("LOTEAMENTO", "LOT");
      neighborhood = neighborhood.replace("CONJUNTO", "CONJ");
      neighborhood = neighborhood.replace("CONDOMINIO", "COND");
      neighborhood = neighborhood.replace("CHACARA", "CHAC");
      neighborhood = neighborhood.replace("POVOADO", "POV");
      neighborhood = neighborhood.replace("COLONIA", "COL");
      neighborhood = neighborhood.replace("PARQUE", "PQ");

      return neighborhood;
    },
    
  }
};
</script>

<style lang="scss" >
.group-type-address {
  legend.col-form-label {
    padding-bottom: 0px !important;
  }
  .custom-control-label {
    &::before,
    &::after {
      opacity: 0;
    }
  }

  .custom-radio {
    padding-left: 12px;
  }
  input[type="radio"] {
    margin-left: -16px !important;
  }
}
h2 {
  font-size: 0.9em;
}
.link-hasBillingAddres {
  cursor: pointer;
  &:hover,
  &:active {
    text-decoration: underline;
  }
}
</style>