<template>
  <b-modal id="edit-modal" size="lg" :no-close-on-backdrop="true">
    <template v-slot:modal-header="{  }">
      <b-container>
      <b-row class="d-flex justify-content-between mb-2 mt-1">
        <b-col class="d-flex modal-text-color ml-2" cols="8">
          <div class="d-flex align-self-center justify-content-center rounded-div mr-2 mt-1">
            <font-awesome-icon icon="exclamation-circle" class="align-self-center" />
          </div>
          <div class="pt-1">
            <div class="akkurat-bold max-header-text">Editar informaçoes</div>
          </div>
        </b-col>
        <b-col class="d-flex justify-content-end mr-2 mt-1">
          <span class="close-icon" @click="closeModal">
            <font-awesome-icon icon="times" class="align-self-center" />
          </span>
        </b-col>
      </b-row>
      </b-container>
    </template>

    <b-container>
     <b-row>
       <b-col>
         <b-form>
           <h4>Dados pessoais **</h4>
            <b-form-row class="custom-form-row">
              <b-form-group class="col-md-6 col-sm-12">
                <text-input v-model="name" title="Nome Completo" place-holder="Lucia Matias" />
              </b-form-group>
              <b-form-group class="col-md-3 col-sm-12">
                <div class="text-left label"><label for="gender">Sexo:</label></div>
                <b-form-select
                  v-model="selectedGender"
                  :options="genderOptions"
                  id="gender"
                  class="radius-theme"
                />
              </b-form-group>
              <b-form-group class="col-md-3 col-sm-12">
                <date-input v-model="birthDate" />
              </b-form-group>
            </b-form-row>

            <b-form-row class="custom-form-row">
              <b-form-group class="col-md-4 col-sm-12">
                <cpf v-model="cpf" />
              </b-form-group>
              <b-form-group class="col-md-4 col-sm-12">
                <number-input v-model="docId" title="Número de identificação:"/>
              </b-form-group>
              <b-form-group class="col-md-4 col-sm-12">
                <gov-agent v-model="govAgent"  />
              </b-form-group>
            </b-form-row>

            <b-form-row class="custom-form-row">
              <b-form-group class="col-md-6 col-sm-12">
                <text-input v-model="motherName"
                  title="Nome da Mãe:"
                  place-holder="Luzia da Silva"
                />
              </b-form-group>

            </b-form-row>

            <h4>Contatos</h4>
            
            <b-form-row class="custom-form-row">
              <b-form-group class="col-md-6 col-sm-12">
                <email v-model="email" :submit="submit"/>
              </b-form-group>
              <b-form-group class="col-md-6 col-sm-12">
                <phone-number v-model="mobilePhone" :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">
                <phone-number
                  title="Telefone"
                  v-model="residentialPhone"
                  place-holder="62 3030-3030"
                  :is_cellphone="false"
                  :submit="submit"
                />
              </b-form-group>
              <b-form-group class="col-md-4 col-sm-12">
                <phone-number
                  title="Telefone para Recado"
                  v-model="phoneToMessage"
                  place-holder="62 3131-3131"
                  :is_cellphone="false"
                  :submit="submit"
                />
              </b-form-group>
              <b-form-group class="col-md-4 col-sm-12">
                <text-input v-model="person" place-holder="Joana vizinha" title="Falar com:" :submit="submit" />
              </b-form-group>
            </b-form-row>

            <!-- Billing Address -->
            <h4>Endereço de cobrança</h4>
            <address-component :address="billing_address" :status="sales_consultant.status" @change="changeBilling" />
            
            <!-- Shipping Address -->
            <h4>Endereço de entrega</h4>
            <div class="
                d-flex
                justify-content-start
                align-items-center
                text-left
                mb-1
                akkurat-regular"
              >
                <b-button class="
                  btn-copy
                  ml-2
                  py-0
                  px-3
                  akkurat-bold
                  btn-green
                  text-center" @click="copyAddress">
                  Copiar o endereço de cobrança
                </b-button>
                <!-- TODO - put the button here from delivery-schedule -->
              </div>
             <address-component :address="shipping_address" :status="sales_consultant.status" @change="changeShipping" />

            <h4>Complemento</h4>
            <b-form-row class="custom-form-row">
             <b-form-group class="col-md-6 col-sm-12">
                <div class="text-left label"><label for="residence">Tipo de Residência:</label></div>

                <b-form-select
                  v-model="selectedResidence"
                  :options="residenceOptions"
                  id="residence"
                  class="radius-theme"
                />

              </b-form-group>
              <b-form-group class="col-md-6 col-sm-12">
                <div class="text-left label"><label for="voltage">Voltagem:</label></div>
                <b-form-select
                  v-model="selectedVoltage"
                  :options="voltageOptions"
                  id="voltage"
                  class="radius-theme"
                />
              </b-form-group>
            </b-form-row>

            <b-form-row class="custom-form-row">
              <b-form-group class="col-md-6 col-sm-12">
                <div class="text-left label">
                  <label for="voltage">Há entrega pelos correios:</label>
                </div>
                <b-form-select
                  v-model="selectedHasDelivery"
                  :options="deliveryOptions"
                  id="voltage"
                  class="radius-theme"
                />
              </b-form-group>
              <b-form-group class="col-md-6 col-sm-12">
                <number-input v-model="section"
                :submit="submit"
                title="Seção:"
                place-holder="Informar Seção"
              />
            </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="otherBrands"
                title="Trabalha com outras marcas de venda direta? Quais?"
              />
            </b-form-group>
            </b-form-row>

          </b-form>

       </b-col>
     </b-row>
    </b-container>
     
    <template v-slot:modal-footer="{  }">
      <b-container>
      <b-row>
        <b-col cols="12" class="d-flex justify-content-center my-3 px-3">
          <b-button
              class="mr-2 btn shadow-none border-0 btn-default btn-red"
              @click="closeModal"
            >
              Cancelar
          </b-button>
          
          <b-button
            class="mr-2 btn shadow-none border-0 btn-default"
            @click="done"
          >
            Salvar
          </b-button>
        </b-col>
      </b-row>
      </b-container>
    </template>

  </b-modal>
</template>

<script>
import TextInput from '@/components/shared-components/inputs/TextInput.vue';
import Cpf from '@/components/shared-components/inputs/Cpf.vue';
import NumberInput from '@/components/shared-components/inputs/NumberInput.vue';
import GovAgent from '@/components/shared-components/inputs/GovAgent.vue';
import DateInput from '@/components/shared-components/inputs/DateInput.vue';
import PostalCode from '@/components/shared-components/inputs/PostalCode.vue';
import Email from '@/components/shared-components/inputs/Email.vue';
import PhoneNumber from '@/components/shared-components/inputs/PhoneNumber.vue';
import AddressComponent from '@/components/solicitations/solicitations-list/waiting-analyze/modals/AddressComponent.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: 'accept-credit-card',
  components:{
    Cpf,
    GovAgent,
    DateInput,
    TextInput,
    NumberInput,
    PostalCode,
    Email,
    PhoneNumber,
    AddressComponent
  },
  props:{
    sales_consultant:{
      type: Object
    },
    isPending:{
      type: Boolean,
      default: false
    }
  },
  data: () => ({
    cpf: '',
    name: '',
    docId: '',
    gender: '',
    govAgent: '',
    birthDate: '',
    motherName: '',
    whoIndicated: '',
    section: '',
    email: '',
    mobilePhone: '',
    residentialPhone: '',
    phoneToMessage: '',
    person: '',
    selectedGender: 'female',
    genderOptions: [
      { text: 'Feminino', value: 'female' },
      { text: 'Masculino', value: 'male' },
    ],
    shipping_address:{
      city: 'SELECIONE UMA CIDADE',
      state: '',
      street: '',
      postal_code: '',
      number: '',
      complement: '',
      reference: ''
    },
    billing_address:{
      city: 'SELECIONE UMA CIDADE',
      state: '',
      street: '',
      postal_code: '',
      number: '',
      complement: '',
      reference: ''
    },
    otherBrands: '',
    selectedResidence: 'OWN',
    selectedVoltage: '110',
    selectedHasDelivery: true,
    residenceOptions:[
      { text: 'Casa Própria', value: 'OWN' },
      { text: 'Casa Alugada', value: 'RENTED' },
      { text: 'Casa Cedida', value: 'CEDED' }
    ],
    voltageOptions: [
      { text: '110v', value: '110' },
      { text: '220v', value: '220' },
    ],
    deliveryOptions: [
      { text: 'Sim', value: true },
      { text: 'Não', value: false },
    ],
    neighborhood: null,
    neighborhoods: [],
    neighborhood_not_found: false,
    neighborhood_list: true,
    submit: false
  }),
  methods: {
    closeModal() {
      this.$emit('edited');
      this.$modal.hide('edit-modal');
    },
    changeBilling(result){
      this.billing_address = result;
    },
    changeShipping(result){
      this.shipping_address = result;
    },
    copyAddress(){
      
      this.shipping_address.postal_code = this.billing_address.postal_code;
      this.shipping_address.marketDefinition = this.billing_address.marketDefinition;
      this.shipping_address.city = this.billing_address.city;
      this.shipping_address.city_ibge = this.billing_address.city_ibge;
      this.shipping_address.street = this.billing_address.street;
      this.shipping_address.state = this.billing_address.state;
      this.shipping_address.reference = this.billing_address.reference;
      this.shipping_address.number = this.billing_address.number;
      this.shipping_address.complement = this.billing_address.complement;
      this.shipping_address.neighborhood = this.billing_address.neighborhood;
      this.shipping_address.marketDefinitionID = this.billing_address.marketDefinitionID;
      this.shipping_address.deliverable = this.billing_address.deliverable;
    },
    done(){
      let vm = this;

      var contacts = [];

      contacts.push({
        id: this.sales_consultant.contacts.length >= 1 ?  this.sales_consultant.contacts[0].id : null,
        is_cellphone: true, 
        is_whatsapp: false,
        is_note: false,
        ddd: String(this.mobilePhone).substr(0, 2),
        number: String(this.mobilePhone).substr(2, String(this.mobilePhone).length),
        is_verified: this.sales_consultant.contacts.length >= 1  ? this.sales_consultant.contacts[0].is_verified : false,
        is_principal: true        
      });
      

      contacts.push({
        id: this.sales_consultant.contacts.length >= 2 ? this.sales_consultant.contacts[1].id : null,
        is_cellphone: false, 
        is_whatsapp: false,
        is_note: false,
        ddd: String(this.residentialPhone).substr(0, 2),
        number: String(this.residentialPhone).substr(2, String(this.residentialPhone).length),
        is_verified: this.sales_consultant.contacts.length >= 2 ? this.sales_consultant.contacts[1].is_verified : false,
        is_principal: false        
      });
      
      contacts.push({
        id: this.sales_consultant.contacts.length >= 3 ? this.sales_consultant.contacts[2].id : null,
        name: this.person,
        is_cellphone: false, 
        is_whatsapp: false,
        is_note: true,
        ddd: String(this.phoneToMessage).substr(0, 2),
        number: String(this.phoneToMessage).substr(2, String(this.phoneToMessage).length),
        is_verified: this.sales_consultant.contacts.length >= 3 ?  this.sales_consultant.contacts[2].is_verified : false,
        is_principal: false        
      });



      let data = {
        id: this.sales_consultant.id,
        _method: 'PUT',
        pending: this.isPending,
        contacts: contacts,
        name: this.name,
        cpf: this.cpf,
        email: this.email,
        sex: this.selectedGender,
        mother_name: this.motherName,
        birthday: this.birthDate,
        rg: this.docId,
        rg_emissor: this.govAgent,
        residence_type: this.selectedResidence,
        residence_voltage: this.selectedVoltage,
        section: this.section,
        whoIndicated: this.whoIndicated,
        spc_restrition: this.spc_restrition,
        campaign_code: this.campaign_code,
        direct_sales: this.otherBrands,
        billing_address: this.billing_address,
        shipping_address: this.shipping_address,
        out_definition: this.outDefinition
      };

      service
      .update(data)
      .then(response => {
        
        var city = {
          name: this.city,
          state:{
            uf: this.state
          }
        };

        data.shipping_address.city = city;
        this.$bvModal.hide('edit-modal');
        this.$emit('edited');
      })
      .catch(err => {
        
      });
      
    },
  },
  computed:{
    base(){
      return process.env.VUE_APP_API_HOST;
    },
    outDefinition(){
      for(var i = 0; i < this.sales_consultant.status.length; i++){
        if(this.sales_consultant.status[i].status == 'OUT_DEFINITION' && !this.sales_consultant.status[i].approved){
          return this.sales_consultant.status[i].id;
        }
      }

      return -1;
    }
  },
  mounted(){
    
    // Person Data
    this.cpf = this.sales_consultant.cpf;
    this.name = this.sales_consultant.name;
    this.docId = this.sales_consultant.rg;
    this.selectedGender = this.sales_consultant.sex;
    this.govAgent = this.sales_consultant.rg_emissor;
    this.motherName = this.sales_consultant.mother_name;
    this.birthDate = this.$options.filters.formatDDMMAAAA(this.sales_consultant.birthday);
  
    // Shipping Address
    this.shipping_address = this.sales_consultant.shipping_address;
    this.billing_address = this.sales_consultant.billing_address;
    //this.getMarketDefinition(this.sales_consultant.shipping_address.city.ibge_code, this.sales_consultant.shipping_address.neighborhood);

    // Contacts
    this.email = this.sales_consultant.email;
    this.mobilePhone = this.sales_consultant.contacts[0].ddd + this.sales_consultant.contacts[0].number;
    this.residentialPhone = this.sales_consultant.contacts.length >= 2 ? this.sales_consultant.contacts[1].ddd + this.sales_consultant.contacts[1].number : '';
    this.phoneToMessage = this.sales_consultant.contacts.length >= 3 ? this.sales_consultant.contacts[2].ddd + this.sales_consultant.contacts[2].number : '';
    this.person = this.sales_consultant.contacts.length >= 3 ? this.sales_consultant.contacts[2].name : '';

    // Complement
    this.selectedResidence = this.sales_consultant.residence_type;
    this.selectedVoltage = this.sales_consultant.residence_voltage;
    this.section = this.sales_consultant.section;
    this.otherBrands = this.sales_consultant.direct_sales;
    this.selectedHasDelivery = this.sales_consultant.shipping_address.deliverable;

  }
};
</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>
