<script>
import BulkItemsSelect from "./BulkItemsSelect.vue";
// import ZohoSearch from "@/components/ZohoSearch.vue";
import LoadingButton from "@/components/LoadingButton.vue";
export default {
  name: "Adjustments",
  components: { BulkItemsSelect, LoadingButton },
  data: () => ({
    items: [],
    modalOpen: false,
    newAdjustment: {
      adjustment_date: new Date().toLocaleString("fr-CA", {}).slice(0, 10),
      quantity: 0,
    },
    row: {},
    itemsSourceUrl: "stock/products/search",
    selectedDepartment: null,
  }),
  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"
      );
    },
    submitDisabled() {
      return (
        !this.newAdjustment.adjustment_date ||
        !this.newAdjustment.reason ||
        !this.items.length ||
        this.items.some((item) => item.quantity < 0 || !item.adjusted)
      );
    },
  },
  mounted() {
    if (this.isEditingMode) {
      this.$http
        .get(`stock/adjustments/show/${this.$route.params.reference}/items`)
        .then((response) => {
          if (response.data.status) {
            this.row = response.data.row;
            this.newAdjustment.reason = this.row.reason;
            this.newAdjustment.description = this.row.description;
            this.newAdjustment.department_id = this.row.department_id;
            this.newAdjustment.adjustment_date = new Date(
              this.row.adjustment_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,
                alreadyExist: true,
                rowId: item.id,
              });
            });
          }
        });
    }
  },
  methods: {
    handleItemRemove(i) {
      this.items.splice(i, 1);
    },
    getDepartmentItems(department) {
      if (department) {
        this.items = [];
        this.selectedDepartment = department;
        this.itemsSourceUrl = `stock/products/search?department=${department.id}`;
      }
    },
    findQtyAdjusted(item) {
      item.adjusted = -(Number(item.current_qty) - Number(item.quantity));
    },
    findQtyInHands(item) {
      item.quantity = Number(item.current_qty) + Number(item.adjusted);
    },
    getBulkAddedItems(items) {
      this.toggleBulkModal();
      items.forEach((item) => {
        if (!this.addedItems.includes(item.id)) {
          this.items.push({
            id: item.id,
            name: item.name,
            unit: item.unit,
            quantity: item.quantity,
            adjusted: 0,
            current_qty: item.quantity,
          });
        }
      });
    },
    toggleBulkModal() {
      this.modalOpen = !this.modalOpen;
    },
    handleSubmit() {
      this.newAdjustment.items = this.items;
      if (!this.$helper.empty(this.row)) {
        this.newAdjustment.adjustment_id = this.row.id;
      }
      this.$http
        .post(
          "stock/adjustments/store",
          this.$helper.generateFormData(this.newAdjustment)
        )
        .then((response) => {
          if (response.data.status) {
            this.newAdjustment = {};
            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">{{ $trans("Record New Stock Adjustment") }}</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="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="newAdjustment.adjustment_date"
                  />
                </div>
              </div>
              <!-- <div class="mb-3 row">
                <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="newAdjustment.department_id"
                    @selected="getDepartmentItems"
                    style="z-index: 999"
                  ></ZohoSearch>
                  <div class="mt-2" v-if="selectedDepartment">
                    <div
                      class="alert alert-info alert-outline alert-dismissible fade show"
                      role="alert"
                    >
                      <i
                        class="uil uil-exclamation-triangle font-size-20 text-info me-2"
                      ></i>
                      {{ $trans("New Adjusted quantities will be assigned to") }}
                      <strong>{{ selectedDepartment.name }}</strong> {{ $trans(department) }}
                      <button
                        type="button"
                        class="btn-close"
                        data-bs-dismiss="alert"
                        aria-label="Close"
                      ></button>
                    </div>
                  </div>
                </div>
              </div> -->
              <div class="mb-1 row">
                <label class="col-md-4 col-form-label required">{{
                  $trans("Reason")
                }}</label>
                <div class="col-md-8">
                  <input
                    class="form-control"
                    type="text"
                    placeholder="Reason"
                    v-model="newAdjustment.reason"
                  />
                </div>
              </div>
              <div class="mb-1 row">
                <label class="col-md-4 col-form-label">{{
                  $trans("Descriptions")
                }}</label>
                <div class="col-md-8">
                  <textarea
                    v-model="newAdjustment.description"
                    class="form-control"
                    placeholder="Max. 500 characters"
                  ></textarea>
                </div>
              </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 adjustment 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 class="required">{{ $trans("System Qty") }}</th>
                  <th class="required">{{ $trans("Physical Qty") }}</th>
                  <th class="required">
                    {{ $trans("Adjusted Qty") }}
                    <span class="font-size-10">(<em>+10, -10</em>)</span>
                  </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>
                    {{ $helper.formatNumber(item.current_qty) }}
                  </td>
                  <td>
                    <input
                      type="number"
                      v-model="items[i].quantity"
                      class="form-control sheet-field"
                      placeholder="Qty"
                      @input="findQtyAdjusted(item)"
                    />
                  </td>
                  <td>
                    <input
                      type="number"
                      v-model="items[i].adjusted"
                      class="form-control sheet-field"
                      placeholder="Eg. +10, -10"
                      readonly
                      @input="findQtyInHands(item)"
                    />
                  </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>
              </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="ADJUSTING_ITEMS"
      :disabled="submitDisabled"
    >
      <template #caption>{{ $trans("Confirm Save") }}</template>
    </LoadingButton>
    <button class="btn btn-light ms-2" type="button">
      {{ $trans("Cancel") }}
    </button>
  </div>
  <BulkItemsSelect
    @closed="toggleBulkModal"
    @confirmed="getBulkAddedItems"
    v-if="modalOpen"
    :fetch-url="itemsSourceUrl"
    :increment-quantity="false"
  />
</template>
