<template>
<div>
  <div>
    <b-row class="mb-3" >
      <b-col>
        <div class="
          d-flex
          justify-content-start
          align-items-center
          text-left
          mb-1
          akkurat-regular"
        >
          {{ title }}
          <b-button class="
            btn-copy
            ml-2
            py-0
            px-3
            akkurat-bold
            btn-green
            text-center" @click="copyAddress"
            v-show="!isChargeAddress">
            Copiar o endereço de cobrança
          </b-button>
          <!-- TODO - put the button here from delivery-schedule -->
        </div>
        <div class="profile-card px-2 pt-3 pb-0">
          <b-form>
            <b-form-row class="custom-form-row">
              <b-form-group class="col-md-6 col-sm-12">
                <postal-code v-model="postal_code" @change="buscaCEP" :submit="submit" />
              </b-form-group>
              <b-form-group class="col-md-3 col-sm-12">
                <text-input v-model="street" title="Endereço: " place-holder="Rua 001" :submit="submit" />
              </b-form-group>
              <b-form-group class="col-md-3 col-sm-12">
                <number-input v-model="number" place-holder="108" :submit="submit"/>
              </b-form-group>
            </b-form-row>

            <b-form-row class="custom-form-row">
              <b-form-group class="col-md-4 col-sm-12">
                <text-input v-model="complement"
                  title="Complemento:"
                  place-holder="Qd. 10 Lt. 20"
                  :submit="submit"
                  />
                </b-form-group>

                 <b-form-group class="col-md-6 col-sm-12">
                  <div class="text-left label"><label for="cities">Cidade:</label></div>
                  <b-form-select
                    v-model="city"
                    :options="cities"
                    @change="selectedMarketDefinition"
                    id="cities"
                    class="radius-theme"
                  />

                </b-form-group>
        
            </b-form-row>

            <b-form-row class="custom-form-row">
             
              <b-form-group class="col-md-4 col-sm-12">
                <div class="text-left label"><label for="marketDefinition">Bairro:</label></div>
                <b-form-select
                    v-model="marketDefinition"
                    :options="marketDefinitions"
                    @change="selectedMarketDefinition"
                    id="marketDefinition"
                    class="radius-theme"
                  />
                  <p v-if="submit && marketDefinition == 'SELECIONE UM BAIRRO'" class="text-left text-danger">
                    Selecione o bairro
                  </p>
                </b-form-group>

              <b-form-group class="col-md-4 col-sm-12" v-show="neighborhood_not_found">
                <text-input v-model="neighborhood"
                title="Bairro / Setor: "
                place-holder="Centro"
                />
              </b-form-group>

              <b-form-group class="col-md-4 col-sm-12">
                <text-input v-model="state"
                title="Estado:"
                place-holder="Goiás"
                :submit="submit"
                />
              </b-form-group>
            </b-form-row>

            <b-form-row class="custom-form-row">
              <b-form-group class="col-md-12 col-sm-12">
                <text-input v-model="reference"
                title="Ponto de Referência:"
                place-holder="Próximo ao Supermercado da Vila"
                :submit="submit"
                />
              </b-form-group>
            </b-form-row>
          </b-form>
        </div>
      </b-col>
    </b-row>
    <b-row class="mb-2">
      <b-col class="d-flex justify-content-center align-items-center mt-3">
        <signup-button title="Voltar" icon="user-friends" btn-color="#FF9B64"
        class="align-self-center" :router-name="getBackRoute" />
        <signup-button title="Continuar" icon="user-friends" btn-color="#278937"
        class="align-self-center" @clicked="continueRegister"/>
      </b-col>
    </b-row>
  </div>
</div>
</template>

<script>
import TextInput from '@/components/shared-components/inputs/TextInput.vue';
import PostalCode from '@/components/shared-components/inputs/PostalCode.vue';
import NumberInput from '@/components/shared-components/inputs/NumberInput.vue';
import SignupButton from '@/components/signup/SignupButton.vue';
import SalesConsultantsWebService from "@/services/resources/SalesConsultantsWebService";
import CityService from "@/services/resources/CityService";

import axios from 'axios';

const service = SalesConsultantsWebService.build();
const cityService = CityService.build();


export default {
  name: 'charge-delivery-address',
  props:{
    title: {
      type: String,
      default: 'Endereço de Cobrança',
    },
  },
  components: {
    TextInput,
    PostalCode,
    NumberInput,
    SignupButton
  },
  data: () => ({
    city: 'SELECIONE UMA CIDADE',
    cities: ['SELECIONE UMA CIDADE'],
    city_ibge: '',
    marketDefinition: "SELECIONE UM BAIRRO",
    marketDefinitions: ["SELECIONE UM BAIRRO"],
    state: '',
    street: '',
    postal_code: '',
    number: '',
    complement: '',
    reference: '',
    file: null,
    neighborhoods: [],
    neighborhood: null,
    neighborhood_not_found: false,
    routeName: 'Endereço de Cobrança',
    billing_address_component: null,
    shipping_address_component: null,
    submit: false,
    cpf: '',
    contacts: [],
    campaign_code: '',
    spc_restrition: '',
    name: '',
    gender: '',
    docId: '',
    govAgent: '',
    birthDate: '',
    motherName: '',
    whoIndicated:'',
    email: '',
    person: '',
    billing_address: {},
    shipping_address: {}
  }),
  computed: {
    isChargeAddress() {
      return this.title === 'Endereço de Cobrança';
    },
    billing_address_computed:{
      get(){
        return this.billing_address_component || this.billing_address;
      },
      set(new_object){
        this.billing_address_component = new_object;
      }
    },
    shipping_address_computed:{
      get(){
        return this.shipping_address_component || this.shipping_address;
      },
      set(new_object){
        this.shipping_address_component = new_object;
      }
    },
    getBackRoute(){
      return this.isChargeAddress ? 'Contatos' : 'Endereço de Cobrança';
    }
  },
  methods: {
    copyAddress() {
      this.city = this.billing_address.city;
      this.postal_code = this.billing_address.postal_code;
      this.street = this.billing_address.street;
      this.complement = this.billing_address.complement;
      this.reference = this.billing_address.reference;
      this.number = this.billing_address.number;
      this.state = this.billing_address.state;
      this.neighborhood = this.billing_address.neighborhood;
      this.marketDefinitionID = this.billing_address.marketDefinitionID;
      if(this.marketDefinitionID == -1){
        this.marketDefinition = "NÃO ENCONTRADO";
        this.neighborhood_not_found = true;
      }
    },
    buscaCEP(){
      if (this.postal_code.length >= 8 ) {
        let vm = this;

        axios
        .get('https://viacep.com.br/ws/' + this.postal_code + '/json')
        .then(response => {
          if(typeof response.data.erro != 'undefined' && response.data.erro){
            vm.marketDefinitions.push("NÃO ENCONTRADO");
          }else{
            vm.city_ibge = response.data.ibge;
            vm.street = response.data.logradouro;
            vm.getCities(response.data.localidade, response.data.uf);

            var neighborhood = this.processNeighborhood(response.data.bairro);

            vm.state = response.data.uf;
            
            vm.getMarketDefinition(response.data.ibge, neighborhood);
          }
        }).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;
    },
    getCities(city, state_uf){
      var city = city.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toUpperCase();

      let filters = {
        state_uf: state_uf
      };

      let vm = this;

      cityService
      .search(filters)
      .then(response => {


        response.forEach(element => {
          element.name = element.name.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toUpperCase();

          if(element.name == city){
            this.city = city;
          }
          vm.cities.push(element.name);
        });
        vm.cities.push("NÃO ENCONTRADO");

      })
      .catch(err => {
        console.log(err);
      });

    },
    getMarketDefinition(ibge, neighborhood){
      let vm = this;

      cityService
        .read(ibge)
        .then(response => {

          vm.neighborhoods = response;

          response.forEach(element => {
            if(element.neighborhood == neighborhood){
              this.marketDefinition = neighborhood;
            }
            vm.marketDefinitions.push(element.neighborhood);
          });
          vm.marketDefinitions.push("NÃO ENCONTRADO");

        })
        .catch(err => {
          console.log(err);
        });
    },
    selectedMarketDefinition(){
      if(this.marketDefinition == "NÃO ENCONTRADO"){
        this.neighborhood_not_found = true;
      }else{
        this.neighborhood_not_found = false;
      }
    },
    continueRegister(){
       if(this.checkFields()){

        let vm = this;
        var marketDefinitionID = -1;
        
        if(this.marketDefinition != "NÃO ENCONTRADO"){
          this.neighborhoods.forEach(element => {
              if(element.neighborhood == this.marketDefinition){
                marketDefinitionID = element.id;
              }
          });
        }

        if(this.isChargeAddress){
          var name = 'Endereço de Entrega';

          this.billing_address_computed = {
            postal_code: this.postal_code,
            street: this.street,
            complement: this.complement,
            number: this.number,
            reference: this.reference,
            city_ibge: this.city_ibge,
            city: this.city,
            state: this.state,
            neighborhood: this.neighborhood || this.marketDefinition,
            marketDefinitionID: marketDefinitionID,
            deliverable: false
          };
        }else{
          var name = 'Complemento';

          this.shipping_address_computed = {
            postal_code: this.postal_code,
            street: this.street,
            complement: this.complement,
            number: this.number,
            reference: this.reference,
            city_ibge: this.city_ibge,
            city: this.city,
            state: this.state,
            neighborhood: this.neighborhood || this.marketDefinition,
            marketDefinitionID: marketDefinitionID,
            deliverable: false
          }; 
        }

        let data = {
          cpf: this.cpf,
          campaign_code: this.campaign_code,
          spc_restrition: this.spc_restrition,
          name: this.name,
          email: this.email,
          gender: this.gender,
          docId: this.docId,
          govAgent: this.govAgent,
          birthDate: this.birthDate,
          motherName: this.motherName,
          whoIndicated: this.whoIndicated,
          contacts: this.contacts,
          billing_address: this.billing_address_computed,
          shipping_address: this.shipping_address_computed
        };
        localStorage.step_4 = JSON.stringify(data);

        this.$router.push({
          name: name
        });

       }

    },
    checkFields(){
      if(this.postal_code.length == 0 || this.street.length == 0 || this.complement.length == 0 || this.number.length == 0 || this.reference.length == 0 || this.city.length == 0 || this.marketDefinition == "SELECIONE UM BAIRRO" ){
        this.submit = true;
        return false;
      }

      return true;
    }
  },
  mounted(){
    if(!localStorage.step_2){
      this.$router.push({
            name: 'Documentos'
      });
    }

    var data;
    
    if(this.isChargeAddress){
      if(localStorage.step_4){
        data = JSON.parse(localStorage.step_4);
        
        this.postal_code = data.billing_address.postal_code;
        this.street = data.billing_address.street;
        this.number = data.billing_address.number;
        this.complement = data.billing_address.complement;
        this.reference = data.billing_address.reference;
        this.city_ibge = data.billing_address.city_ibge;
        this.city = data.billing_address.city;
        this.neighborhood = data.billing_address.neighborhood;
        this.marketDefinition = data.billing_address.neighborhood;
        
        
      
      }else{
        data = JSON.parse(localStorage.step_3);
      }
    }else{
      data = JSON.parse(localStorage.step_4);

    if(typeof data.shipping_address.postal_code != 'undefined'){
        this.postal_code = data.shipping_address.postal_code;
        this.street = data.shipping_address.street;
        this.number = data.shipping_address.number;
        this.complement = data.shipping_address.complement;
        this.reference = data.shipping_address.reference;
        this.city_ibge = data.shipping_address.city_ibge;
        this.city = data.shipping_address.city;
        this.neighborhood = data.shipping_address.neighborhood;
        this.marketDefinition = data.shipping_address.neighborhood;
      }
    }

    this.billing_address = data.billing_address;
    this.shipping_address = data.shipping_address;

data = JSON.parse(localStorage.step_3);//atualizar dados que vieram de steps anteriores
    this.cpf = data.cpf;
    this.campaign_code = data.campaign_code;
    this.spc_restrition = data.spc_restrition;
    this.name = data.name;
    this.email = data.email;
    this.gender = data.gender;
    this.docId = data.docId;
    this.govAgent = data.govAgent;
    this.birthDate = data.birthDate;
    this.motherName = data.motherName;
    this.whoIndicated = data.whoIndicated;
    this.contacts = data.contacts;
    
  
  }
};
</script>

<style scoped lang="scss">
@import '../../assets/css/main.scss';
@import '../../assets/css/cards.scss';

.custom-width {
  width: 25%;
}

.btn-copy {
  font-size: 12px;
}
</style>
