<template>
  <modal
    name="show-selfsignup"
    :scrollable="true"
    width="90%"
    height="auto"
    :header-bg-variant="null"
    @opened="load"
    @closed="$emit('closed')"
  >
    <div>
      <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="portrait" class="align-self-center" />
          </div>
          <div class="pt-1">
            <div class="inline-block akkurat-regular min-header-text">Pré-Cadastro</div>
            <div class="akkurat-bold max-header-text" v-if="selfSignUp">{{selfSignUp.name}}</div>
            <div class="akkurat-bold max-header-text" v-if="!selfSignUp && loading">carregando...</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>

      <div class="custom-body" v-if="selfSignUp">
        <consultas-spc-modal
          v-if="selfSignUp.consulta_spc"
          :spc="selfSignUp.consulta_spc.dados"
          :viewOnly="true"
        />

        <b-row v-if="!editing">
          <b-col md="12">
            <strong>Campanha:</strong>
            <span v-if="selfSignUp.campaign">{{selfSignUp.campaign.name}}</span>
            <span v-else>Não informada</span>
            <strong>Setor:</strong>
            <span v-if="selfSignUp.sector">{{selfSignUp.sector.name}}</span>
            <span v-else>Não informado</span>
          </b-col>

          <b-col md="3">
            <h4>Dados Pessoais</h4>

            <p>
              <strong>Nome:</strong>
              {{selfSignUp.name}}
              <br />
              <strong>CPF:</strong>
              {{selfSignUp.cpf}}
              <br />
              <strong>Data de Nasc.:</strong>
              {{selfSignUp.birth_date | formatDDMMAAAA}}
              <br />
              <strong>Telefone:</strong>
              <span v-if="selfSignUp.contact">
                ({{selfSignUp.contact.ddd}}) {{selfSignUp.contact.number}}
                <font-awesome-icon
                  class="text-success"
                  icon="check"
                  v-if="selfSignUp.contact.is_verified"
                />
              </span>
              <br />
              <strong>Email:</strong>
              {{selfSignUp.email}}
              <br />
              <strong>Doc. identificação:</strong>
              {{selfSignUp.document_identification_type}}
            </p>

            <p class="text-left">
              <a v-if="selfSignUp.consulta_spc" href="#" @click.prevent="showSPCModal">
                <font-awesome-icon icon="search" class="align-self-center" /> Consulta SPC
              </a>

              <a v-if="selfSignUp.crm.length > 0" href="#" 
                @click.prevent="$modal.show('show-crm-selfsignup')">
                <font-awesome-icon icon="clock" class="align-self-center" /> CRM
              </a>
            </p>

          </b-col>

          <b-col md="3" v-if="selfSignUp.credit_limit != null">
            <div>
              <strong>Forma de Pgto:</strong> (
              <span v-if="selfSignUp.credit_limit > 0">BOLETO e Cartão</span>
              <span v-else>Cartão</span>
              )
            </div>

            <div v-if="selfSignUp.credit_limit > 0">
              <strong>Limite de Crédito:</strong>
              R$ {{ parseFloat(selfSignUp.credit_limit) | formatCoin}}
            </div>
          </b-col>

          <b-col md="3" v-else>
            <strong>Limite de crédito não adicionado</strong>
          </b-col>

          <b-col md="6">
            <h4>Endereço de Entrega</h4>

            <p v-if="selfSignUp.shipping_address">
              {{selfSignUp.shipping_address.street}} Nº
              <span
                v-if="selfSignUp.shipping_address.number"
              >{{selfSignUp.shipping_address.number}}</span>

              <span v-else>S/N</span>
              {{selfSignUp.shipping_address.complement}}
              Bairro:
              {{selfSignUp.shipping_address.neighborhood}}
              CEP: {{selfSignUp.shipping_address.postal_code}}
              {{selfSignUp.shipping_address.city.name}}
              {{selfSignUp.shipping_address.city.state.uf}}
            </p>

            <p v-else>
              <i>Não informado</i>
            </p>

            <h4>Endereço de Cobrança</h4>

            <p v-if="selfSignUp.billing_address">
              {{selfSignUp.billing_address.street}} Nº
              <span
                v-if="selfSignUp.billing_address.number"
              >{{selfSignUp.billing_address.number}}</span>

              <span v-else>S/N</span>
              {{selfSignUp.billing_address.complement}}
              Bairro:
              {{selfSignUp.billing_address.neighborhood}}
              CEP: {{selfSignUp.billing_address.postal_code}}
              {{selfSignUp.billing_address.city.name}}
              {{selfSignUp.billing_address.city.state.uf}}
            </p>

            <p v-else>
              <i>Não informado</i>
            </p>

            <p v-if="selfSignUp.disapproved_at" class="text-center">
              <strong>Negado em {{selfSignUp.disapproved_at | formatDateTimeDDMMAAAA}}</strong>
              por
              <strong>{{selfSignUp.disapproved_by.name}}</strong>
            </p>

            <p class="text-center" v-if="!selfSignUp.approved_at">
              <b-button
                class="btn shadow-none border-0 btn-danger"
                :disabled="selfSignUp.disapproved_at != null"
                @click="showDisapprove"
              >
                <b-spinner v-if="loading" small type="grow"></b-spinner>
                <font-awesome-icon icon="thumbs-down" class="align-self-center" />NEGAR
              </b-button>

              <b-button
                :disabled="!completed"
                class="btn shadow-none border-0 btn-success"
                @click="approve"
              >
                <b-spinner v-if="loading" small type="grow"></b-spinner>
                <font-awesome-icon icon="thumbs-up" class="align-self-center" />APROVAR CADASTRO
              </b-button>
            </p>
            <p v-else class="text-center">
              <strong>Aprovado em {{selfSignUp.approved_at | formatDateTimeDDMMAAAA}}</strong>
            </p>
          </b-col>
        </b-row>
        <div v-else>
          <form-edit
            ref="formEdit"
            @hasBillingAddress="setHasBillingAddress"
            :hasBillingAddress="hasBillingAddress"
            v-model="selfSignUpModelToEdit"
          />
        </div>
        <b-row v-if="!editing">
          <b-col md="12">
            <h4>Anexos</h4>

            <b-row class="images" v-viewer.rebuild="viewerOptions">
              <b-col md="2">
                <file-input
                  v-if="selfSignUp"
                  :fileInit="selfSignUp.document_identification_selfie_url"
                  :disabled="!editing"
                  label="Selfie"
                  v-model="selfSignUp.document_identification_selfie"
                />
              </b-col>

              <b-col md="2">
                <fileInput
                  v-if="selfSignUp"
                  :disabled="!editing"
                  :label="'Frente. ('+selfSignUp.document_identification_type+')'"
                  :fileInit="selfSignUp.document_identification_photo_front_url"
                  v-model="selfSignUp.document_identification_photo_front"
                />
              </b-col>

              <b-col md="2">
                <file-input
                  v-if="selfSignUp"
                  :disabled="!editing"
                  :label="'Verso. ('+selfSignUp.document_identification_type+')'"
                  :fileInit="selfSignUp.document_identification_photo_back_url"
                  v-model="selfSignUp.document_identification_photo_back"
                />
              </b-col>

              <b-col md="2">
                <file-input
                  v-if="selfSignUp && selfSignUp.shipping_address"
                  :fileInit="selfSignUp.shipping_address.proof_url"
                  :disabled="!editing"
                  label="End. Entrega"
                  v-model="selfSignUp.shipping_address.proof"
                />
              </b-col>

              <b-col md="2">
                <file-input
                  v-if="selfSignUp &&  hasBillingAddress"
                  :fileInit="selfSignUp.billing_address.proof_url"
                  :disabled="!editing"
                  label="End. Cobrança"
                  v-model="selfSignUp.billing_address.proof"
                />
              </b-col>
            </b-row>
          </b-col>
        </b-row>

        <b-row>
          <b-col class="d-flex justify-content-center my-3 px-3">
            <b-button
              class="btn shadow-none border-0 btn-primary"
              v-if="!editing"
              @click="closeModal"
              :disabled="loading"
            >FECHAR</b-button>

            <b-button
              class="btn shadow-none border-0 btn-primary"
              v-else
              @click="editing = false"
              :disabled="loading"
            >CANCELAR</b-button>

            <b-button
              class="btn shadow-none border-0 btn-primary btn-default btn-blue"
              @click="showEdit()"
              v-if="!editing"
              :disabled="loading || selfSignUp.approved_at != null"
            >EDITAR</b-button>
            <b-button
              :disabled="loading"
              v-else
              class="btn shadow-none border-0 btn-success"
              @click="store()"
            >
              <b-spinner v-if="loading && action === 'UPDATE' " small type="grow"></b-spinner>SALVAR
            </b-button>

            <b-button
              :disabled="loading"
              @click="remove"
              class="btn shadow-none border-0 btn-danger"
            >
              <b-spinner v-if="loading && action === 'DELETE' " small type="grow"></b-spinner>EXCLUIR
            </b-button>
          </b-col>
        </b-row>
      </div>
    </div>

    <disapprove-modal v-model="disapproveModel" @disapprove="disapprove" />
    <show-crm-modal v-if="selfSignUp" :crm="selfSignUp.crm" />
  </modal>
</template>

<script>
import SelfSignUp from "@/services/resources/SelfSignUpAuthenticatedService";
import SelfSignupModel from "@/models/SelfSignupModel.js";
import formEdit from "./forms/edit";
import imageInput from "@/components/shared-components/UploadImage";
import fileInput from "@/components/shared-components/FileInput";
import TextInput from "@/components/shared-components/inputs/TextInput.vue";
import ConsultasSpcModal from "@/components/consults/consults-list/modals/ViewModal.vue";
import DisapproveModal from "@/components/modals/selfSignUp/disapprove";
import showCrmModal from "@/components/modals/selfSignUp/showCrm";
import "viewerjs/dist/viewer.css";
import { objectToFormData } from "@/utils/convert.js";
import Viewer from "v-viewer";
import Vue from "vue";
Vue.use(Viewer);
const service = SelfSignUp.build();

const viewerOptions = {
  inline: false,
  button: true,
  navbar: false,
  title: false,
  toolbar: true,
  tooltip: false,
  movable: true,
  zoomable: true,
  rotatable: true,
  scalable: false,
  transition: true,
  fullscreen: true,
  keyboard: true,
  url: "data-source"
};

export default {
  name: "show-selfsignup",
  props: {
    id: {
      required: true
    }
  },
  components: {
    imageInput,
    fileInput,
    TextInput,
    formEdit,
    ConsultasSpcModal,
    DisapproveModal,
    showCrmModal
  },
  data: () => ({
    alertMessage: "",
    loading: false,
    selfSignUp: null,
    selfSignUpModelToEdit: new SelfSignupModel(),
    hasBillingAddress: false,
    viewerOptions: viewerOptions,
    editing: false,
    action: "UPDATE",
    showViewModalSPC: false,
    disapproveModel: { motive: null, description: "" }
  }),
  computed: {
    completed() {
      if (
        this.selfSignUp.shipping_address &&
        this.selfSignUp.document_identification_type &&
        this.selfSignUp.document_identification_selfie_url &&
        this.selfSignUp.document_identification_photo_front_url &&
        this.selfSignUp.document_identification_photo_back_url
      ) {
        return true;
      }
      return false;
    }
  },
  methods: {
    showSPCModal() {
      this.$nextTick(function() {
        this.$bvModal.show("consultas-spc-modal");
      });
    },
    closeModal() {
      this.$modal.hide("show-selfsignup");
      this.$emit("modalClosed", this.file);
    },
    setHasBillingAddress(hasBillingAddress) {
      if (!this.selfSignUp.billing_address) {
        this.selfSignUp.billing_address = this.selfSignUpModelToEdit.billing_address;
      }
      this.hasBillingAddress = hasBillingAddress;
    },
    showEdit() {
      this.selfSignUpModelToEdit = new SelfSignupModel(this.selfSignUp);

      this.editing = true;
    },
    approve() {
      if (!this.completed) {
        alert("Cadastro incompleto");
        return;
      }

      this.selfSignUpModelToEdit = new SelfSignupModel(this.selfSignUp);
      this.editing = true;
      this.selfSignUpModelToEdit.approved = true;
      this.updateSelfSignup();
    },
    showDisapprove() {
      this.$modal.show("disapprove-selfsignup");
    },
    disapprove() {
      var vm = this;

      this.loading = true;
      service
        .update({
          id: this.id,
          _method: "PUT",
          disapproved: true,
          disapproved_motive: this.disapproveModel.motive,
          disapproved_description: this.disapproveModel.description
        })
        .then(response => {
          vm.$fire({
            title: "",
            text: response.msg,
            type: "success"
          });
          vm.loading = false;
          vm.$modal.hide("disapprove-selfsignup");
          vm.closeModal();
        })
        .catch(err => {
          let resp = JSON.parse(err.response.data);
          vm.$fire({
            title: "Falha ao reprovar registro",
            text: resp.msg,
            type: "error"
          });
          vm.loading = false;
          vm.$modal.hide("disapprove-selfsignup");
        });
    },
    store() {
      console.log(this.selfSignUpModelToEdit.isValid());
      console.log(objectToFormData(this.selfSignUpModelToEdit));
      this.updateSelfSignup();
    },
    updateSelfSignup() {
      var vm = this;
      let formToSend = {
        _method: "PUT",
        id: this.selfSignUp.id
      };

      Object.assign(formToSend, this.selfSignUpModelToEdit);

      if (!this.hasBillingAddress) {
        delete formToSend.billing_address;
      }

      this.action = "UPDATE";
      this.loading = true;
      service
        .update(objectToFormData(formToSend))
        .then(response => {
          vm.$fire({
            title: "",
            text: response.msg,
            type: "success"
          });
          vm.editing = false;
          vm.loading = false;
          vm.closeModal();
        })
        .catch(err => {
          let resp = JSON.parse(err.response.data);
          vm.$fire({
            title: "Falha ao salvar dados",
            text: resp.msg,
            type: "error"
          });
          vm.loading = false;
        });
    },

    remove() {
      var vm = this;

      this.action = "DELETE";
      this.loading = true;
      service
        .update({
          id: this.id,
          _method: "DELETE"
        })
        .then(response => {
          vm.$fire({
            title: "",
            text: response.msg,
            type: "success"
          });
          vm.loading = false;
          vm.closeModal();
        })
        .catch(err => {
          let resp = JSON.parse(err.response.data);
          vm.$fire({
            title: "Falha ao excluir registros",
            text: resp.msg,
            type: "error"
          });
          vm.loading = false;
          vm.closeModal();
        });
    },
    load() {
      this.editing = false;
      var vm = this;
      this.loading = true;
      this.selfSignUp = null;
      service
        .read({
          id: this.id
        })
        .then(response => {
          vm.selfSignUp = response;
          vm.selfSignUpModelToEdit = new SelfSignupModel(response);

          vm.hasBillingAddress = response.billing_address ? true : false;

          vm.loading = false;
        })
        .catch(resp => {
          vm.alertMessage = resp.msg;
          vm.$bvModal.show("message-modal");
          vm.loading = false;
        });
    },
    isPdf(file) {
      let re = /(?:\.([^.]+))?$/;
      if (re.exec(file)[1].toUpperCase() == "PDF") {
        return true;
      }
      return false;
    }
  }
};
</script>

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

.custom-body {
  margin: 10px;
}

.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 {
  margin: 10px;
  border-radius: 20px;
  width: 100%;
  max-width: 192px;
  height: 35px;
}

.btn-default {
  background: #ff9b64;
}

.rounded-div {
  background: #cb2d2d80 0% 0% no-repeat padding-box;
  svg {
    color: #cb2d2d;
  }
}

.close-icon {
  cursor: pointer;
}
</style>
