<template>
  <div>
    <b-modal id="sales-consultant-info" 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">Ver informaçoes</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" v-if="!isDisable">
            <b-button
            v-b-popover.hover="'Editar'"
              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" v-if="!isDisable">
            <b-button
              v-b-popover.hover="'Confirmar Telefone'"
              class="mr-2 btn shadow-none border-0 btn-default btn-theme text-white"
              @click="openTelephone"
            >
              <font-awesome-icon icon="phone" class="align-self-center" />
            </b-button>
          </b-col>

          <b-col cols="2">
            <b-button
              v-b-popover.hover="'Pendencias'"
              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" />
            </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" v-if="showApprove && isAnalyst">
            <b-button
              v-b-popover.hover="'Aprovar cadastro'"
              class="mr-2 btn shadow-none border-0 btn-default btn-success text-white"
              @click="confirmApproveSalesConsultant"
            >
              <font-awesome-icon icon="thumbs-up" class="align-self-center" />
            </b-button>
          </b-col>
          <b-col cols="2" v-if="!isDisable">
            <b-button
            v-b-popover.hover="'Negar Cadastro'"
              class="mr-2 btn shadow-none border-0 btn-default btn-danger bg-danger text-white"
              @click="openCrmModal"
            >
              <font-awesome-icon icon="times" 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="mt-3" v-for="attachment in attachments">
          <b-col cols="4" class="item-attachment" v-for="item in attachment" :key="item.id">
            <div class="text-center">{{ item.attachment.description }}</div>
            <div class="wrap-attachment-preview">
              <div class="state-icon" @click="openFullscreen(item)">
                <font-awesome-icon
                  icon="check"
                  class="align-self-center text-success"
                  v-if="(typeof item.state != 'undefined' && item.state == 'ATTACHMENT_APPROVED') || (typeof item.state == 'undefined' &&  item.status != null && item.status.status == 'ATTACHMENT_APPROVED')"
                />
                <font-awesome-icon
                  icon="times"
                  class="align-self-center text-danger"
                  v-if="typeof item.state != 'undefined' && item.state == 'ATTACHMENT_PENDING'"
                />
                <font-awesome-icon
                  icon="exclamation-triangle"
                  class="align-self-center text-warning"
                  v-if="typeof item.state == 'undefined' && item.status != null && item.status.status == 'ATTACHMENT_PENDING'"
                />
              </div>

              <template v-if="item.extension == 'pdf'">
                <img src="@/assets/pdf-icon.png" class="img-fluid" />
              </template>
              <template v-else>
                <img :src="'data:image/jpeg;base64,'+ item.path" class="img-fluid" />
              </template>
            </div>
          </b-col>
        </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
                v-if="!isDisable"
                class="mr-2 btn shadow-none border-0 btn-default"
                @click="done"
              >Salvar</b-button>
            </b-col>
          </b-row>
        </b-container>
      </template>
    </b-modal>

    <attachment-fullscreen-modal
      :attachment="attachment"
      :attachments="sales_consultant.attachments"
      :sales_consultant_status_id="pendingID"
      @result="result"
      :isDisable="isDisable"
    />
    <edit-modal :sales_consultant="sales_consultant" v-if="showEditModal" @edited="edited" />
    <telephone-modal
      :sales_consultant_id="sales_consultant.id"
      :contacts="sales_consultant.contacts"
      v-if="typeof sales_consultant.id != 'undefined'"
    />
    <sales-consultant-crm-modal :sales_consultant_id="sales_consultant.id" />
    <general-pending-modal
      :isDisable="isDisable"
      :pendings="pendings"
      @generalPending="generalPendingDone"
    />
    <pending-history-modal :isDisable="!isAnalyst" :status="sales_consultant.status" />
  </div>
</template>

<script>
import AttachmentFullscreenModal from "@/components/solicitations/solicitations-list/waiting-analyze/modals/AttachmentFullscreenModal.vue";
import SalesConsultantCrmModal from "@/components/solicitations/solicitations-list/waiting-analyze/modals/SalesConsultantCrmModal.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 EditModal from "@/components/solicitations/solicitations-list/waiting-analyze/modals/EditModal.vue";
import TelephoneModal from "@/components/solicitations/solicitations-list/waiting-analyze/modals/TelephoneModal.vue";
import SalesConsultantStatusService from "@/services/resources/SalesConsultantStatusService";
import SalesConsultantService from "@/services/resources/SalesConsultantsWebService";
import FilesLoadService from "@/services/resources/FilesLoadService";
import moment from "moment";

const signupService = SalesConsultantService.build();
const service = SalesConsultantStatusService.build();
const serviceFiles = FilesLoadService.build();

export default {
  name: "view-salesconsultant-modal",
  components: {
    AttachmentFullscreenModal,
    EditModal,
    SalesConsultantCrmModal,
    TelephoneModal,
    GeneralPendingModal,
    PendingHistoryModal
  },
  props: {
    sales_consultant_id: {
      type: Number
    },
    isDisable: {
      type: Boolean
    }
  },
  data: () => ({
    loading: true,
    sales_consultant: {
      shipping_address: {
        street: "",
        complement: "",
        neighborhood: "",
        postal_code: "",
        city: {
          name: "",
          state: {
            uf: ""
          }
        }
      },
      contacts: [],
      spc: [],
      status: []
    },
    attachments_analyzeds: [],
    newPendings: [],
    attachment: {
      extension: "",
      path: "",
      name: "",
      id: 0
    },
    is_pending: false,
    showEditModal: false
  }),
  watch: {
    showEditModal: function(newValue) {
      if (newValue) {
        this.$nextTick(function() {
          this.$bvModal.show("edit-modal");
        });
      }
    }
  },
  methods: {
    openTelephone() {
      this.$bvModal.show("telephone");
    },
    openGeneralPending() {
      this.$bvModal.show("general-pending");
    },
    openPendingHistory() {
      this.$bvModal.show("pending-history");
    },
    openCrmModal() {
      this.$bvModal.show("sales-consultant-crm");
    },
    closeModal(reload) {
      this.$bvModal.hide("sales-consultant-info");
      this.$emit("close", reload);
    },
    edited() {
      this.load(this.sales_consultant_id);
      this.showEditModal = false;
    },
    generalPendingDone(pendings) {
      this.newPendings = this.newPendings.concat(pendings);
    },
    confirmApproveSalesConsultant() {
      var vm = this;

      this.$fire({
        title: "Você deseja realmente marcar esse cadastro como aprovado?",
        text: "A ação não poderá ser revertida!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Sim, confirmo!",
        cancelButtonText: "Não, vou revisar"
      }).then(result => {
        if (result.value) {
          vm.approveSalesConsultant();
        }
      });
    },
    approveSalesConsultant() {
     
      var vm = this;
      service
        .create({
          sales_consultant_id: this.sales_consultant_id,
          status: "APPROVED"
        })
        .then(resp => {
          vm.$fire({
            title: "",
            text: resp.msg,
            type: "success"
          });
          vm.closeModal(false);
        })
        .catch(err => {
          let resp = JSON.parse(err.response.data);
          vm.$fire({
            title: "Falha ao salvar dados",
            text: resp.msg,
            type: "error"
          });
        });
    },
    result(object) {
      if (typeof object != "undefined") {
        for (var i = 0; i < this.sales_consultant.attachments.length; i++) {
          if (this.sales_consultant.attachments[i].id == object.attachment_id) {
            this.sales_consultant.attachments[i].state = object.status;
          }
        }
        this.$forceUpdate();
        this.attachments_analyzeds.push(object);
      }
    },
    load(id) {
      signupService
        .read(id)
        .then(response => {
          this.sales_consultant = response;
          for (var i = 0; i < this.sales_consultant.attachments.length; i++) {
            for (var j = 0; j < this.attachments_analyzeds.length; j++) {
              if (
                this.sales_consultant.attachments[i].id ==
                this.attachments_analyzeds[j].attachment_id
              ) {
                this.sales_consultant.attachments[
                  i
                ].state = this.attachments_analyzeds[j].status;
              }
            }
          }
          this.$forceUpdate();
          this.loading = false;
        })
        .catch(err => {
          console.log(err);
        });
    },
    done() {
      if (
        this.attachments_analyzeds.length > 0 ||
        this.newPendings.length > 0
      ) {
        let data = {
          sales_consultant_status_id: this.pendingID,
          sales_consultant_id: this.sales_consultant_id,
          pendings: this.newPendings,
          attachments: this.attachments_analyzeds
        };

        service
          .create(data)
          .then(response => {
            this.closeModal(true);
          })
          .catch(err => {});
      } else {
        this.closeModal(false);
      }
    },
    openFullscreen(attachment) {
      this.attachment = attachment;
      this.$bvModal.show("attachment-fullscreen");
    }
  },
  computed: {
    spc() {
      if (this.sales_consultant.spc.length > 0) {
        var dados = JSON.parse(this.sales_consultant.spc[0].dados);

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

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

      return pendings;
    },
    pendingID() {
      for (var i = 0; i < this.sales_consultant.status.length; i++) {
        if (
          this.sales_consultant.status[i].status == "REANALYZE" &&
          !this.sales_consultant.status[i].approved
        ) {
          return this.sales_consultant.status[i].id;
        }
      }

      return 0;
    },
    telephoneUrl() {
      var number = 4334;
      var ramal = 34;

      var url =
        "http://server3.kingtelecom.com.br/api/adorata.php?action=originate&numero=" +
        number +
        "&ramal=" +
        ramal;
      return url;
    },
    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;
    },
    showApprove(){

      let statusReanalyze = this.sales_consultant.status.find(
        element => element.status == "WAITING_APPROVATION" && element.approved == false
      );

    let statusOther = this.sales_consultant.status.find(
        element => element.status != "WAITING_APPROVATION" && element.approved == false
      );

if(typeof(statusReanalyze) != "undefined" && typeof(statusOther) == "undefined"){
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";

.wrap-modal-body {
  height: 400px;
  overflow-y: auto;
}

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

.wrap-attachment-preview {
  position: relative;
  left: 0;
  top: 0;

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

.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>
