<script>
import BulkItemsSelect from "./BulkItemsSelect.vue";
import ZohoSearch from "@/components/ZohoSearch.vue";
import LoadingButton from "@/components/LoadingButton.vue";
import { tableMixin } from "@/helpers/tables.mixin";
export default {
  name: "ProformaCreator",
  components: { BulkItemsSelect, ZohoSearch, LoadingButton },
  mixins: [tableMixin],
  data: () => ({
    items: [],
    modalOpen: false,
    newProforma: {
      date_initiated: new Date().toLocaleString("fr-CA", {}).slice(0, 10),
    },
    row: {},
    client: {},
    detailModal: null,
    selectedProduct: null,
  }),
  computed: {
    submitDisabled() {
      return (
        !this.newProforma.date_initiated ||
        !this.newProforma.client_id ||
        !this.items.length ||
        !this.totalAmount ||
        this.hasUnavailableBatch
      );
    },
    addedItems() {
      return this.items.map((item) => item.id);
    },
    totalAmount() {
      return this.items.reduce((a, b) => a + b.total_amount, 0);
    },
    isEditingMode() {
      return this.$route && this.$route.params.reference;
    },
    currentUser() {
      return this.$store.state.user || {};
    },
    hasUnavailableBatch() {
      return this.items.some((item) => !item.batch);
    },
  },
  mounted() {
    if (this.isEditingMode) {
      this.$http
        .get(`stock/proforma/show/${this.$route.params.reference}/items`)
        .then((response) => {
          if (response.data.status) {
            this.row = response.data.row;
            this.newProforma.proforma_id = this.row.id;
            this.newProforma.client_id = this.row.client.id;
            this.client = this.row.client;
            this.newProforma.date_initiated = new Date(this.row.date_initiated)
              .toLocaleString("fr-CA", {})
              .slice(0, 10);
            this.newProforma.vat = this.row.vat;
            const items = response.data.items;
            this.existingItems = items;
            items.forEach((item) => {
              this.items.push({
                id: item.product_id,
                name: item.product.name,
                unit: item.product.unit,
                private_price: item.price,
                quantity: item.quantity,
                total_amount: item.price * item.quantity,
                alreadyExist: true,
                rowId: item.id,
              });
            });
          }
        });
    }
    this.detailModal = new bootstrap.Modal(
      document.getElementById("detail-modal")
    );
  },
  methods: {
    handleItemRemove(i) {
      if (this.items[i].alreadyExist || this.items[i].rowId) {
        this.$confirm({
          title: "Deleting",
          content: `Item already exists. Are you sure you want to delete ${this.items[i].name}? because this action is irreversible.`,
          actionText: "Yes, Continue",
          closeText: "Discard",
          classes: "btn btn-danger",
          action: () => {
            this.$http
              .get(`stock/proforma/items/${this.items[i].rowId}/destroy`)
              .then((response) => {
                if (response.data.status) {
                  this.items.splice(i, 1);
                  this.$notify({
                    type: "success",
                    message: "Record deleted successfully",
                  });
                }
              });
          },
        });
      } else {
        this.items.splice(i, 1);
      }
    },
    getBulkAddedItems(items) {
      this.toggleBulkModal();
      items.forEach((item) => {
        if (!this.addedItems.includes(item.id)) {
          item.total_amount = item.private_price * item.quantity;
          this.items.push(item);
        }
      });
    },
    toggleBulkModal() {
      this.modalOpen = !this.modalOpen;
    },
    calculateItemAmount(i) {
      this.items[i].total_amount =
        this.items[i].private_price * this.items[i].quantity;
    },
    handleSubmit() {
      this.newProforma.amount = this.totalAmount;
      this.newProforma.items = this.items;
      if (!this.$helper.empty(this.currentUser.department)) {
        this.newProforma.department_id = this.currentUser.department.id;
      }
      if (!this.$helper.empty(this.row)) {
        this.newProforma.proforma_id = this.row.id;
      }
      this.$http
        .post(
          "stock/proforma/store",
          this.$helper.generateFormData(this.newProforma)
        )
        .then((response) => {
          if (response.data.status) {
            this.newProforma = {};
            this.items = [];
            this.$notify({
              type: "success",
              message: "Record saved successfully",
            });
            this.$router.push({
              name: "ProformaView",
              params: {
                reference: response.data.ref,
                action: "view",
              },
              query: {
                origin: "proforma",
              },
            });
          }
        });
    },
    productDetailModal(row) {
      this.selectedProduct = row;
      this.$store.commit("SET_AJAX_TASK", "SHOW-PRODUCT-DETAIL");
      setTimeout(this.detailModal.show(), 1);
    },
  },
};
</script>
<template>
  <div class="row">
    <div class="col-12">
      <div
        class="page-title-box d-flex align-items-center justify-content-between"
      >
        <h4 class="mb-0" v-if="isEditingMode && !$helper.empty(row)">
          {{ $trans("Edit Proforma") }} #{{ $helper.padNumber(row.id) }}
        </h4>
        <h4 class="mb-0" v-else>{{ $trans("Create a new Proforma") }}</h4>
        <div class="page-title-right">
          <span class="fw-bold"
            >{{ items.length }} {{ $trans("items added") }}</span
          >
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-12">
      <div class="requisition-items-container">
        <div class="row border-top border-primary pt-4 border-4">
          <div class="col-xl-4 col-lg-6">
            <div class="form-container">
              <div class="mb-1 row">
                <label class="col-md-4 col-form-label required">{{
                  $trans("Date")
                }}</label>
                <div class="col-md-8">
                  <input
                    class="form-control"
                    type="date"
                    v-model="newProforma.date_initiated"
                  />
                </div>
              </div>
              <div
                class="mb-1 row"
                v-if="$helper.empty(currentUser.department)"
              >
                <label class="col-md-4 col-form-label required">{{
                  $trans("Client")
                }}</label>
                <div class="col-md-8">
                  <ZohoSearch
                    url="stock/clients/search"
                    label="name"
                    placeholder="Customer"
                    v-model="newProforma.client_id"
                    :load-defaults="true"
                    fetch-flag="SEARCHING_FOR_CLIENTS"
                    ref="CustomersSelector"
                  ></ZohoSearch>
                </div>
              </div>
            </div>
          </div>
          <div class="col-xl-6 col-lg-6">
            <div class="row mb-1">
              <label for="invoiceFile" class="col-md-2 col-form-label"
                >Reference</label
              >
              <div class="col-md-6">
                <input
                  class="form-control"
                  id="PurchaseReference"
                  placeholder="Reference Id"
                  v-model="newProforma.DocReference"
                  type="text"
                />
              </div>
            </div>
          </div>
        </div>
        <hr />
        <div class="h-100">
          <div
            class="page-title-box d-flex align-items-center justify-content-between"
          >
            <h4 class="mb-0">{{ $trans("Items on Proforma sheet") }}</h4>
            <div class="page-title-right">
              <div class="w-100">
                <a
                  href="javascript:void(0)"
                  class="btn btn-md btn-primary"
                  @click.prevent="toggleBulkModal"
                >
                  <i class="uil uil-plus"></i> {{ $trans("Add Items") }}
                </a>
              </div>
            </div>
          </div>
          <div class="bulf-form-container">
            <table class="table table-form mb-0 sheet-view">
              <thead class="thead-sticky">
                <tr>
                  <th class="text-center px-0" style="width: 35px">#</th>
                  <th style="width: 500px; text-align: center">
                    {{ $trans("Product Name") }}
                  </th>
                  <th style="width: 55px">{{ $trans("Unit") }}</th>
                  <th style="width: 150px" class="required text-center">
                    {{ $trans("Qty") }}
                  </th>
                  <th class="required text-center">
                    {{ $trans("Selling Price") }}
                  </th>
                  <th class="text-center">{{ $trans("Batch") }}</th>
                  <th class="text-center">{{ $trans("Balance") }}</th>
                  <th style="width: 30px"></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, i) in items" :key="'item' + i">
                  <td class="text-center align-middle">
                    {{ i + 1 }}
                  </td>
                  <td class="align-middle">
                    <a
                      href="javascript:void(0)"
                      @click="productDetailModal(item)"
                    >
                      <span class="fw-bolder font-size-12"
                        >{{ item.name || "" }}
                        <small v-if="item.packaging"
                          >[{{ item.packaging || "" }}]</small
                        ></span
                      ></a
                    >
                  </td>
                  <td class="text-left align-middle">
                    <span class="fw-bolder">{{ item.unit || "" }}</span>
                  </td>
                  <td>
                    <div class="sheet-field px-1">
                      <div class="currency-with-amount">
                        <input
                          type="number"
                          v-model="items[i].quantity"
                          class="form-control"
                          placeholder="Qty"
                          @keyup="calculateItemAmount(i)"
                        />
                      </div>
                    </div>
                  </td>
                  <td>
                    <div class="sheet-field">
                      <div class="currency-with-amount">
                        <input
                          type="number"
                          v-model="items[i].private_price"
                          class="form-control text-purple fw-bold"
                          placeholder="Selling Price"
                          @keyup="calculateItemAmount(i)"
                        />
                      </div>
                    </div>
                  </td>
                  <td>
                    <div class="sheet-field">
                      <div class="currency-with-amount">
                        <select
                          class="form-control"
                          style="width: 100px"
                          v-model="items[i].batch"
                        >
                          <option :value="undefined" hidden disabled>
                            Batch
                          </option>
                          <option v-for="batch in item.product_changes">
                            {{ batch.batch_nber }}
                          </option>
                        </select>
                      </div>
                    </div>
                  </td>
                  <td>
                    <div class="sheet-field">
                      <div class="currency-with-amount">
                        <input
                          type="number"
                          readonly
                          v-model="items[i].total_amount"
                          class="form-control fw-bold"
                          placeholder="Total Amount"
                        />
                      </div>
                    </div>
                  </td>
                  <td class="text-center align-middle">
                    <a
                      href="javascript:void(0)"
                      @click.prevent="handleItemRemove(i)"
                    >
                      <i class="uil uil-trash text-danger fs-5"></i>
                    </a>
                  </td>
                </tr>
                <tr
                  v-if="!items.length"
                  style="border-color: transparent !important"
                >
                  <td
                    colspan="6"
                    class="text-center"
                    style="padding: 1rem !important"
                  >
                    <span class="fw-bolder py-4 h5">{{
                      $trans("No Items Added")
                    }}</span>
                  </td>
                </tr>
                <tr v-if="totalAmount">
                  <td colspan="6">
                    <span style="font-family: nunito">
                      <span class="text-primary font-size-11 fw-bold">{{
                        NumInWords(totalAmount).toUpperCase()
                      }}</span></span
                    >
                  </td>
                  <td>
                    <span class="h5"
                      ><small class="me-2">FBU</small>
                      <b class="fw-bold">{{
                        $helper.formatNumber(totalAmount)
                      }}</b></span
                    >
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
  <hr />
  <div
    class="border-top shadow w-100 fixed-bottom p-4 main-content bg-white"
    style="z-index: 999"
  >
    <LoadingButton
      @clicked="handleSubmit"
      class="btn btn-md btn-primary"
      type="button"
      task="RECEIVING_ITEMS"
      :disabled="submitDisabled"
    >
      <template #caption>{{ $trans("Save") }}</template>
    </LoadingButton>
    <button class="btn btn-light ms-2" type="button">
      {{ $trans("Cancel") }}
    </button>
  </div>
  <BulkItemsSelect
    @closed="toggleBulkModal"
    @confirmed="getBulkAddedItems"
    v-if="modalOpen"
  />

  <div
    class="modal fade bs-example-modal-lg"
    id="detail-modal"
    tabindex="-1"
    aria-labelledby="detail-modalLabel"
    aria-hidden="true"
  >
    <div class="modal-dialog modal-lg modal-dialog-centered">
      <div class="modal-content" v-if="selectedProduct != null">
        <div class="modal-header bg-primary">
          <h5 class="modal-title text-white" id="detail-modalLabel">
            Product Details #<span class="fw-bold text-white"
              >{{ selectedProduct.name }}
              <i class="font-size-13">{{ selectedProduct.packaging }}</i></span
            >
          </h5>
        </div>
        <div class="modal-body p-2">
          <div class="row g-gs align-items-center">
            <div class="col-12">
              <div class="table-responsive">
                <table
                  class="table font-size-13 table-light table-hover table-striped align-middle table-nowrap table-check"
                  id="pagination-table"
                >
                  <tbody>
                    <tr>
                      <td class="fw-bold">Current Quantity:</td>
                      <td class="fw-bold text-purple">
                        {{ selectedProduct.available_qty || "N/A" }}
                        {{
                          selectedProduct.unit || ""
                        }}
                      </td>
                    </tr>
                  </tbody>
                </table>
                <table
                  class="table font-size-13 table-light table-hover table-striped align-middle table-nowrap table-check"
                  id="pagination-table"
                >
                  <thead>
                    <tr>
                      <th>#</th>
                      <th>Batch number</th>
                      <th>Quantity</th>
                      <th>Price</th>
                      <th>Expiration date</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr
                      v-for="(
                        productChange, i
                      ) in selectedProduct.product_changes"
                      :key="i"
                    >
                      <td>{{ i + 1 }}</td>
                      <td>{{ productChange.batch_nber }}</td>
                      <td class="fw-bold">{{ productChange.quantity }}</td>
                      <td>{{ productChange.price }}</td>
                      <td>{{ productChange.expiration_date }}</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
