<template>
  <div>
  <b-modal id="sales-consultant-info" :no-close-on-backdrop="true" size="lg">
      <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">Informações</div>
              </div>
            </b-col>
            <b-col class="d-flex justify-content-end mr-2 mt-1">
              <span class="close-icon" @click="closeModal(false)">
                <font-awesome-icon icon="times" class="align-self-center" />
              </span>
            </b-col>
          </b-row>
        </b-container>
      </template>
      <b-container>
        <b-row class="px-2">
          <b-col cols="3">
            <b>Nome: </b>
          </b-col>
          <b-col cols="9" >
             {{ sales_consultant.name }}
          </b-col>
        </b-row>
        <b-row class="px-2">
          <b-col cols="3">
            <b>CPF: </b>
          </b-col>
          <b-col cols="9" >
             {{ sales_consultant.cpf }}
          </b-col>
        </b-row>
        <b-row class="px-2">
          <b-col cols="3">
            <b>RG: </b>
          </b-col>
          <b-col cols="9" >
             {{ sales_consultant.rg }}
          </b-col>
        </b-row>
        <b-row class="px-2">
          <b-col cols="3">
            <b>Endereço: </b>
          </b-col>
          <b-col cols="9" >
             {{ sales_consultant.shipping_address.street }}
          </b-col>
        </b-row>
        <b-row class="px-2">
          <b-col cols="3">
            <b>Complemento: </b>
          </b-col>
          <b-col cols="9" >
             {{ sales_consultant.shipping_address.complement }}
          </b-col>
        </b-row>
        <b-row class="px-2">
          <b-col cols="3">
            <b>Bairro: </b>
          </b-col>
          <b-col cols="9" >
             {{ sales_consultant.shipping_address.neighborhood }}
          </b-col>
        </b-row>
        <b-row class="px-2">
          <b-col cols="3">
            <b>Cidade / UF: </b>
          </b-col>
          <b-col cols="9" >
             {{ sales_consultant.shipping_address.city.name }} / {{ sales_consultant.shipping_address.city.state.uf }}
          </b-col>
        </b-row>
        <b-row class="px-2">
          <b-col cols="3">
            <b>CEP: </b>
          </b-col>
          <b-col cols="9" >
             {{ sales_consultant.shipping_address.postal_code }}
          </b-col>
        </b-row>
        <b-row class="px-2">
          <b-col cols="3">
            <b>Nascimento: </b>
          </b-col>
          <b-col cols="9" >
             {{ sales_consultant.birthday | date }}
          </b-col>
        </b-row>
        <b-row class="px-2">
          <b-col cols="3">
            <b>Cadastro: </b>
          </b-col>
          <b-col cols="9" >
             {{ sales_consultant.created_at | date }}
          </b-col>
        </b-row>
        <b-row class="px-2">
          <b-col cols="3">
            <b>Celular: </b>
          </b-col>
          <b-col cols="9" v-if="sales_consultant.contacts.length">
             {{ sales_consultant.contacts[sales_consultant.contacts.length - 1].ddd }} {{ sales_consultant.contacts[sales_consultant.contacts.length - 1].number }}
          </b-col>
        </b-row>
        <b-row class="px-2">
          <b-col cols="3">
            <b>Email: </b>
          </b-col>
          <b-col cols="9" >
             {{ sales_consultant.email }}
          </b-col>
        </b-row>
         <b-row class="px-2">
          <b-col cols="3">
            <b>Limite de Crédito:</b>
          </b-col>
          <b-col cols="9"> R$ {{ parseFloat(sales_consultant.credit_limit) | formatCoin }}</b-col>
        </b-row>
        <b-row class="px-2">
          <b-col cols="3">
            <b>Consulta SPC: </b>
          </b-col>
          <b-col cols="9" v-if="sales_consultant.spc.length > 0">
             {{ spc }} - {{ sales_consultant.spc[sales_consultant.spc.length - 1].created_at | date }}
          </b-col>
          <b-col cols="9" v-else>
             Sem consulta registrada
          </b-col>
        </b-row>

        <b-row>
          <b-col cols="2">
            <b-button
            v-b-popover.hover="'Editar Cadastro'"
              class="mr-2 btn shadow-none border-0 btn-default btn-theme "
              @click="showEditModal = true"
              >
              <font-awesome-icon icon="edit" class="align-self-center" />
            </b-button>
          </b-col>

          <b-col cols="2">
            <b-button 
            v-b-popover.hover="'Pendênicas'"
            class="mr-2 btn shadow-none border-0 btn-default btn-theme text-white"
            @click="openGeneralPending">
                <font-awesome-icon icon="clipboard-list" class="align-self-center mr-2" />
                <b-badge variant="light" v-if="pendingCount > 0">{{ pendingCount }}</b-badge>

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

          <b-col cols="2">
            <b-button 
            v-b-popover.hover="'Histórico de Pendencias'"
            class="mr-2 btn shadow-none border-0 btn-default btn-theme text-white"
            @click="openPendingHistory">
                <font-awesome-icon icon="history" class="align-self-center" />
            </b-button>
          </b-col>

          <b-col cols="2">
            <b-button 
            v-b-popover.hover="'Adicionar Anexos'"
            class="mr-2 btn shadow-none border-0 btn-default btn-theme text-white"
            @click="openAddAttachments">
                <font-awesome-icon icon="plus" class="align-self-center" />
            </b-button>
          </b-col>

        </b-row>

      <b-row>
        <b-col cols="12 text-center">
          <h4>Anexos</h4>
        </b-col>
      </b-row>
      <b-row class="px-1">
        <div style="width: 30%" v-for="attachment in attachments" class="m-2" v-if="(attachment.sales_consultants_status_id != null && attachment.status.status == 'ATTACHMENT_PENDING' && !attachment.status.approved) || typeof attachment.id == 'undefined'">
          <div class="wrap-drop-zone p-2">
            <div class="text-center">{{ attachment.attachment.description }}</div>

            <upload-image-thumb :attachment="attachment" v-model="attachment.path" @change="selected" />
          </div>
          <b-row v-if="typeof attachment.status != 'undefined'">
            <b-col cols="12 text-center">
              <b >Pendência ##</b>
            </b-col>
          </b-row>
          <p class="p-2" v-if="typeof attachment.status != 'undefined'">
            {{ attachment.status.description }}
          </p>
        </div>
      </b-row>
      <div v-if="loading" class="loading-content">
        <b-spinner type="grow" style="width: 5rem; height: 5rem;"></b-spinner>
      </div>
      </b-container>

      <template v-slot:modal-footer="{  }">
        <b-container>
          <b-row>
            <b-col 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(false)"
              >
                Cancelar
              </b-button>

              <b-button
                class="mr-2 btn shadow-none border-0 btn-default"
                @click="done"
              >
                Salvar Alterações
              </b-button>
            </b-col>
          </b-row>
        </b-container>
      </template>

      </b-modal>

      <edit-modal :sales_consultant="sales_consultant" v-if="showEditModal" @edited="edited" :isPending="true" />
      <general-pending-modal :isDisable="true" :pendings="pendings" />
      <pending-history-modal :isDisable="!isAnalyst" :status="sales_consultant.status" />
      <add-attachments-modal @added="addedAttachments" :attachments_count="attachments.length"/>

   


  </div>
</template>

<script>

import AttachmentFullscreenModal from "@/components/solicitations/solicitations-list/waiting-analyze/modals/AttachmentFullscreenModal.vue";
import UploadImageThumb from '@/components/shared-components/UploadImageThumb.vue';
import SalesConsultantService from "@/services/resources/SalesConsultantsWebService";
import EditModal from "@/components/solicitations/solicitations-list/waiting-analyze/modals/EditModal.vue";
import GeneralPendingModal from "@/components/solicitations/solicitations-list/waiting-analyze/modals/GeneralPendingModal.vue";
import PendingHistoryModal from "@/components/solicitations/solicitations-list/waiting-analyze/modals/PendingHistoryModal.vue";
import AddAttachmentsModal from "@/components/solicitations/solicitations-list/pending/modals/AddAttachmentsModal.vue";
import moment from "moment";

const service = SalesConsultantService.build();

export default {
  name: 'accept-credit-card',
  components:{
    AttachmentFullscreenModal,
    UploadImageThumb,
    EditModal,
    GeneralPendingModal,
    PendingHistoryModal,
    AddAttachmentsModal
  },
  props:{
    sales_consultant_id:{
      type: Number
    }
  },
  data: () => ({
    loading: true,
    sales_consultant: {
      shipping_address:{
          street: '',
          complement: '',
          neighborhood: '',
          postal_code: '',
          city:{
            name: '',
            state: {
              uf: ''
            }
          }
        },
        attachments: [],
        contacts: [],
        spc: [],
        status: []
    },
    image_fullscreen: null,
    files: [],
    showEditModal: false
  }),
  watch: {
    showEditModal: function (newValue) {
      if(newValue){
        this.$nextTick(function() {
          this.$bvModal.show('edit-modal');
        });
      } 
    }
  },
  methods: {
    closeModal(reload) {
      this.$bvModal.hide('sales-consultant-info');
      this.$emit('close', reload);
    },
    openPendingHistory(){
      this.$bvModal.show('pending-history');
    },
    openGeneralPending(){
      this.$bvModal.show('general-pending');
    },
    openAddAttachments(){
      this.$bvModal.show('add-attachments-modal');
    },
    edited(){
      this.load(this.sales_consultant_id);
      this.showEditModal = false;
    },
    addedAttachments(attachments){

      attachments.forEach(element => {
        this.sales_consultant.attachments.push({
          sales_consultant_id: this.sales_consultant.id,
          sales_consultants_status_id: null,
          path: '',
          extension: '',
          attachment_id: element.id,
          attachment: element
        });
      });

    },
    load(id){
      service
      .read(id)
      .then(response => {
        this.sales_consultant = response;
        this.loading = false;
      }).catch(err => {
          console.log(err);
      });
    },
    done() {

      if(this.files.length > 0){

        var formData = new FormData();
        formData.append('id', this.sales_consultant.id);
        formData.append('_method', 'PUT');

        for(var i = 0; i < this.files.length; i++){
          if(typeof this.files[i].id != 'undefined')
            formData.append('attachments['+ i +'][id]', this.files[i].id);
          formData.append('attachments['+ i +'][attachment_id]', this.files[i].attachment_id);
          formData.append('attachments['+ i +'][file]', this.files[i].file);
        }

        service
        .update(formData)
        .then(response => {
          this.closeModal(true);
        })
        .catch(err => {
          console.log(err);
        });
      }else{
        this.closeModal(true);
      }
    },
    openFullscreen(image){
      this.image_fullscreen = image;
      this.$modal.show('attachment-fullscreen');
    },
    closeFullscreenModal(){
      this.$modal.hide('attachment-fullscreen');
    },
    selected(file){
     this.files.push(file);
    }
  },
  computed:{
    spc(){
      if(this.sales_consultant.spc.length > 0){
        var dados = JSON.parse(this.sales_consultant.spc[this.sales_consultant.spc.length - 1].dados);

        return !dados.restricao ? 'Aprovado' : 'Negado';
      }

      return '';
    },
    base(){
      return process.env.VUE_APP_API_HOST;
    },
    pendings(){
      var pendings = [];
      this.sales_consultant.status.forEach(element => {
        if(element.status == 'PENDING'){
          pendings.push(element);
        }
      });

      return pendings;
    },
    pendingCount(){
        var count = 0;
        this.sales_consultant.status.forEach(element => {
          if((element.status == 'PENDING') && !element.approved){
            count++;
          }
        });
        return count;
    },
    attachments(){
      return this.sales_consultant.attachments;
    },
    isAnalyst(){
      var roles = this.$store.state.user.user.roles;
      for(var i = 0; i < roles.length; i++) {
        if(roles[i].name == 'Analyst'){
          return true;
        }
      }

      return false;
    }
  },
  filters:{
    date(date){
      return moment(date, "YYYY-MM-DD").format('DD/MM/YYYY')
    }
  },
  mounted(){
    this.load(this.sales_consultant_id);
  }
};
</script>

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

.item-attachment{
  height: 150px;
  overflow: hidden;
  cursor: pointer;
}

.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-theme{
  background: $theme-color-blue;
}

.loading-content{
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  display: flex;
  background: rgba(255, 255, 255, 0.7);
  justify-content: center;
  align-items: center;
}

</style>
