<template>
  <div>
            <b-form-row class="custom-form-row">
              <b-form-group class="col-md-6 col-sm-12">
                <postal-code v-model="address_component.postal_code" @change="buscaCEP" />
              </b-form-group>
              <b-form-group class="col-md-3 col-sm-12">
                <text-input v-model="address_component.street" title="Endereço: " place-holder="Rua 001" />
              </b-form-group>
              <b-form-group class="col-md-3 col-sm-12">
                <number-input v-model="address_component.number" @change="updateObject" place-holder="108" />
              </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="address_component.complement"
                  title="Complemento:"
                  place-holder="Qd. 10 Lt. 20"
                  @change="updateObject"
                  />
                </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="address_component.city"
                    :options="cities"
                    id="cities"
                    class="radius-theme"
                  />

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

            <b-form-row class="custom-form-row">

              <b-form-group class="col-md-5 col-sm-12" v-show="neighborhood_not_found">
                <text-input v-model="address_component.neighborhood"
                title="Bairro / Setor: "
                place-holder="Centro"
                @change="updateObject"
                />
                <b-container v-if="!neighborhood_list">
                  <b-row class="mt-1">
                      <b-col class="
                        d-flex
                        justify-content-start
                        align-items-center
                        text-left
                        mb-1
                        akkurat-regular
                        btn-copy"
                      >
                        <div class="text-danger">Fora da definição</div>
                        <b-button class="
                          btn-copy
                          ml-2
                          py-0
                          px-3
                          akkurat-bold
                          btn-green
                          text-center" @click="editNeighborhood">
                          Alterar bairro
                        </b-button>
                        <!-- TODO - put the button here from delivery-schedule -->
                      </b-col>
                  </b-row>
                </b-container>
              </b-form-group>

              <b-form-group class="col-md-5 col-sm-12" v-if="neighborhood_list">
                <div class="text-left label">
                  <label for="marketDefinition">Bairro:</label>
                </div>
                <b-form-select
                    v-model="address_component.marketDefinition"
                    :options="marketDefinitions"
                    @change="selectedMarketDefinition"
                    id="marketDefinition"
                    class="radius-theme"
                  />
                </b-form-group>

              <b-form-group class="col-md-2 col-sm-12">
                <text-input v-model="address_component.state"
                title="Estado:"
                place-holder="Goiás"
                />
              </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="address_component.reference"
                title="Ponto de Referência:"
                place-holder="Próximo ao Supermercado da Vila"
                @change="updateObject"
                />
              </b-form-group>
            </b-form-row>
    </div>
</template>

<script>
import TextInput from '@/components/shared-components/inputs/TextInput.vue';
import NumberInput from '@/components/shared-components/inputs/NumberInput.vue';
import PostalCode from '@/components/shared-components/inputs/PostalCode.vue';
import PhoneNumber from '@/components/shared-components/inputs/PhoneNumber.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: 'address',
  props:{
    status:{
      type: Array
    },
    address:{
      type: Object
    }
  },
  components:{
    TextInput,
    NumberInput,
    PostalCode,
    PhoneNumber
  },
  data: () => ({
    cities: ['SELECIONE UMA CIDADE'],
    marketDefinitions: ["SELECIONE UM BAIRRO"],
    address_component:{
      id: 0,
      marketDefinition: "SELECIONE UM BAIRRO",
      city: 'SELECIONE UMA CIDADE',
      city_ibge: '',
      state: '',
      street: '',
      postal_code: '',
      number: '',
      complement: '',
      reference: '',
      neighborhood: null,
      marketDefinitionID: -1,
      deliverable: false
    },    
    neighborhoods: [],
    neighborhood_not_found: false,
    neighborhood_list: true,
    submit: false
  }),
  methods: {
    updateObject(){
       this.$emit('change', this.address_component);
    },
    editNeighborhood(){
      this.neighborhood_list = true;
    },
    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.address_component.city = city;
          }
          vm.cities.push(element.name);
        });
        vm.cities.push("NÃO ENCONTRADO");

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

    },
    selectedMarketDefinition(){
      if(this.address_component.marketDefinition == "NÃO ENCONTRADO"){
        this.neighborhood_not_found = true;
        return;
      }

      var marketDefinitionID = -1;

      this.neighborhoods.forEach(element => {
          if(element.neighborhood == this.address_component.marketDefinition){
            marketDefinitionID = element.id;
          }
      });
      
      this.address_component.marketDefinitionID = marketDefinitionID;

      this.updateObject();
    },
    buscaCEP(){
      if (this.address_component.postal_code.length >= 8) {
        let vm = this;

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

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

            vm.address_component.state = response.data.uf;
            
            vm.getMarketDefinition(response.data.ibge, neighborhood);
          }
        }).catch(error => {
          console.log(error);
        });
      }
    },
    getMarketDefinition(ibge, neighborhood){
      let vm = this;

      cityService
        .read(ibge)
        .then(response => {
          var found = false;
          this.neighborhoods = response;

          for(var i = 0; i < response.length; i++){
            if(response[i].neighborhood == neighborhood){

              this.address_component.marketDefinitionID = response[i].id;
              this.address_component.marketDefinition = neighborhood;
              this.address_component.neighborhood = neighborhood;
              found = true;

              this.$emit('change', this.address_component);

            }
            vm.marketDefinitions.push(response[i].neighborhood);
          }
          vm.marketDefinitions.push("NÃO ENCONTRADO");

          if(!found || this.outDefinition != -1){
            this.address_component.marketDefinition = "NÃO ENCONTRADO";
            this.neighborhood_not_found = true;
            this.neighborhood_list = false;
            this.neighborhood = this.address_component.neighborhood;
          }


        })
        .catch(err => {
          console.log(err);
        });
    },
  },
  computed:{
    outDefinition(){
      for(var i = 0; i < this.status.length; i++){
        if(this.status[i].status == 'OUT_DEFINITION' && !this.status[i].approved){
          return this.status[i].id;
        }
      }

      return -1;
    }
  },
  mounted(){

    this.address_component.id =  this.address.id;
    this.address_component.postal_code = this.address.postal_code;
    this.address_component.complement = this.address.complement;
    this.address_component.number = this.address.number;
    this.address_component.reference = this.address.reference;
  }

};
</script>

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

.wrap-modal-body{
  height: 400px;
  overflow-y: auto;
}
.modal-text-color {
  color: #3E3E3E;
}

.min-header-text {
  letter-spacing: 0.2px;
  font-size: 9px;
}

.max-header-text {
  letter-spacing: 0.4px;
  font-size: 16px;
}


.close-icon {
  color: #979797;
  font-size: 20px;
}

.btn-default {
  border-radius: 20px;
  width: 100%;
  max-width: 192px;
  height: 35px;
  background: #278937;
}

.btn-red {
  background: #CB2D2D;
}

.btn-copy {
  font-size: 12px;
}

</style>
