<script>
import BulkItemsSelect from "./BulkItemsSelect.vue";
import ZohoSearch from "@/components/ZohoSearch.vue";
import LoadingButton from "@/components/LoadingButton.vue";
import { permissionsHandler } from "@/helpers/permissions-handler";
import { object, string, number, required, min } from "yup";
export default {
  name: "ItemsTransfer",
  mixins: [permissionsHandler],
  components: { BulkItemsSelect, ZohoSearch, LoadingButton },
  data: () => ({
    items: [],
    modalOpen: false,
    newTransfer: {
      date_transfered: new Date().toLocaleString("fr-CA", {}).slice(0, 10),
    },
    row: {},
    requisition: {},
    string,
    number,
    required,
    min,
    invalidInputs: {},
    department: "",
  }),
  computed: {
    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 &&
        this.$route.params.action == "edit"
      );
    },
    isDeliverMode() {
      return (
        this.$route &&
        this.$route.params.reference &&
        this.$route.params.action == "deliver"
      );
    },
    submitDisabled() {
      return (
        !this.newTransfer.date_transfered ||
        // !this.newTransfer.department_id ||
        !this.newTransfer.taken_by ||
        !this.items.length ||
        !this.totalAmount ||
        this.hasUnavailableItems ||
        !this.$helper.empty(this.invalidInputs)
      );
    },
    hasUnavailableItems() {
      return this.items.some(
        (item) => item.quantity > item.available_qty || !item.price
      );
    },
  },
  mounted() {
    if (this.isDeliverMode) {
      this.$http
        .get(`stock/requisitions/show/${this.$route.params.reference}/items`)
        .then((response) => {
          if (response.data.status) {
            this.requisition = response.data.row;
            this.department = this.requisition.department.name;
            this.newTransfer.department_id = this.requisition.department_id;
            this.newTransfer.date_transfered = new Date()
              .toLocaleString("fr-CA", {})
              .slice(0, 10);
            const items = response.data.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,
                available_qty: item.product.quantity,
              });
            });
          }
        });
    }
    if (this.isEditingMode) {
      this.$http
        .get(`stock/inventory/transfers/show/${this.$route.params.reference}`)
        .then((response) => {
          if (response.data.status) {
            this.row = response.data.row;
            this.newTransfer.department_id = this.row.department_id;
            this.newTransfer.taken_by = this.row.taken_by;
            this.newTransfer.date_transfered = new Date(
              this.row.date_transfered
            )
              .toLocaleString("fr-CA", {})
              .slice(0, 10);
            const items = response.data.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: {
    //string () v, number(), required(), min(),
    handleValidation(e, regx) {
      const schema = object(Object.fromEntries([[e.target.name, regx.rules]]));
      try {
        schema.validateSync(
          Object.fromEntries([[e.target.name, e.target.value]])
        );
        delete this.invalidInputs[e.target.name];
      } catch (err) {
        this.invalidInputs[e.target.name] = err.errors;
        //console.log(err.errors);
      }
    },
    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/inventory/transfers/${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) => {
        console.log(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() {
      this.newTransfer.amount = this.totalAmount;
      this.newTransfer.items = this.items;
      if (!this.$helper.empty(this.row)) {
        this.newTransfer.transfer_id = this.row.id;
      }
      if (!this.$helper.empty(this.requisition)) {
        this.newTransfer.requisition_id = this.requisition.id;
      }
      this.$http
        .post(
          "stock/inventory/transfers/store",
          this.$helper.generateFormData(this.newTransfer)
        )
        .then((response) => {
          if (response.data.status) {
            this.newTransfer = {};
            this.items = [];
            this.$notify({
              type: "success",
              message: "Record saved successfully",
            });
          }
        });
    },
  },
};
</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="isDeliverMode && !$helper.empty(requisition)">
          {{ $trans("Deliver items of Requisition") }} #{{
            $helper.padNumber(requisition.id)
          }}
        </h4>
        <h4 class="mb-0" v-else-if="isEditingMode && !$helper.empty(row)">
          {{ $trans("Edit Requisition") }}
          <span class="fw-bold">#{{ $helper.padNumber(row.id) }}</span>
        </h4>
        <h4 class="mb-0" v-else>
          {{ $trans("Transfer items to departments") }}
        </h4>

        <div class="page-title-right">
          <span class="fw-bold"
            >{{ items.length }} {{ $trans("items added") }}</span
          >
        </div>
      </div>
    </div>
  </div>
  <hr />
  <div class="row">
    <div class="col-12">
      <div class="transfer-items-container">
        <div class="row">
          <div class="col-xl-4 col-lg-6">
            <div class="form-container">
              <div class="mb-3 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="newTransfer.date_transfered"
                  />
                </div>
              </div>
              <div class="mb-3 row" v-if="!isDeliverMode">
                <label class="col-md-4 col-form-label">{{
                  $trans("Department")
                }}</label>
                <div class="col-md-8">
                  <ZohoSearch
                    placeholder="Select Department"
                    url="departments/search"
                    label="name"
                    :load-defaults="true"
                    v-model="newTransfer.department_id"
                    style="z-index: 999"
                  ></ZohoSearch>
                </div>
              </div>
              <div class="mb-3 row">
                <label class="col-md-4 col-form-label required">{{
                  $trans("Taken By")
                }}</label>
                <div class="col-md-8">
                  <ZohoSearch
                    placeholder="Select Employee"
                    url="users/search"
                    label="name"
                    :load-defaults="true"
                    v-model="newTransfer.taken_by"
                  ></ZohoSearch>
                </div>
              </div>
              <div class="mb-3 row" v-if="isDeliverMode">
                <label class="col-md-4 col-form-label">{{
                  $trans("Status")
                }}</label>
                <div class="col-md-8">
                  <span
                    class="badge bg-success"
                    v-if="this.requisition.status == 'ACCEPTED'"
                    >{{ $trans("ACCEPTED") }}</span
                  >
                  <span
                    class="badge bg-warning"
                    v-else-if="this.requisition.status == 'PENDING'"
                    >{{ $trans("PENDING") }}</span
                  >
                  <span class="badge bg-danger" v-else>{{
                    $trans("Cancelled")
                  }}</span>
                </div>
              </div>
              <div class="mb-3 row" v-if="isDeliverMode">
                <label class="col-md-4 col-form-label">{{
                  $trans("Department")
                }}</label>
                <div class="col-md-8">
                  <span class="badge bg-purple">
                    {{ this.department }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <hr />
        <div class="h-100 mt-4">
          <div
            class="page-title-box d-flex align-items-center justify-content-between"
          >
            <h4 class="mb-0" v-if="isDeliverMode">
              {{ $trans("Items on Requisition list") }}
            </h4>
            <h4 class="mb-0" v-else>{{ $trans("Items on transfer list") }}</h4>

            <div class="page-title-right" v-if="!isDeliverMode">
              <div class="w-100 my-3">
                <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-end px-0" style="width: 60px">№</th>
                  <th>{{ $trans("Product Name") }}</th>
                  <th>{{ $trans("Mesure") }}</th>
                  <th>{{ $trans("Qty. In") }}</th>
                  <th class="required">{{ $trans("Quantity") }}</th>
                  <th class="required">{{ $trans("Price") }}</th>
                  <th>{{ $trans("Total Amount") }}</th>
                  <th style="width: 30px" v-if="!isDeliverMode"></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">{{ item.name }}</span>
                  </td>
                  <td class="text-left align-middle">
                    <span class="fw-bolder">{{ item.unit }}</span>
                  </td>
                  <td class="text-left align-middle">
                    <span class="fw-bolder">{{ item.available_qty }}</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"
                          :class="{
                            'is-invalid': Object.keys(invalidInputs).includes(
                              'Quantity' + i
                            ),
                          }"
                          placeholder="Qty"
                          :name="'Quantity' + i"
                          @keyup="calculateItemAmount(i)"
                          @input="
                            handleValidation($event, {
                              rules: number()
                                .required()
                                .min(1)
                                .max(
                                  item.available_qty,
                                  `Quantity must be less than or equal to ${item.available_qty}`
                                ),
                            })
                          "
                        />
                      </div>
                      <span
                        class="invalid-feedback d-block"
                        style="font-size: 60%"
                        v-if="
                          Object.keys(invalidInputs).includes('Quantity' + i)
                        "
                      >
                        {{ invalidInputs["Quantity" + i][0] }}
                      </span>
                    </div>
                  </td>
                  <td>
                    <div class="sheet-field">
                      <div class="currency-with-amount">
                        <div class="currency-field">FBU</div>
                        <input
                          type="number"
                          v-model="items[i].price"
                          class="form-control"
                          placeholder="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"
                          placeholder="Total Amount"
                        />
                      </div>
                    </div>
                  </td>
                  <td class="text-center align-middle" v-if="!isDeliverMode">
                    <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>
              </tbody>
            </table>
            <div class="text-end" v-if="totalAmount">
              <span class="h4"
                >FBU {{ $helper.formatNumber(totalAmount) }}</span
              >
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <hr />
  <div
    class="border-top shadow w-100 fixed-bottom p-4 main-content bg-primary d-flex align-items-center"
    style="z-index: 999"
  >
    <LoadingButton
      @clicked="handleSubmit"
      class="btn btn-lg btn-light"
      type="button"
      task="TRANSFERING_ITEMS"
      :disabled="submitDisabled"
    >
      <template #caption>{{ $trans("Save") }}</template>
    </LoadingButton>
    <a
      href="/reports/requisitions"
      class="btn btn-danger btn-lg ms-2"
      type="button"
    >
      {{ $trans("Cancel") }}
    </a>
    <div class="text-danger ms-3" v-if="hasUnavailableItems">
      <span>
        {{
          $trans(
            "Transfer is disabled. Some items on the list are not available in stock"
          )
        }}
      </span>
    </div>
  </div>
  <BulkItemsSelect
    @closed="toggleBulkModal"
    @confirmed="getBulkAddedItems"
    v-if="modalOpen"
    fetch-url="stock/products/search?with_quantity=1"
  />
</template>
