<template>
  <section id="contact2">
    <div class="container">
      <div class="section-header">
        <h1>Property Admin</h1>
      </div>
      <div class="row">
        <div class="col-lg-4"></div>
        <div class="col-lg-4">
          <input
            @input="updateLazyFilter"
            class="form-control uniSelect"
            type="text"
            placeholder="SEARCH"
            v-model="filter"
          />
        </div>
        <div class="col-lg-4">
          <select
            @change="downloadExcelSheet"
            name="downloadType"
            class="form-control uniSelect"
            v-model="selectedExcelDownload"
            id=""
          >
            <option value="">Select Download Option</option>
            <option value="displayItems">
              <download-excel
                ref="dlDisplay"
                :data="DisplayItems"
                :fields="excelFields"
                worksheet="Timeshare Listings"
                name="Uni-Vate Timeshare.xls"
              >
                Download Display Items
              </download-excel>
            </option>
            <option value="allPublished">
              <download-excel
                ref="dlPublished"
                :data="OnlyPublished"
                :fields="excelFields"
                worksheet="Timeshare Listings"
                name="Uni-Vate Timeshare.xls"
              >
                Download Published Items
              </download-excel>
            </option>
            <option value="allItems">
              <download-excel
                ref="dlAll"
                :data="AllListingsSortedById"
                :fields="excelFields"
                worksheet="Timeshare Listings"
                name="Uni-Vate Timeshare.xls"
              >
                Download All
              </download-excel>
            </option>
          </select>
        </div>
      </div>
      <div class="row">
        <br />
      </div>
    </div>
    <!-- <div class="row">
      <div class="col">
        {{ DisplayItems[0] }}
      </div>
    </div>
    <div class="row">
      <div class="col">
        <download-excel
          :data="DisplayItems"
          :fields="excelFields"
          worksheet="Timeshare Listings"
          name="Uni-Vate Timeshare.xls"
        >
          Download Excel
        </download-excel>
      </div>
    </div> -->
    <div class="container-fluid">
      <div class="row justify-content-center">
        <div class="col-auto">
          <table class="table table-striped table-responsive" style="max-width:1920px">
            <thead>
              <tr>
                <th scope="col" v-for="(col, c) in displayColumns" :key="c">
                  <div @click="sortBy(columns[c])" style="cursor: pointer">
                    <div class="d-flex bd-highlight">
                      <div class="w-100 bd-highlight">{{ col }}</div>
                      <div class="flex-shrink-1 bd-highlight">
                        <img
                          src="../../../../public/img/sort-up.png"
                          height="8px;"
                          v-if="sortKey === columns[c] && reverse"
                        />
                        <img
                          src="../../../../public/img/sort-down.png"
                          height="8px;"
                          v-if="sortKey === columns[c] && !reverse"
                        />
                      </div>
                    </div>
                  </div>
                </th>
                <!-- <th scope="col">Property</th>
                <th scope="col">Unit</th>
                <th scope="col">Size</th>
                <th scope="col">Price Ex VAT</th>
                <th scope="col">Region</th>
                <th scope="col">Town</th>
                <th scope="col">Suburb</th>
                <th scope="col">Status</th>
                <th scope="col">Type</th>-->
                <th scope="col">Publish</th>
                <th scope="col">Edit</th>
                <th scope="col">Delete</th>
              </tr>
            </thead>

            <tbody>
              <tr v-for="(item, i) in DisplayItems" :key="i">
                <td>#{{ item.id }}</td>
                <td>{{ item.owner }}</td>
                <td>{{ item.agent }}</td>
                <td>{{ item.resort.resortName }}</td>
                <td>{{ item.module }}</td>
                <td>{{ item.unitNumber }}</td>
                <td>{{ item.bedrooms }}</td>
                <td>{{ item.season }}</td>
                <td>{{ item.region.regionName }}</td>
                <td>{{ item.sellPrice | toCurrency }}</td>
                <td>{{ item.pulbishedDate | toDate }}</td>
                <td>{{ item.status.description }}</td>
                <td v-if="!item.publish">
                  <a v-on:click="Publish(item)">
                    <img src="../../../../public/img/icons/Upload.png" height="25" width="25" />
                  </a>
                </td>
                <td v-else>
                  <a v-on:click="Unpublish(item)">
                    <img
                      src="../../../../public/img/icons/Download-grey.png"
                      height="25"
                      width="25"
                    />
                  </a>
                </td>
                <td>
                  <a v-on:click="Edit(item)">
                    <img src="../../../../public/img/icons/Edit.png" height="25" width="25" />
                  </a>
                </td>
                <td>
                  <a v-on:click="Delete(item)">
                    <img src="../../../../public/img/icons/delete.png" height="25" width="25" />
                  </a>
                </td>
              </tr>
            </tbody>
          </table>
          <div class="d-flex justify-content-between" v-if="showPager">
            <div class="p-1">
              {{ currentPage + " / " + PageCount + (" - (" + FilteredListings.length + " items)") }}
            </div>
            <div class="p-1">
              <BasePagination
                :currentPage="currentPage"
                :pageCount="PageCount"
                @nextPage="pageChangeHandle('next')"
                @previousPage="pageChangeHandle('previous')"
                @loadPage="pageChangeHandle"
              />
            </div>
            <div class="p-2">
              <div class="d-flex flex-row">
                <div>
                  <select
                    class="form-control uniSelect"
                    v-model="visibleItemsPerPageCount"
                    @change="onChangeItemsPerPage()"
                  >
                    <option v-for="(item, i) in itemsPerPageList" :key="i">
                      {{ item }}
                    </option>
                  </select>
                </div>
              </div>
            </div>
          </div>
          <div class="p-2">
            <div class="d-flex flex-row">
              <div>
                <button v-if="sortKey !== 'id'" class="btn-solid-blue" @click="ClearSort">
                  Clear Sort
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="wait" id="preloader"></div>
    </div>
  </section>
</template>

<script>
/* eslint-disable */
import { mapState, mapActions, mapGetters } from "vuex";
import Log from "../../../assets/Log";
import BasePagination from "../../shared/basePagination";
import ItemsPerPageList from "../../../assets/staticData/itemsPerPageFive";
import _ from "lodash";

export default {
  components: {
    BasePagination
  },
  data() {
    return {
      hover: -1,
      filter: undefined,
      userId: Log.getUser().id,
      wait: true,
      showPager: true,
      visibleItemsPerPageCount: 10,
      itemsPerPageList: ItemsPerPageList,
      currentPage: 1,
      reverse: true,
      sortKey: "id",
      selectedExcelDownload: "",
      excelFields: {
        Ref: "id",
        Owner: "owner",
        agent: "Agent",
        Resort: "resort.resortName",
        Module: "module",
        Unit: "unitNumber",
        Beds: "bedrooms",
        MaxSleep: "maxSleep",
        Season: "season",
        Region: "region.regionName",
        Amount: {
          field: "sellPrice",
          callback: value => {
            return "R " + value;
          }
        },
        Levy: {
          field: "levyAmount",
          callback: value => {
            return "R " + value;
          }
        },
        ArrivalDate: {
          field: "arrivalDate",
          callback: value => {
            return value.substring(0, 10);
          }
        },
        DepartureDate: {
          field: "departureDate",
          callback: value => {
            return value.substring(0, 10);
          }
        },
        Submitted: {
          field: "pulbishedDate",
          callback: value => {
            return value.substring(0, 10);
          }
        },
        Status: "status.description"
      },
      displayColumns: [
        "Ref",
        "Owner",
        "Agent",
        "Resort",
        "Week Module",
        "Unit",
        "Beds",
        "Season",
        "Region",
        "Amount",
        "Submitted",
        "Status"
      ],
      columns: [
        "id",
        "owner",
        "agent",
        "resort",
        "module",
        "unitNumber",
        "bedrooms",
        "season",
        "region",
        "sellPrice",
        "weekStatus"
      ]
    };
  },
  methods: {
    ...mapActions("myWeeks", ["getAllItems"]),
    ...mapActions("timeshare", ["updateFilter"]),
    ...mapActions("myWeeks", [
      "getItems",
      "verifyWeek",
      "editSave",
      "publishWeek",
      "unpublishWeek",
      "deleteListing"
    ]),
    updateLazyFilter() {
      this.updateFilter(this.filter);
    },
    downloadExcelSheet() {
      if (this.selectedExcelDownload == "displayItems") {
        const elem = this.$refs.dlDisplay;
        elem.$el.click();
      } else if (this.selectedExcelDownload == "allPublished") {
        const elem = this.$refs.dlPublished;
        elem.$el.click();
      } else if (this.selectedExcelDownload == "allItems") {
        const elem = this.$refs.dlAll;
        elem.$el.click();
      }
    },
    Publish(item) {
      var today = new Date();
      var dd = String(today.getDate()).padStart(2, "0");
      var mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
      var yyyy = today.getFullYear();
      item.pulbishedDate = today.toISOString().substring(0, 19);
      item.publish = true;
      // item.status.id = 26;
      // item.status.code = "FS";
      // item.status.description = "For Sale";
      // item.status.statusType = true;
      // console.log(JSON.stringify(item));
      // this.publishOnly(item);
      this.publishWeek(item);
    },
    Unpublish(item) {
      this.unpublishWeek(item);
    },
    Edit(item) {
      this.$router.push({ name: "EditTimeshare", params: { weekParam: item } });
      // this.$router.push(`/editTimeShare/${item.id}`);
    },
    Delete(item) {
      this.deleteListing(item.id);
    },
    async pageChangeHandle(value) {
      switch (value) {
        case "next":
          this.currentPage += 1;
          break;
        case "previous":
          this.currentPage -= 1;
          break;
        default:
          this.currentPage = value;
      }
    },
    sortBy(sortKey) {
      this.reverse = this.sortKey === sortKey ? !this.reverse : false;
      this.sortKey = sortKey;
    },
    ClearSort() {
      this.reverse = true;
      this.sortKey = "id";
    }
  },
  computed: {
    ...mapState("propertyList", ["properties"]),
    ...mapState("timeshare", ["timeshareFilter"]),
    ...mapGetters({ getNeedsVerify: "myWeeks/getNeedsVerify" }),
    FilteredListings() {
      if (this.timeshareFilter) {
        const list = _.filter(this.getNeedsVerify, item =>
          Object.values(item).some(
            i =>
              JSON.stringify(i)
                .toLowerCase()
                .indexOf(this.timeshareFilter.toLowerCase()) > -1
          )
        );
        return _.orderBy(list, this.sortKey, this.SortDirection);
      } else {
        return _.orderBy(this.getNeedsVerify, this.sortKey, this.SortDirection);
      }
    },
    AllListingsSortedById() {
      return _.orderBy(this.getNeedsVerify, "id", "desc");
    },
    OnlyPublished() {
      var list = [];
      this.FilteredListings.forEach(listing => {
        if (listing.publish) {
          list.push(listing);
        }
      });
      return list;
    },
    PageCount() {
      return this.visibleItemsPerPageCount !== 0
        ? Math.ceil(this.FilteredListings.length / this.visibleItemsPerPageCount)
        : 1;
    },
    DisplayItems() {
      const list = this.FilteredListings;
      const startSlice = (this.currentPage - 1) * this.visibleItemsPerPageCount;
      let endSlice = this.currentPage * this.visibleItemsPerPageCount;
      if (endSlice > list.length) {
        endSlice = list.length;
      }
      return list.slice(startSlice, endSlice);
    },
    SortDirection() {
      return this.reverse ? "desc" : "asc";
    }
  },
  created() {
    this.getItems(this.userId).then(() => {
      this.wait = false;
    });
  },
  mounted() {
    if (this.timeshareFilter !== "") {
      this.filter = this.timeshareFilter;
    }
    // this.getAdminProperties(this.userId).then(fulfuilled => {
    //   this.wait = false;
    //   if (this.itemsPerPageList && this.itemsPerPageList.length > 0) {
    //     const [startItem] = this.itemsPerPageList;
    //     this.visibleItemsPerPageCount = startItem;
    //   }
    // });
  },
  watch: {
    filter: {
      immediate: true,
      handler(val, oldVal) {
        if (val != oldVal) {
          this.currentPage = 1;
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.refbyAgent {
  will-change: transform;
  transition: height 500ms;
  height: 0px;
}

.refbyAgent--clicked {
  height: 150px;
}

.spacebanked1 {
  will-change: transform;
  transition: height 500ms;
  height: 0px;
}

.spacebanked1--clicked {
  height: 150px;
}

.custom-file-label {
  border-width: 2px;
  border-color: rgb(27, 117, 187);
  margin-bottom: 20px;
}

.custom-file-label::after {
  border-left: none;
  border-bottom: solid;
  border-width: 2px;
  border-color: rgb(27, 117, 187);
  font-family: "Muli";
}
</style>
