<template>
  <div>
    <!-- Header -->
    <div
      class="flex bg-white p-4 text-lg border-b border-gray-300 h-20 items-center"
    >
      <div class="flex-1 font-semibold">{{ trans('Imports') }}</div>
      <div class="flex justify-end items-center space-x-3">
        <div v-show="selectedItems.length">
          <a-checkbox v-model="showOnlySelected">
            <span>{{ trans('Show only selected') }}</span>
          </a-checkbox>
          <div class="text-xs font-semibold text-gray-600 ml-6 -mt-1">
            {{ trans("Items selected", { count: selectedItems.length }) }}
          </div>
        </div>
        <a-button
          v-if="!$page.props.user"
          @click="createRequestVisible = true"
          :disabled="selectedItems.length === 0"
          >{{ trans('Create request') }}</a-button
        >
        <a-button
          v-if="$page.props.user"
          type="primary"
          @click="importModalVisible = true"
          >{{ trans('Upload excel') }}</a-button
        >
        <a-button
          v-if="group && group.file"
          type="primary"
          @click="() => download(group.hashid)"
          >{{ trans('Download excel') }}</a-button
        >
        <a-select
          v-model="filter.group"
          :placeholder="trans('Group')"
          class="w-48"
          show-search
        >
          <a-select-option
            v-for="group in groups"
            :key="group.id"
            :value="group.id"
            >{{ group.title[$page.props.locale || 'tm'] }}</a-select-option
          >
        </a-select>
      </div>
    </div>
    <!-- Filter -->
    <div class="flex space-x-3 p-4">
      <!-- <div class="w-2/12">
        <a-input v-model="filter.title" :placeholder="trans('Title')" allow-clear />
      </div> -->
      <div class="w-2/12">
        <a-select
          v-model="filter.country"
          :placeholder="trans('Country')"
          allow-clear
          show-search
          class="w-full"
        >
          <a-select-option
            v-for="country in countries"
            :key="country"
            :value="country"
            >{{ country }}</a-select-option
          >
        </a-select>
      </div>
      <div class="w-2/12">
        <a-select
          v-model="filter.unit"
          :placeholder="trans('Unit')"
          class="w-full"
          allow-clear
          show-search
        >
          <a-select-option v-for="unit in units" :key="unit" :value="unit">{{
            unit
          }}</a-select-option>
        </a-select>
      </div>
      <div class="w-2/12">
        <a-select
          v-model="filter.currency"
          :placeholder="trans('Currency')"
          class="w-full"
          allow-clear
          show-search
        >
          <a-select-option
            v-for="currency in currencies"
            :key="currency"
            :value="currency"
            >{{ currency }}</a-select-option
          >
        </a-select>
      </div>
    </div>
    <!-- Table -->
    <a-table
      class="table w-full"
      :dataSource="showOnlySelected ? selectedItems : items"
      :columns="columns"
      :pagination="false"
      :customRow="
        (record) => {
          let self = this;
          return {
            on: {
              click: (event) => onRowClick(event, record),
            },
          };
        }
      "
      rowKey="id"
    >
      <span slot="checkbox" slot-scope="_, row">
        <a-checkbox
          @click.prevent.native
          :checked="selectedRowKeys.includes(row.id)"
        ></a-checkbox>
      </span>
      <span
        slot="id"
        slot-scope="_, __, index"
        class="text-right"
        v-text="index + 1"
      />
    </a-table>
    <infinite-loading
      :identifier="infiniteScroll"
      :distance="20"
      spinner="waveDots"
      @infinite="loadMore"
      v-if="!showOnlySelected && items.length >= perPage"
    >
      <div slot="no-more" class="uppercase font-bold text-gray-700 mb-6 py-5">
        {{ trans('All items loaded') }}
      </div>
      <div slot="no-results"></div>
    </infinite-loading>
    <!-- Other -->
    <import-modal
      v-if="importModalVisible"
      action="imports"
      @close="importModalVisible = false"
    />
    <create-request-modal
      v-if="createRequestVisible"
      :selected-items="selectedItems"
      :birzha_user="birzha_user"
      @close="createRequestVisible = false"
    />
  </div>
</template>

<script>
import columns from "@/data/import-columns";
import ImportModal from "@/Components/ImportModal";
import InfiniteLoading from "vue-infinite-loading";
import CreateRequestModal from "@/Components/CreateRequestModal";

export default {
  props: ["imports", "countries", "units", "currencies", "filters", "groups", "birzha_user"],

  components: { ImportModal, CreateRequestModal, InfiniteLoading },

  metaInfo() {
    return {
      title: this.trans('Imports'),
    }
  },

  data() {
    this.loadMore = _.debounce(this.loadMore, 300);

    return {
      page: 1,
      perPage: 50,
      infiniteScroll: +new Date(),
      importModalVisible: false,
      createRequestVisible: false,
      items: this.imports.data,
      selectedRowKeys: [],
      selectedItems: [],
      showOnlySelected: false,
      filter: _.assign(
        {
          title: undefined,
          country: undefined,
          currency: undefined,
          unit: undefined,
          group: undefined,
        },
        this.filters
      ),
    };
  },

  watch: {
    filter: {
      handler(value) {
        this.$inertia.get(this.route("imports"), value, {
          preserveState: true,
          onSuccess: (response) => {
            this.page = 1;
            this.infiniteScroll = +new Date();
            this.items = response.props.imports.data;
          },
        });
      },
      deep: true,
    },
  },

  computed: {
    group() {
      return this.groups.find((group) => group.id === this.filter.group);
    },

    columns() {
      return columns.map((column) => {
        column.title = this.trans(column.title)
        return column
      });
    }
  },

  beforeMount() {
    if (this.$page.url.search('page') !== -1) {
      this.$inertia.get(this.route("imports"), this.filter)
    }
  },

  methods: {
    onSelectChange(selectedRowKeys, selectedRows) {
      const items = _.differenceBy(this.selectedItems, selectedRows, "id");
      this.selectedItems = [...items, ...selectedRows].filter((item) =>
        selectedRowKeys.includes(item.id)
      );

      this.selectedRowKeys = selectedRowKeys;
    },

    onRowClick(_, record) {
      let selected;
      if (this.selectedRowKeys.includes(record.id)) {
        selected = this.selectedRowKeys.filter((key) => key !== record.id);
      } else {
        selected = this.selectedRowKeys.concat(record.id);
      }
      this.onSelectChange(selected, [record]);
    },

    loadMore($state) {
      this.$inertia.get(
        this.route("imports"),
        {
          ...this.filter,
          page: this.page + 1,
          per_page: this.perPage,
        },
        {
          only: ["imports"],
          preserveState: true,
          preserveScroll: true,
          onSuccess: (response) => {
            if (response.props.imports.data.length) {
              this.items = this.items.concat(response.props.imports.data);
              this.page += 1;
              $state.loaded();
            } else {
              $state.complete();
            }
          },
        }
      );
    },
  },
};
</script>


<style scoped>
.table >>> td {
  padding: 12px 8px;
}

.table >>> th:last-child,
.table >>> td:last-child {
  padding-right: 20px;
}

.table >>> th {
  white-space: nowrap;
}
</style>
