<template>
  <div>
    <q-form @submit="save" class="q-mt-sm" ref="myForm">
      <div  class="form-section q-mb-sm">
        <div class="section-header">
          <div class="section-number">1</div>
          <div class="section-title">Quem pagará pelo frete?</div>
        </div>
        <div class="q-pa-md">
          <q-option-group
            type="radio"
            v-model="item.payer"
            :options="options"
          />
        </div>
      </div>

      <div v-if="loadingContact" class="row">
        <div class="col-12 pageloader">
          <q-spinner color="primary" class="q-uploader__spinner" />
        </div>
      </div>

      <div v-if="loadingContact === false && item.payer !== false">
        <div class="form-section q-mb-sm">
          <div class="section-header">
            <div class="section-number">2</div>
            <div class="section-title">Dados da coleta</div>
          </div>
          <div class="q-pa-md">
            <div class="row justify-center items-stretch">
              <div class="col-xs-12 col-sm-5">
                <div class="summary-card">
                  <div class="summary-card-title">Dados da coleta</div>
                  <q-markup-table
                    bordered
                    separator="none"
                    class="summary-table"
                  >
                    <tbody>
                    <tr>
                      <td class="text-left text-bold">Nome</td>
                      <td class="text-left">
                        {{ retrieveIsCompany ? loggedContactName : (steps.retrieve ? steps.retrieve.name : '') }}
                      </td>
                    </tr>
                    <tr v-if="retrieveIsCompany && companyName">
                      <td class="text-left text-bold">Empresa</td>
                      <td class="text-left">
                        {{ companyName }}
                      </td>
                    </tr>
                    <tr v-if="retrieveCompanyDocument">
                      <td class="text-left text-bold">Documento</td>
                      <td class="text-left">
                        {{ retrieveCompanyDocument }}
                      </td>
                    </tr>
                    <tr>
                      <td class="text-left text-bold">E-Mail</td>
                      <td class="text-left">
                        {{ retrieveIsCompany ? loggedContactEmail : (steps.retrieve && steps.retrieve.contact ? steps.retrieve.contact.email : '') }}
                      </td>
                    </tr>
                    <tr>
                      <td class="text-left text-bold">Telefone</td>
                      <td class="text-left">
                        {{ retrieveIsCompany ? (loggedContactPhone ? fPhone(loggedContactPhone) : '') : (steps.retrieve && steps.retrieve.contact ? fPhone(steps.retrieve.contact.phone) : '') }}
                      </td>
                    </tr>
                    <tr>
                      <td class="text-left text-bold">CEP</td>
                      <td class="text-left">
                        {{ steps.retrieve && steps.retrieve.address ? formatCEP(steps.retrieve.address.postal_code) : '' }}
                      </td>
                    </tr>

                    <tr>
                      <td class="text-left text-bold">Endereço</td>
                      <td class="text-left">
                        {{ steps.retrieve && steps.retrieve.address ? `${steps.retrieve.address.street}, ${steps.retrieve.address.number} ${steps.retrieve.address.complement}` : '' }}
                      </td>
                    </tr>
                    <tr>
                      <td class="text-left text-bold">Bairro</td>
                      <td class="text-left">
                        {{ steps.retrieve && steps.retrieve.address ? steps.retrieve.address.district : '' }}
                      </td>
                    </tr>
                    <tr>
                      <td class="text-left text-bold">Cidade</td>
                      <td class="text-left">
                        {{ steps.retrieve && steps.retrieve.address ? `${steps.retrieve.address.city} / ${steps.retrieve.address.state}` : '' }}
                      </td>
                    </tr>
                    </tbody>
                  </q-markup-table>
                </div>
              </div>
              <div class="col-xs-12 col-sm-2 gt-xs">
                <div class="row justify-center items-center full-height">
                  <q-icon
                    name="local_shipping"
                    class="text-primary"
                    style="font-size: 3em"
                  />
                </div>
              </div>
              <div class="col-xs-12 col-sm-5">
                <div class="summary-card">
                  <div class="summary-card-title">Dados da entrega</div>
                  <q-markup-table
                    bordered
                    separator="none"
                    class="summary-table"
                  >
                    <tbody>
                    <tr>
                      <td class="text-left text-bold">Nome</td>
                      <td class="text-left">
                        {{ deliveryIsCompany ? loggedContactName : (steps.delivery ? steps.delivery.name : '') }}
                      </td>
                    </tr>
                    <tr v-if="deliveryIsCompany && companyName">
                      <td class="text-left text-bold">Empresa</td>
                      <td class="text-left">
                        {{ companyName }}
                      </td>
                    </tr>
                    <tr v-if="deliveryCompanyDocument">
                      <td class="text-left text-bold">Documento</td>
                      <td class="text-left">
                        {{ deliveryCompanyDocument }}
                      </td>
                    </tr>
                    <tr>
                      <td class="text-left text-bold">E-Mail</td>
                      <td class="text-left">
                        {{ deliveryIsCompany ? loggedContactEmail : (steps.delivery && steps.delivery.contact ? steps.delivery.contact.email : '') }}
                      </td>
                    </tr>
                    <tr>
                      <td class="text-left text-bold">Telefone</td>
                      <td class="text-left">
                        {{ deliveryIsCompany ? (loggedContactPhone ? fPhone(loggedContactPhone) : '') : (steps.delivery && steps.delivery.contact ? fPhone(steps.delivery.contact.phone) : '') }}
                      </td>
                    </tr>
                    <tr>
                      <td class="text-left text-bold">CEP</td>
                      <td class="text-left">
                        {{ steps.delivery && steps.delivery.address ? formatCEP(steps.delivery.address.postal_code) : '' }}
                      </td>
                    </tr>

                    <tr>
                      <td class="text-left text-bold">Endereço</td>
                      <td class="text-left">
                        {{ steps.delivery && steps.delivery.address ? `${steps.delivery.address.street}, ${steps.delivery.address.number} ${steps.delivery.address.complement}` : '' }}
                      </td>
                    </tr>
                    <tr>
                      <td class="text-left text-bold">Bairro</td>
                      <td class="text-left">
                        {{ steps.delivery && steps.delivery.address ? steps.delivery.address.district : '' }}
                      </td>
                    </tr>
                    <tr>
                      <td class="text-left text-bold">Cidade</td>
                      <td class="text-left">
                        {{ steps.delivery && steps.delivery.address ? `${steps.delivery.address.city} / ${steps.delivery.address.state}` : '' }}
                      </td>
                    </tr>
                    </tbody>
                  </q-markup-table>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="form-section q-mb-sm">
          <div class="section-header">
            <div class="section-number">3</div>
            <div class="section-title">Resumo da carga</div>
          </div>
          <div class="q-pa-md">
            <div class="row">
              <div class="col-xs-12">
                <q-markup-table flat class="q-mb-md">
                  <thead>
                    <tr>
                      <th>Cubagem</th>
                      <th>Tipo de material</th>
                      <th>Valor da nota fiscal</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <td class="text-center">
                        {{
                          `${new Intl.NumberFormat("pt-br").format(
                            this.order.product.sumCubage
                          )} kg`
                        }}
                      </td>
                      <td class="text-center">
                        {{ this.order.product.type }}
                      </td>
                      <td class="text-center">
                        {{ formatMoney(this.order.product.totalPrice) }}
                      </td>
                    </tr>
                  </tbody>
                </q-markup-table>
              </div>

              <div v-if="order.product.packages.length > 0" class="col-xs-12">
                <div class="col-xs-12 text-subtitle2 q-mb-sm">
                  Detalhes dos produtos
                </div>
                <q-markup-table class="q-mb-md">
                  <thead>
                    <tr>
                      <th>Quantidade</th>
                      <th>Peso</th>
                      <th>Altura</th>
                      <th>Largura</th>
                      <th>Profundidade</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr
                      v-for="(myPackage, index) in order.product.packages"
                      :key="index"
                    >
                      <td class="text-center">{{ myPackage.qtd }}</td>
                      <td class="text-center">{{ `${myPackage.weight} kg` }}</td>
                      <td class="text-center">{{ `${myPackage.height} m` }}</td>
                      <td class="text-center">{{ `${myPackage.width} m` }}</td>
                      <td class="text-center">{{ `${myPackage.depth} m` }}</td>
                    </tr>
                  </tbody>
                </q-markup-table>
              </div>
            </div>
          </div>
        </div>

        <div class="form-section q-mb-sm">
          <div class="section-header">
            <div class="section-number">4</div>
            <div class="section-title">Observações</div>
          </div>
          <div class="q-pa-md">
            <q-input
              outlined
              stack-label
              v-model="item.comments"
              type="textarea"
              label="Observações"
            />
          </div>
        </div>

        <div class="form-section q-mb-sm">
          <div class="section-header">
            <div class="section-number">5</div>
            <div class="section-title">Finalização</div>
          </div>
          <div class="q-pa-md">
            <div class="row justify-end">
              <div class="col-12 q-mb-sm">
                <q-list>
                  <q-item tag="label" v-ripple>
                    <q-item-section avatar top>
                      <q-checkbox v-model="termsAccepted" color="secondary" />
                    </q-item-section>
                    <q-item-section>
                      <q-item-label>
                        Aceito os
                        <a href="https://www.freteclick.com.br/termos-e-condicoes" target="_blank"
                          >termos e condições</a
                        >
                      </q-item-label>
                    </q-item-section>
                  </q-item>
                </q-list>
              </div>
              <q-btn
                type="submit"
                color="primary"
                label="Finalizar pedido"
                :loading="isLoading"
              />
              <div class="col-12 q-mt-sm text-subtitle1 text-right">
                * Não incluso a Taxa de Dificuldade de Entrega (TDE para CNPJ) e Zona Rural (TZR), que serão repassadas à parte, por incidência, conf. Transportadora
              </div>
              <div class="col-12 q-mt-sm text-subtitle1 text-right">
                * Coleta e Entrega em horário comercial e responsável no local - ausência sujeitará a custo adicional
              </div>
              <div class="col-12 q-mt-sm text-subtitle1 text-right">
                * Mercadorias frágeis, como/contendo : pisos, vidro, cerâmica, acrílico, etc, transporte somente com Carta de Isenção de Avarias
              </div>
              <div class="col-12 q-mt-sm text-subtitle1 text-right">
                * Instruir o Destinatário sobre obrigatoriedade de ressalva no documento no ato do recebimento e/ou recusa de mercadoria avariada.
              </div>
            </div>
          </div>
        </div>
      </div>
    </q-form>

    <q-dialog
      v-model="dialogs.details.visible"
      transition-show="scale"
      transition-hide="scale"
    >
      <q-card class="text-white" style="background-color: #00519b">
        <q-card-section>
          <div class="row items-center">
            <div class="text-h6">Detalhes</div>
            <q-space />
            <q-btn icon="close" color="white" flat round dense v-close-popup />
          </div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          <q-markup-table>
            <tbody>
              <tr>
                <td class="text-left">Nome</td>
                <td class="text-left">{{ dialogs.details.data.name }}</td>
              </tr>
              <tr>
                <td class="text-left">Email</td>
                <td class="text-left">{{ dialogs.details.data.email }}</td>
              </tr>
              <tr>
                <td class="text-left">Telefone</td>
                <td class="text-left">{{ dialogs.details.data.phone }}</td>
              </tr>
              <tr>
                <td class="text-left">País</td>
                <td class="text-left">{{ dialogs.details.data.country }}</td>
              </tr>
              <tr>
                <td class="text-left">Estado</td>
                <td class="text-left">{{ dialogs.details.data.state }}</td>
              </tr>
              <tr>
                <td class="text-left">Cidade</td>
                <td class="text-left">{{ dialogs.details.data.city }}</td>
              </tr>
              <tr>
                <td class="text-left">Bairro</td>
                <td class="text-left">{{ dialogs.details.data.district }}</td>
              </tr>
              <tr>
                <td class="text-left">CEP</td>
                <td class="text-left">
                  {{ dialogs.details.data.postal_code }}
                </td>
              </tr>
              <tr>
                <td class="text-left">Rua</td>
                <td class="text-left">{{ dialogs.details.data.street }}</td>
              </tr>
              <tr>
                <td class="text-left">Número</td>
                <td class="text-left">{{ dialogs.details.data.number }}</td>
              </tr>
              <tr></tr>
            </tbody>
          </q-markup-table>
        </q-card-section>
      </q-card>
    </q-dialog>
  </div>
</template>

<script>
import { mapActions, mapGetters } from "vuex";
import { formatPhone } from "@freteclick/quasar-common-ui/src/utils/formatter";

export default {
  props: {
    order: {
      type: Object,
      required: true,
    },
    steps: {
      type: Object,
      required: true,
    },
  },

  mounted() {
    const retrieveId =
      this.steps && this.steps.retrieve ? this.steps.retrieve.id : null;
    if (!this.item.payer && retrieveId) {
      this.item.payer = retrieveId;
      return;
    }
    if (this.item.payer) {
      this.syncPeopleDocument(this.item.payer);
    }
  },

  data() {
    return {
      isCif: false,
      isLoading: false,
      loadingContact: false,
      peopleDocument: "",
      dialogs: {
        details: {
          visible: false,
          data: {
            name: null,
            email: null,
            phone: null,
            country: null,
            state: null,
            city: null,
            district: null,
            postal_code: null,
            street: null,
            number: null,
          },
        },
      },
      item: {
        payer: false,
        comments: "",
        paymentType: null,
      },
      termsAccepted: false,
    };
  },

  watch: {
    "item.payer": function (peopleId) {
      this.syncPeopleDocument(peopleId);
    },
  },

  computed: {
    ...mapGetters({
      defaultCompany: "people/defaultCompany",
      myCompany: "people/currentCompany",
    }),
    loggedUser() {
      return this.$store.getters["auth/user"];
    },
    companyName() {
      const company = this.myCompany || this.defaultCompany;
      return company ? (company.alias || company.name || "") : "";
    },
    loggedContactName() {
      const user = this.loggedUser;
      return user ? (user.realname || user.username || user.user || "") : "";
    },
    loggedContactEmail() {
      const user = this.loggedUser;
      return user ? user.email || "" : "";
    },
    loggedContactPhone() {
      const user = this.loggedUser;
      return user ? user.phone || "" : "";
    },
    retrieveIsCompany() {
      return (
        this.steps &&
        this.steps.retrieve &&
        this.steps.retrieve.whereRetrieve === "MC"
      );
    },
    deliveryIsCompany() {
      return (
        this.steps &&
        this.steps.delivery &&
        this.steps.delivery.whereDelivery === "MC"
      );
    },
    retrieveCompanyDocument() {
      return this.formatDocumentValue(
        this.getDocumentValue(this.steps && this.steps.retrieve ? this.steps.retrieve.document : null)
      );
    },
    deliveryCompanyDocument() {
      return this.formatDocumentValue(
        this.getDocumentValue(this.steps && this.steps.delivery ? this.steps.delivery.document : null)
      );
    },
    options() {
      let opts = [];
      if (!this.steps || !this.steps.retrieve || !this.steps.delivery) {
        return opts;
      }
      if (this.item.payer === false || this.item.payer === null) {
        this.item.payer = this.steps.retrieve.id;
      }
      if (this.steps.retrieve.id == this.steps.delivery.id) {
        this.isCif = true;
        this.item.payer = this.steps.retrieve.id;
        opts.push({
          label: `${
            this.steps.retrieve.name || (this.steps.retrieve.contact ? this.steps.retrieve.contact.name : '')
          } (CIF)`,
          value: this.steps.retrieve.id,
        });
      } else {
        opts.push({
          label: `${
            this.steps.retrieve.name || (this.steps.retrieve.contact ? this.steps.retrieve.contact.name : '')
          } (CIF)`,
          value: this.steps.retrieve.id,
        });

        opts.push({
          label: `${
            this.steps.delivery.name || (this.steps.delivery.contact ? this.steps.delivery.contact.name : '')
          } (FOB)`,
          value: this.steps.delivery.id,
        });
      }

      //opts.push({label: "Outra pessoa",value: null,});

      return opts;
    },
  },

  methods: {
    ...mapActions({
      contact: "people/contact",
    }),

    getDocumentValue(document) {
      if (!document) return "";
      if (typeof document === "string" || typeof document === "number") {
        return document.toString();
      }
      if (Array.isArray(document) && document.length > 0) {
        return this.getDocumentValue(document[0]);
      }
      if (document.id) return document.id.toString();
      if (document.document) return document.document.toString();
      return "";
    },

    normalizeDocument(document) {
      return (document || "").toString().replace(/\D/g, "");
    },

    formatDocumentValue(document) {
      const digits = this.normalizeDocument(document);
      if (!digits) return "";
      if (digits.length === 11) {
        return digits.replace(/^(\d{3})(\d{3})(\d{3})(\d{2})$/, "$1.$2.$3-$4");
      }
      if (digits.length === 14) {
        return digits.replace(
          /^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/,
          "$1.$2.$3/$4-$5"
        );
      }
      return digits;
    },

    syncPeopleDocument(peopleId) {
      if (!peopleId) return;
      const localPayer =
        this.steps && this.steps.retrieve && this.steps.retrieve.id == peopleId
          ? this.steps.retrieve
          : this.steps && this.steps.delivery && this.steps.delivery.id == peopleId
          ? this.steps.delivery
          : null;
      if (localPayer) {
        const localDoc = this.getDocumentValue(localPayer.document);
        this.peopleDocument = this.normalizeDocument(localDoc);
      }
      this.searchContact(peopleId).then((response) => {
        if (response && response.document) {
          this.peopleDocument = this.normalizeDocument(
            this.getDocumentValue(response.document)
          );
        } else if (!this.peopleDocument) {
          this.peopleDocument = "";
        }
      });
    },

    seeDetails(data) {
      this.dialogs.details.data.name = data.contact.name;
      this.dialogs.details.data.email = data.contact.email;
      this.dialogs.details.data.phone = this.fPhone(data.contact.phone);
      this.dialogs.details.data.country = data.address.country;
      this.dialogs.details.data.state = data.address.state;
      this.dialogs.details.data.city = data.address.city;
      this.dialogs.details.data.district = data.address.district;
      this.dialogs.details.data.postal_code = this.formatCEP(
        data.address.postal_code
      );
      this.dialogs.details.data.street = data.address.street;
      this.dialogs.details.data.number = data.address.number;

      this.dialogs.details.visible = true;
    },

    save() {
      if (
        this.termsAccepted === false &&
        this.defaultCompany.domainType != "ceg"
      ) {
        this.$q.notify({
          message: "Primeiro deve aceitar os termos e condições",
          position: "bottom",
          type: "negative",
        });
        return;
      }

      this.isLoading = true;

      this.$emit("saved", {
        errors: false,
        data: {
          ...this.item,
          peopleDocument: this.peopleDocument,
        },
        hasCallback: function () {
          this.isLoading = false;
        }.bind(this),
      });
    },

    fPhone(phone) {
      return formatPhone(phone);
    },
    formatCEP(cep) {
      return formatPhone(cep);
    },
    formatMoney(value) {
      let formatter = new Intl.NumberFormat(this.$i18n.locale, {
        style: "currency",
        currency: "BRL",
      });

      if (typeof value == "string") value = value.replace(",", ".");

      return formatter.format(value);
    },

    isInvalid(key) {
      return (val) => {
        if (!(val && val.length > 0)) return this.$t("messages.fieldRequired");

        if (key == "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val))
          return this.$t("messages.emailInvalid");

        if (key == "phone") {
          const digits = (val || '').replace(/\D/g, '');
          if (!(digits.length >= 10 && digits.length <= 11))
            return this.$t("messages.phoneInvalid");
        }

        if (key == "password" && val.length < 6)
          return this.$t("A senha deve ter no mínimo 6 caracteres");

        if (key == "confirm" && this.item.password != this.item.confirmPassword)
          return this.$t("As senhas não coincidem");

        return true;
      };
    },

    searchContact(id) {
      let request = {
        id: id,
        params: { id: id },
      };

      this.loadingContact = true;

      return this.contact(request)
        .then((response) => {
          let hasErrors = !(response && response.success === true);

          return hasErrors === false ? response.data : false;
        })
        .catch((error) => {
          this.notifyError(error.message);
        })
        .finally(() => {
          this.loadingContact = false;
        });
    },

    isInvalid(key) {
      return (val) => {
        if (!(val && val.length > 0)) return this.$t("messages.fieldRequired");

        return true;
      };
    },
  },
};
</script>

<style scoped lang="scss">
.pageloader {
  text-align: center;
}

.form-section {
  border-left: 4px solid $primary;
  padding-left: 0.75rem;
  padding-top: 0.25rem;
  padding-bottom: 0.25rem;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 0.25rem;
}

.section-number {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  background-color: $primary;
  color: white;
  border-radius: 50%;
  font-weight: bold;
  font-size: 0.9rem;
  flex-shrink: 0;
}

.section-title {
  font-size: 1rem;
  font-weight: 500;
  color: $dark;
  margin: 0;
}

.summary-card {
  background: #fff;
  border: 1px solid #e6e6e6;
  border-radius: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.summary-card-title {
  background: #f7f8fa;
  color: $primary;
  font-weight: 600;
  padding: 0.75rem 1rem;
  border-bottom: 1px solid #e6e6e6;
}

.summary-table {
  width: 100%;
}

.summary-table td {
  padding: 0.6rem 1rem;
}

.summary-table tr:nth-child(even) td {
  background: #fcfcfd;
}

.summary-table td:first-child {
  color: $dark;
  font-weight: 600;
  width: 38%;
}
</style>
