<script>
import BulkItemsSelect from "./BulkItemsSelect.vue";
import LoadingButton from "@/components/LoadingButton.vue";
import ZohoSearch from "@/components/ZohoSearch.vue";
import { tableMixin } from "@/helpers/tables.mixin";

export default {
  name: "PurchaseOrderCreator",
  mixins: [tableMixin],
  components: { BulkItemsSelect, LoadingButton, ZohoSearch },
  data: () => ({
    items: [],
    modalOpen: false,
    newPurchaseOrder: {
      date_initiated: new Date().toLocaleString("fr-CA", {}).slice(0, 10),
    },
    row: {},
  }),
  computed: {
    submitDisabled() {
      return (
        !this.newPurchaseOrder.date_initiated ||
        !this.items.length ||
        !this.totalAmount ||
        !this.newPurchaseOrder.currency ||
        !this.newPurchaseOrder.supplier_id
      );
    },
    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 || {};
    },
  },
  mounted() {
    if (this.isEditingMode) {
      this.$http
        .get(`stock/purchase-order/show/${this.$route.params.reference}/items`)
        .then((response) => {
          if (response.data.status) {
            this.row = response.data.row;
            this.newPurchaseOrder.date_initiated = new Date(
              this.row.date_initiated
            )
              .toLocaleString("fr-CA", {})
              .slice(0, 10);
            this.newPurchaseOrder.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,
                price: item.price,
                quantity: item.quantity,
                total_amount: item.price * item.quantity,
                alreadyExist: true,
                rowId: item.id,
              });
            });
          }
        });
    }
  },
  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}?`,
          actionText: "Yes, Continue",
          closeText: "Discard",
          classes: "btn btn-danger",
          action: () => {
            this.$http
              .get(
                `stock/purchase-order/${this.row.id}/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.price * item.quantity;
          this.items.push(item);
        }
      });
    },
    toggleBulkModal() {
      this.modalOpen = !this.modalOpen;
    },
    calculateItemAmount(i) {
      this.items[i].total_amount = this.items[i].price * this.items[i].quantity;
    },
    handleSubmit() {
      let uploadedFile = document.querySelector("#invoiceFile");
      this.newPurchaseOrder.amount = this.totalAmount;
      this.newPurchaseOrder.items = this.items;
      if (!this.$helper.empty(this.row)) {
        this.newPurchaseOrder.requisition_id = this.row.id;
      }
      let fd = this.$helper.generateFormData(this.newPurchaseOrder);
      if (uploadedFile.files.length != 0) {
        fd.append("file", uploadedFile.files[0], uploadedFile.files[0].name);
      }
      this.$http.post("stock/purchase-order/store", fd).then((response) => {
        if (response.data.status) {
          this.newPurchaseOrder = {};
          this.items = [];
          this.$notify({
            type: "success",
            message: "Record saved successfully",
          });
          this.$router.push({
            name: "PurchaseOrderView",
            params: {
              reference: response.data.ref,
              action: "view",
            },
            query: {
              origin: "purchaseorder",
            },
          });
        }
      });
    },
  },
};
</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">{{ $trans("Make a Purchase Order") }}</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-6 col-lg-6">
            <div class="form-container">
              <div class="mb-1 row">
                <label for="Date" class="col-md-4 col-form-label required">{{
                  $trans("Date")
                }}</label>
                <div class="col-md-8">
                  <input
                    class="form-control"
                    type="date"
                    id="Date"
                    v-model="newPurchaseOrder.date_initiated"
                  />
                </div>
              </div>
              <div class="mb-1 row">
                <label class="col-md-4 col-form-label required">{{
                  $trans("Supplier")
                }}</label>
                <div class="col-md-8">
                  <ZohoSearch
                    placeholder="Select supplier"
                    url="stock/suppliers/search"
                    label="name"
                    :load-defaults="true"
                    v-model="newPurchaseOrder.supplier_id"
                  ></ZohoSearch>
                </div>
              </div>
              <div class="row mb-1">
                <label
                  for="currency"
                  class="required col-md-4 col-form-label"
                  >{{ $trans("Currency") }}</label
                >
                <div class="col-md-8">
                  <ZohoSearch
                    placeholder="Select Currency"
                    url="stock/currency/search"
                    label="name"
                    :load-defaults="true"
                    v-model="newPurchaseOrder.currency"
                  ></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">{{
                $trans("Attachment")
              }}</label>
              <div class="col-md-8">
                <input
                  class="form-control"
                  id="invoiceFile"
                  type="file"
                  multiple
                />
              </div>
            </div>
            <div class="row mb-1">
              <label for="invoiceFile" class="col-md-2 col-form-label"
                >Reference</label
              >
              <div class="col-md-8">
                <input
                  class="form-control"
                  id="PurchaseReference"
                  placeholder="Reference Id"
                  v-model="newPurchaseOrder.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("Purchase Order List") }}
              <span class="text-purple">(P.O)</span>
            </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">
                    {{ $trans("Qty") }}
                  </th>
                  <th class="required">{{ $trans("Purchase Price") }}</th>
                  <th>{{ $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">
                    <span class="fw-bolder font-size-12">{{ item.name }}</span>
                  </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].price"
                          class="form-control"
                          placeholder="Purchase Price"
                          @keyup="calculateItemAmount(i)"
                        />
                      </div>
                    </div>
                  </td>
                  <td>
                    <div class="sheet-field">
                      <div class="currency-with-amount">
                        <!-- <div class="currency-field">FBU</div> -->
                        <input
                          type="number"
                          readonly
                          v-model="items[i].total_amount"
                          class="form-control font-size-15"
                          style="font-weight: 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="5">
                    <span style="font-family: nunito">
                      <span class="text-primary font-size-11 fw-bold">{{
                        NumInWords(totalAmount).toUpperCase()
                      }}</span></span
                    >
                  </td>
                  <td>
                    <span class="h5"
                      >
                      <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"
  />
</template>
