<template>
  <section id="contact2">
    <div class="container">
      <div class="section-header">
        <h1>Property Admin</h1>
      </div>
      <div class="row">
        <div class="col-lg-6 offset-3">
          <input class="form-control uniSelect" type="text" placeholder="SEARCH" v-model="filter" />
        </div>
      </div>
      <div class="row">
        <br />
      </div>
      <div class="row">
        <div class="col-lg-12">
          <table class="table table-striped table-responsive">
            <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.owner }}</td>
                <td>{{ item.agent }}</td>
                <td>{{ item.resort.resortName }}</td>
                <td>{{ item.weekNumber }}</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.weekStatus }}</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",
      displayColumns: [
        "Owner",
        "Agent",
        "Resort",
        "Week Module",
        "Unit",
        "Beds",
        "Season",
        "Region",
        "Amount",
        "Submitted",
        "Status"
      ],
      columns: [
        "owner",
        "agent",
        "resort",
        "weekNumber",
        "unitNumber",
        "bedrooms",
        "season",
        "region",
        "sellPrice",
        "weekStatus"
      ]
    };
  },
  methods: {
    ...mapActions("myWeeks", ["getAllItems"]),
    ...mapActions("myWeeks", ["getItems", "verifyWeek", "editSave"]),
    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.owner = {
        name: item.owner
      };
      item.agent = {
        name: item.agent
      };
      console.log(JSON.stringify(item));
      this.editSave(item);
    },
    Unpublish(item) {
      item.publish = false;
      item.owner = {
        name: item.owner
      };
      item.agent = {
        name: item.agent
      };
      console.log(item);
      this.editSave(item);
    },
    Edit(item) {
      this.$router.push({ name: "EditTimeshare", params: { weekParam: item } });
      // this.$router.push(`/editTimeShare/${item.id}`);
    },
    Delete(item) {
      this.deleteProperty(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"]),
    ...mapGetters({ getNeedsVerify: "myWeeks/getNeedsVerify" }),
    FilteredListings() {
      if (this.filter) {
        const list = _.filter(this.getNeedsVerify, item =>
          Object.values(item).some(
            i =>
              JSON.stringify(i)
                .toLowerCase()
                .indexOf(this.filter.toLowerCase()) > -1
          )
        );
        return _.orderBy(list, this.sortKey, this.SortDirection);
      } else {
        return _.orderBy(this.getNeedsVerify, this.sortKey, this.SortDirection);
      }
    },
    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() {
    // 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>
