<template>
  <section id="contact2">
    <div class="container">
      <div class="section-header">
        <h2>Property Admin</h2>
      </div>
      <div v-if="ROLE === 'Agency'">
        <h6>{{ curAgency }}</h6>
      </div>
      <div v-if="ROLE === 'Agent'">
        <h6>{{ agent[0].name + " " + agent[0].surname }}</h6>
      </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 v-if="wait" id="preloader"></div>
    </div>
    <div class="container-fluid">
      <div class="row justify-content-center">
        <div class="col-auto">
          <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.id }}</td>
                <td>{{ item.owner }}</td>
                <td>{{ item.reference }}</td>
                <td>{{ item.property }}</td>
                <td>{{ item.unit }}</td>
                <td>{{ item.size }}</td>
                <td>{{ item.price | toCurrency }}</td>
                <td>{{ item.region }}</td>
                <td>{{ item.town }}</td>
                <td>{{ item.suburb }}</td>
                <td>{{ item.status }}</td>
                <td>{{ item.type }}</td>
                <td v-if="!item.isPublished">
                  <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 + (" - (" + FilteredProperties.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>
  </section>
</template>

<script>
/* eslint-disable */
import { mapState, mapActions } 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: [
        "ID",
        "Owner",
        "Reference",
        "Property",
        "Unit",
        "Size",
        "Price Ex VAT",
        "Region",
        "Town",
        "Suburb",
        "Status",
        "Type",
        "Publish"
      ],
      columns: [
        "id",
        "owner",
        "reference",
        "property",
        "unit",
        "size",
        "price",
        "region",
        "town",
        "suburb",
        "status",
        "type",
        "isPublished"
      ]
    };
  },
  methods: {
    ...mapActions("propertyList", [
      "getAdminProperties",
      "deleteProperty",
      "publishProperty",
      "unpublishProperty"
    ]),
    ...mapActions("register", ["getAgentById"]),
    ...mapActions("timeshare", ["getAgencies"]),
    Publish(item) {
      this.publishProperty(item);
    },
    Unpublish(item) {
      this.unpublishProperty(item);
    },
    Edit(item) {
      this.$router.push(`/property/edit/${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"]),
    ...mapState("register", ["agent"]),
    ...mapState("timeshare", ["agencies"]),
    FilteredProperties() {
      if (this.filter) {
        const list = _.filter(this.properties, 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.properties, this.sortKey, this.SortDirection);
      }
    },
    PageCount() {
      return this.visibleItemsPerPageCount !== 0
        ? Math.ceil(this.FilteredProperties.length / this.visibleItemsPerPageCount)
        : 1;
    },
    curAgency() {
      var selAgency = "";
      this.agencies.forEach(agency => {
        if (this.agent[0].agencyId === agency.id) {
          selAgency = agency.agencyName;
        }
      });
      return selAgency;
    },
    DisplayItems() {
      const list = this.FilteredProperties;
      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";
    },
    ROLE() {
      return Log.getUser().role;
    }
  },
  created() {
    this.getAgentById(Log.getUser().id);
    this.getAgencies();
  },
  mounted() {
    this.wait = true;
    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>
