<template>
  <div>
    <!-- Header -->
    <div
      class="flex bg-white p-4 text-lg border-b border-gray-300 h-20 items-center"
    >
      <div class="block text-base text-gray-700 font-semibold max-w-2xl">
        {{ text }}
      </div>
      <div class="flex-1 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="addToLine"
          :disabled="selectedItems.length === 0"
          >{{ trans('Add to line') }}</a-button
        >
        <!-- <a-button
          @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-popover placement="leftTop" trigger="click">
          <template slot="content">
            <a-checkbox-group :value="showColumns" @change="onCheckboxChange">
              <div v-for="column in columns" :key="column.key">
                <a-checkbox :value="column.key" class="block ml-0">{{
                  column.title
                }}</a-checkbox>
              </div>
            </a-checkbox-group>
          </template>
          <template slot="title">
            <span>{{ trans('Hide show columns') }}</span>
          </template>
          <a-button type="primary" ghost icon="filter"></a-button>
        </a-popover>
        <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-3/12">
        <a-input v-model="filter.title" :placeholder="trans('Title')" allow-clear />
      </div> -->
      <div class="w-2/12">
        <a-select
          v-model="filter.category"
          :placeholder="trans('Category')"
          class="w-full"
          allow-clear
          show-search
        >
          <a-select-option
            v-for="category in categories"
            :key="category.id"
            :value="category.id"
            >{{ category.title[$page.props.locale || 'tm'] }}</a-select-option
          >
        </a-select>
      </div>
      <div class="w-36">
        <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-36">
        <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 class="w-36">
        <a-select
          v-model="filter.payment"
          :placeholder="trans('Payment')"
          class="w-full"
          allow-clear
          show-search
        >
          <a-select-option
            v-for="payment in payments"
            :key="payment"
            :value="payment"
            >{{ payment }}</a-select-option
          >
        </a-select>
      </div>
      <div class="w-36">
        <a-select
          v-model="filter.send"
          :placeholder="trans('Send')"
          class="w-full"
          allow-clear
          show-search
        >
          <a-select-option v-for="send in sends" :key="send" :value="send">{{
            send
          }}</a-select-option>
        </a-select>
      </div>
      <div class="w-36">
        <a-select
          v-model="filter.type"
          :placeholder="trans('Type')"
          class="w-full"
          allow-clear
          show-search
        >
          <a-select-option value="internal">{{ trans('Internal') }}</a-select-option>
          <a-select-option value="external">{{ trans('External') }}</a-select-option>
        </a-select>
      </div>
    </div>
    <!-- Table -->
    <a-table
      class="table w-full"
      :dataSource="showOnlySelected ? selectedItems : items"
      :columns="visibleColumns"
      :pagination="false"
      :customRow="
        (record) => {
          let self = this;
          return {
            on: {
              click: (event) => onRowClick(event, record),
            },
          };
        }
      "
      rowKey="id"
    >
      <span
        slot="id"
        slot-scope="_, __, index"
        class="text-right"
        v-text="index + 1"
      />
      <!-- <span slot="checkbox" slot-scope="_, row">
        <a-checkbox
          @click.prevent.native
          :checked="selectedRowKeys.includes(row.id)"
        ></a-checkbox>
      </span> -->
      <span slot="category" slot-scope="category">
        <span>{{ category && category.title[$page.props.locale || 'tm'] }}</span>
      </span>
      <span slot="price" slot-scope="price, row" class="whitespace-nowrap">
        {{ price }} {{ row.currency }}
      </span>
      <span slot="amount" slot-scope="amount, row" class="whitespace-nowrap">
        {{ amount }} {{ row.unit }}
      </span>
    </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="exports"
      :group="group && group.id"
      @close="importModalVisible = false"
    />
    <!-- <create-request-modal
      v-if="createRequestVisible"
      :selected-items="selectedItems"
      @close="createRequestVisible = false"
    /> -->
  </div>
</template>

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

export default {
  props: [
    "text",
    "exports",
    "categories",
    "groups",
    "units",
    "currencies",
    "payments",
    "sends",
    "filters",
  ],

  components: { ImportModal, CreateRequestModal, InfiniteLoading },

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

  data() {
    this.loadMore = _.debounce(this.loadMore, 300);
    const showColumns = localStorage.getItem("export-columns")
      ? JSON.parse(localStorage.getItem("export-columns"))
      : columns.filter((col) => col.visible).map((col) => col.key);

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

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

    showColumns(value) {
      localStorage.setItem("export-columns", JSON.stringify(value));
    },
  },

  computed: {
    itemsFiltered() {
      return this.items.filter(
        (item) => !this.selectedRowKeys.includes(item.id)
      );
    },

    visibleColumns() {
      return [
        // {
        //   key: "checkbox",
        //   scopedSlots: {
        //     customRender: "checkbox",
        //   },
        //   align: "right",
        //   width: 40,
        // },
        ...this.columns.filter((col) => this.showColumns.includes(col.key)),
      ];
    },

    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("exports"), 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]);
    },

    onCheckboxChange(value) {
      this.showColumns = [...value];
    },

    addToLine() {
      this.$inertia.post(
        this.route("lines.store"),
        {
          ids: this.selectedRowKeys,
        },
        {
          onSuccess: (response) => {
            this.$message.success("Lines added");
          },
        }
      );
    },

    loadMore($state) {
      this.$inertia.get(
        this.route("exports"),
        {
          ...this.filter,
          page: this.page + 1,
          per_page: this.perPage,
        },
        {
          only: ["exports"],
          preserveState: true,
          preserveScroll: true,
          onSuccess: (response) => {
            if (response.props.exports.data.length) {
              this.items = this.items.concat(response.props.exports.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>
