<script>
import { tableMixin } from "@/helpers/tables.mixin";
import ZohoSearch from "@/components/ZohoSearch.vue";
import { permissionsHandler } from "@/helpers/permissions-handler";
export default {
  name: "TransferReport",
  mixins: [tableMixin, permissionsHandler],
  components: {
    ZohoSearch,
  },
  data: () => ({
    dataUrl: "stock/reports/transfers",
    items: [],
    offCanvas: null,
    task: "GETTING_TRANSFER_REPORT",
  }),
  computed: {
    isFetchingItems() {
      this.$store.commit("SET_AJAX_TASK", this.task);
      return (
        this.$store.state.isLoading &&
        this.$store.state.loadingTask == this.task
      );
    },
    itemsAmount() {
      return this.items.reduce((a, b) => a + b.price * b.quantity, 0);
    },
    grandTotal() {
      return this.rows.reduce((a, b) => a + b.amount, 0);
    },
  },
  mounted() {
    this.offCanvas = new bootstrap.Offcanvas(
      document.getElementById("itemsOffCanvas")
    );
  },
  methods: {
    handleItemsView(row) {
      this.offCanvas.show();
      if (this.selectedRow.id != row.id) {
        this.selectedRow = row;
        this.items = [];
        this.$store.commit("SET_AJAX_TASK", "GETTING_TRANSFER_ITEMS");
        this.$http
          .get(`stock/inventory/transfers/${row.id}/items`)
          .then((response) => {
            if (response.data.status) {
              this.items = response.data.items;
            }
          });
      }
    },
    handleDestroy(row, i) {
      this.$confirm({
        title: "Deleting",
        content: `Are you sure you want to delete stock transfer of #${this.$helper.padNumber(
          row.id
        )}?`,
        actionText: "Yes, Continue",
        closeText: "Discard",
        classes: "btn btn-danger",
        action: () => {
          this.$http
            .get(`stock/inventory/transfers/${row.id}/destroy`)
            .then((response) => {
              if (response.data.status) {
                this.rows.splice(i, 1);
                this.$notify({
                  type: "success",
                  message: "Record deleted successfully",
                });
              }
            });
        },
      });
    },
    deleteTransferItem(item, index) {
      this.$confirm({
        title: "Deleting",
        content: `Are you sure you want to delete ${item.product.name} from transfer list?`,
        actionText: "Yes, Continue",
        closeText: "Discard",
        classes: "btn btn-danger",
        action: () => {
          this.$http
            .get(
              `stock/inventory/transfers/${this.selectedRow.id}/items/${item.id}/destroy`
            )
            .then((response) => {
              if (response.data.status) {
                let i = this.rows.findIndex(
                  (item) => item.id == this.selectedRow.id
                );
                this.rows[i].total_items -= 1;
                this.rows[i].amount -= item.price * item.quantity;
                this.items.splice(index, 1);
                this.$notify({
                  type: "success",
                  message: "Record deleted successfully",
                });
              }
            });
        },
      });
    },
  },
};
</script>
<template>
  <div
    class="offcanvas offcanvas-end stock-offcanvas"
    tabindex="-1"
    id="itemsOffCanvas"
    aria-labelledby="itemsOffCanvasLabel"
  >
    <template v-if="!$helper.empty(selectedRow)">
      <div class="offcanvas-header">
        <h5 id="itemsOffCanvasLabel">
          {{ `Transfer #${$helper.padNumber(selectedRow.id)}` }}
        </h5>
        <div class="d-flex align-items-center">
          <a
            href="javascript:void(0)"
            class="text-reset"
            @click.prevent="
              handlePrint(
                '#details-table',
                [],
                `Transfer #${$helper.padNumber(selectedRow.id)}`
              )
            "
          >
            <i class="uil uil-print fs-3"></i>
          </a>
          <a
            href="javascript:void(0)"
            class="text-reset"
            @click.prevent="
              handleExcelExport(
                'details-table',
                `Transfer Report-${$helper.padNumber(selectedRow.id)}`
              )
            "
          >
            <svg
              height="20px"
              viewBox="0 0 16 16"
              xmlns="http://www.w3.org/2000/svg"
              fill="currentColor"
            >
              <path
                fill-rule="evenodd"
                d="M2 2a2 2 0 0 1 2-2h5.293A1 1 0 0 1 10 .293L13.707 4a1 1 0 0 1 .293.707V14a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V2zm7.5 1.5v-2l3 3h-2a1 1 0 0 1-1-1zM5.884 6.68a.5.5 0 1 0-.768.64L7.349 10l-2.233 2.68a.5.5 0 0 0 .768.64L8 10.781l2.116 2.54a.5.5 0 0 0 .768-.641L8.651 10l2.233-2.68a.5.5 0 0 0-.768-.64L8 9.219l-2.116-2.54z"
              ></path>
            </svg>
          </a>
          <button
            type="button"
            class="btn-close text-reset"
            data-bs-dismiss="offcanvas"
            aria-label="Close"
          ></button>
        </div>
      </div>
      <div class="offcanvas-body">
        <div
          class="d-flex justify-content-center loader-container"
          v-if="isFetchingItems && !items.length"
        >
          <div class="lds-ellipsis">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
          </div>
        </div>
        <div class="table-responsive" v-else>
          <table
            class="table align-middle table-nowrap table-check"
            id="details-table"
          >
            <thead>
              <th scope="col">№</th>
              <th scope="col">{{ $trans("Product Name") }}</th>
              <th scope="col">{{ $trans("Quantity") }}</th>
              <th scope="col">U. {{ $trans("Price") }}</th>
              <th scope="col">T. {{ $trans("Amount") }}</th>
              <th>{{ $trans("Actions") }}</th>
            </thead>
            <tbody>
              <tr v-for="(item, i) in items" :key="'item' + i">
                <td>{{ i + 1 }}</td>
                <td>{{ item.product.name }}</td>
                <td>
                  <span class="fw-bolder">{{
                    $helper.formatNumber(item.quantity)
                  }}</span>
                  {{ item.product.unit }}
                </td>
                <td>FBU {{ $helper.formatNumber(item.price) }}</td>
                <td>
                  FBU {{ $helper.formatNumber(item.price * item.quantity) }}
                </td>
                <td class="text-nowrap">
                  <a
                    v-if="this.hasPermissionTo('D')"
                    href="javascript:void(0)"
                    class="text-danger"
                    title="Remove Item"
                    @click.prevent="deleteTransferItem(item, i)"
                  >
                    <i class="uil uil-trash fs-5"></i>
                  </a>
                </td>
              </tr>
              <tr v-if="itemsAmount">
                <td colspan="5" class="text-end">
                  <span class="h4"
                    >FBU {{ $helper.formatNumber(itemsAmount) }}</span
                  >
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </template>
  </div>
  <div class="row">
    <div class="col-lg-12">
      <h4 id="reportTitle">{{ $trans("Transfer products report") }}</h4>
      <div class="w-100 justify-content-between d-flex align-items-center my-3">
        <div class="left-toobar d-flex flex-nowrap">
          <div
            class="date-range d-flex align-items-center"
            style="width: 200px"
          >
            <div class="d-flex align-items-center input-wrapper">
              <input
                type="date"
                v-model="dataFilter.from"
                class="form-control"
                @click="displayPicker"
              />
              <span class="input-separator">-</span>
              <input
                type="date"
                v-model="dataFilter.to"
                class="form-control"
                @click="displayPicker"
              />
            </div>
            <div class="icon ms-auto">
              <i class="uil uil-calendar-alt fs-5"></i>
            </div>
          </div>
          <div class="ms-2">
            <ZohoSearch
              placeholder="Select Department"
              url="departments/search"
              label="name"
              :load-defaults="true"
              style="z-index: 999"
              v-model="dataFilter.department"
            ></ZohoSearch>
          </div>
          <button
            class="btn btn-primary ms-2"
            type="button"
            @click="handleDataFilter"
          >
            {{ $trans("Apply") }}
          </button>
          <button
            class="btn btn-outline-primary ms-2"
            @click="resetFilters"
            type="button"
          >
            {{ $trans("Reset") }}
          </button>
        </div>
        <div class="right-toobar d-flex align-items-center flex-nowrap">
          <button
            class="btn-primary btn btn-icon ms-1"
            type="button"
            :disabled="!rows.length"
            @click="handleExcelExport(null)"
          >
            <svg
              height="18px"
              viewBox="0 0 16 16"
              xmlns="http://www.w3.org/2000/svg"
              fill="currentColor"
            >
              <path
                fill-rule="evenodd"
                d="M2 2a2 2 0 0 1 2-2h5.293A1 1 0 0 1 10 .293L13.707 4a1 1 0 0 1 .293.707V14a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V2zm7.5 1.5v-2l3 3h-2a1 1 0 0 1-1-1zM5.884 6.68a.5.5 0 1 0-.768.64L7.349 10l-2.233 2.68a.5.5 0 0 0 .768.64L8 10.781l2.116 2.54a.5.5 0 0 0 .768-.641L8.651 10l2.233-2.68a.5.5 0 0 0-.768-.64L8 9.219l-2.116-2.54z"
              ></path>
            </svg>
          </button>
          <button
            class="btn-dark btn btn-icon ms-1"
            type="button"
            :disabled="!rows.length"
            @click="
              handlePrint('#pagination-table', [], 'Stock Transfer History')
            "
          >
            <svg
              height="18px"
              viewBox="0 0 16 16"
              xmlns="http://www.w3.org/2000/svg"
              fill="currentColor"
            >
              <path
                d="M11 2H5a1 1 0 0 0-1 1v2H3V3a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2h-1V3a1 1 0 0 0-1-1zm3 4H2a1 1 0 0 0-1 1v3a1 1 0 0 0 1 1h1v1H2a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2h-1v-1h1a1 1 0 0 0 1-1V7a1 1 0 0 0-1-1z"
              ></path>
              <path
                fill-rule="evenodd"
                d="M11 9H5a1 1 0 0 0-1 1v3a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1zM5 8a2 2 0 0 0-2 2v3a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H5z"
              ></path>
              <path d="M3 7.5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0z"></path>
            </svg>
          </button>
        </div>
      </div>
      <div class="table-responsive">
        <table
          class="table table-light table-hover table-striped align-middle table-nowrap table-check"
          id="pagination-table"
        >
          <thead>
            <tr>
              <th scope="col">S/N</th>
              <th scope="col">{{ $trans("Date") }}</th>
              <th scope="col">{{ $trans("Department") }}</th>
              <th scope="col">Tot. {{ $trans("products") }}</th>
              <th scope="col">Tot. {{ $trans("Amount") }}</th>
              <th scope="col">{{ $trans("Taken By") }}</th>
              <th scope="col">{{ $trans("Created By") }}</th>
              <th>{{ $trans("Actions") }}</th>
            </tr>
          </thead>
          <div
            class="d-flex  justify-content-center loader-container"
            v-if="isFetchingItems && !rows.length"
          >
            <div class="lds-ellipsis">
              <div></div>
              <div></div>
              <div></div>
              <div></div>
            </div>
          </div>
          <tbody v-else>
            <tr v-for="(row, i) in rows" :key="i">
              <td>#{{ $helper.padNumber(row.id) }}</td>
              <td>{{ $helper.formatDate(row.date_transfered) }}</td>
              <td>
                <a href="javascript:void(0)">{{
                  limitCharacters(row.department.name, 7)
                }}</a>
              </td>
              <td>{{ $helper.formatNumber(row.total_items) }}</td>
              <td>
                FBU
                <b class="alert alert-success">{{
                  $helper.formatNumber(row.amount)
                }}</b>
              </td>
              <td>
                <a href="javascript:void(0)">{{
                  limitCharacters(row.employee.name, 10)
                }}</a>
              </td>
              <td>
                <a href="javascript:void(0)">{{
                  limitCharacters(row.creator.name, 10)
                }}</a>
              </td>
              <td>
                <div class="">
                  <button
                    class="btn btn-light btn-sm dropdown-toggle"
                    type="button"
                    data-bs-toggle="dropdown"
                    aria-expanded="false"
                  >
                    <i class="uil uil-ellipsis-h"></i>
                  </button>
                  <ul class="dropdown-menu dropdown-menu-end">
                    <li>
                      <a
                        class="dropdown-item"
                        @click.prevent="handleItemsView(row)"
                        href="javascript:void(0)"
                        >{{ $trans("View Items") }}</a
                      >
                    </li>
                    <li v-if="this.hasPermissionTo('U')">
                      <RouterLink
                        class="dropdown-item"
                        :to="{
                          name: 'ItemsTransfer',
                          params: {
                            reference: row.reference,
                            action: 'edit',
                          },
                        }"
                        >{{ $trans("Edit") }}</RouterLink
                      >
                    </li>
                    <li v-if="this.hasPermissionTo('D')">
                      <a
                        class="dropdown-item"
                        @click.prevent="handleDestroy(row, i)"
                        href="javascript:void(0)"
                        >{{ $trans("Delete") }}</a
                      >
                    </li>
                  </ul>
                </div>
              </td>
            </tr>
            <tr v-if="grandTotal">
              <td colspan="5" class="text-end">
                {{ $trans("Grand Total") }}:
                <span class="h5 mb-0 fw-bolder"
                  >FBU {{ $helper.formatNumber(grandTotal) }}</span
                >
              </td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
          </tbody>
        </table>
      </div>
      <paginations
        :to="recordsTo"
        :from="recordsFrom"
        :current_page="currentPage"
        :row_count_page="rowCountPage"
        @page-update="handlePagination"
        :total_records="totalRows"
        :page_range="pageRange"
      ></paginations>
    </div>
  </div>
</template>
