<template>
<div>
  <div>
    <b-row class="mb-3" >
      <b-col>
        <div class="text-left mb-1 akkurat-regular">
          Complemento:
        </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">
                <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"
                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>
        </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="Endereço de Entrega" />
          <b-button
            class="
              d-flex
              btn
              shadow-none
              align-items-center
              border-0
              akkurat-bold
              btn-custom
              mx-2
            "
            @click="openDocModal"
          >
          <div class="d-flex flex-fill justify-content-around align-items-center">
            <b-spinner v-if="loading" small type="grow"></b-spinner>
            <font-awesome-icon v-else icon="user-friends" />
            <div class="akkurat-bold align-self-center flex-fill">Continuar</div>
          </div>
          </b-button>
      </b-col>
    </b-row>
  </div>
    <message-modal :message="message"></message-modal>
    <attachments-modal @uploaded="attachmentsUploaded" :title="title" />

  </div>
</template>

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

const service = SalesConsultantsWebService.build();

export default {
  name: 'signup-form',
  components: {
    TextInput,
    NumberInput,
    SignupButton,
    MessageModal,
    AttachmentsModal,
  },
  data: () => ({
    cpf: '',
    contacts: [],
    campaign_code: '',
    spc_restrition: '',
    name: '',
    gender: '',
    docId: '',
    govAgent: '',
    birthDate: '',
    motherName: '',
    whoIndicated: null,
    email: '',
    billing_address: {},
    shipping_address: {},
    section: '',
    rg_front: null,
    rg_verse: null,
    register_form: null,
    title: 'Foto frontal do RG',
    type_doc: 'rg_front',
    otherBrands: '',
    selectedResidence: 'OWN',
    referencePoint: '',
    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 },
    ],
    message: '',
    loading: false
  }),
  methods: {
    openDocModal() {
      this.$bvModal.show('attachments-modal');
    },
    attachmentsUploaded(attachments){
      this.done(attachments);
    },
    done(attachments){
      var formData = new FormData();
      var vm = this;
      formData.append('step', 'final');
      for(var i = 0; i < this.contacts.length; i++){
        formData.append('contacts['+ i +'][name]', this.contacts[i].name);
        formData.append('contacts['+ i +'][is_cellphone]', this.contacts[i].is_cellphone);
        formData.append('contacts['+ i +'][is_whatsapp]', this.contacts[i].is_whatsapp);
        formData.append('contacts['+ i +'][is_note]', this.contacts[i].is_note);
        formData.append('contacts['+ i +'][ddd]', this.contacts[i].ddd);
        formData.append('contacts['+ i +'][number]', this.contacts[i].number);
        formData.append('contacts['+ i +'][is_verified]', this.contacts[i].is_verified);
        formData.append('contacts['+ i +'][is_principal]', this.contacts[i].is_principal);
      }
      formData.append('name', this.name);
      formData.append('cpf', this.cpf);
      formData.append('email', this.email);
      formData.append('sex', this.gender);
      formData.append('mother_name', this.motherName);
      formData.append('birthday', this.birthDate);
      formData.append('rg', this.docId);
      formData.append('rg_emissor', this.govAgent);
      formData.append('residence_type', this.selectedResidence);
      formData.append('residence_voltage', this.selectedVoltage);
      formData.append('section', this.section);
      if( this.whoIndicated !== null && this.whoIndicated > 0){

        formData.append('whoIndicated',  this.whoIndicated);
      }
      formData.append('spc_restrition', this.spc_restrition);
      formData.append('campaign_code', this.campaign_code);
      formData.append('direct_sales', this.otherBrands);


      // Billing Address
      formData.append('billing_address[postal_code]', this.billing_address.postal_code);
      formData.append('billing_address[street]', this.billing_address.street);
      formData.append('billing_address[complement]', this.billing_address.complement);
      formData.append('billing_address[number]', this.billing_address.number);
      formData.append('billing_address[reference]', this.billing_address.reference);
      formData.append('billing_address[city_ibge]', this.billing_address.city_ibge);
      formData.append('billing_address[city]', this.billing_address.city);
      formData.append('billing_address[state]', this.billing_address.state);
      formData.append('billing_address[neighborhood]', this.billing_address.neighborhood);
      formData.append('billing_address[marketDefinitionID]', this.billing_address.marketDefinitionID);
      formData.append('billing_address[deliverable]', this.billing_address.deliverable);

      // Shipping Address
      formData.append('shipping_address[postal_code]', this.shipping_address.postal_code);
      formData.append('shipping_address[street]', this.shipping_address.street);
      formData.append('shipping_address[complement]', this.shipping_address.complement);
      formData.append('shipping_address[number]', this.shipping_address.number);
      formData.append('shipping_address[reference]', this.shipping_address.reference);
      formData.append('shipping_address[city_ibge]', this.shipping_address.city_ibge);
      formData.append('shipping_address[city]', this.shipping_address.city);
      formData.append('shipping_address[state]', this.shipping_address.state);
      formData.append('shipping_address[neighborhood]', this.shipping_address.neighborhood);
      formData.append('shipping_address[marketDefinitionID]', this.shipping_address.marketDefinitionID);
      formData.append('shipping_address[deliverable]', this.shipping_address.deliverable);

      for(var i = 0; i < attachments.length; i++){
        formData.append('attachments['+ i +'][id]', attachments[i].id);
        formData.append('attachments['+ i +'][file]', attachments[i].file);
      }
    
  vm.loading = true;
      service
        .create(formData)
        .then(response => {
          localStorage.removeItem('step_1');
          localStorage.removeItem('step_2');
          localStorage.removeItem('step_3');
          localStorage.removeItem('step_4');

          this.$router.push({name: 'Cadastro Concluido'});
          vm.loading = false;
        })
        .catch(err => {
          console.log(err);
          vm.loading = false;
            let resp = JSON.parse(err.response.data);
          vm.$fire({
            title: "Falha ao salvar dados",
            text: resp.msg,
            type: "error"
          });
        
        });
    }
  },
  mounted(){
   if(!localStorage.step_4){
      this.$router.push({
            name: 'Documentos'
      });
    }

    let data = JSON.parse(localStorage.step_4);
    this.cpf = data.cpf;
    this.email = data.email;
    this.campaign_code = data.campaign_code;
    this.spc_restrition = data.spc_restrition;
    this.name = data.name;
    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;
    this.billing_address = data.billing_address;
    this.shipping_address = data.shipping_address;

  }
};
</script>

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

.custom-width {
  width: 25%;
}

.btn-custom {
  width: 236px;
  border-radius: 20px;
  height: 40px;
  background: #278937;
}
</style>
