<template>
  <v-container>
    <!-- <v-snackbar color="primary" v-model="snackbar" top>
      {{$t("Client.DeleteMessage")}}
      <v-btn color="pink" @click="deleteClient">{{$t("Client.YesBtn")}}</v-btn>
      <v-btn color="pink" @click="snackbar = false">{{$t("Client.NoBtn")}}</v-btn>
    </v-snackbar>
    <v-snackbar color="primary" v-model="alertSnackbar" :timeout="2000">{{alertText}}</v-snackbar>-->

    <v-row justify="center" dense class="flex-wrap mb-6">
      <v-col md="7" lg="6" cols="12">
        <v-card tile>
          <v-card-actions>
            <v-row style="margin:auto" class="justify-center align-center flex-wrap">
              <v-col cols="6">
                <v-autocomplete
                  :items="itemsOfHISLinks"
                  :label="$t('RegisterRoute.HISLinkCombo')"
                  v-model="selectedBrand"
                  item-text="Name"
                  item-value="Brand"
                ></v-autocomplete>
              </v-col>
            </v-row>
          </v-card-actions>
        </v-card>
      </v-col>
    </v-row>
    <v-row justify="center" dense class="flex-wrap mt-6">
      <v-col md="9" cols="12">
        <v-card class="justify-center">
          <v-progress-linear
            :active="HisWorklistLoading"
            :indeterminate="HisWorklistLoading"
            absolute
            top
            color="cyan lighten-2"
          ></v-progress-linear>
          <v-card-title>
            <strong>{{worklist4hislink.length}}/{{count}}</strong>
            <v-spacer></v-spacer>
            <v-text-field
              v-model="search"
              append-icon="search"
              :label="$t('DataTableSearch')"
              single-line
              hide-details
              style="width:400px"
              class="flex-grow-0"
            ></v-text-field>
          </v-card-title>
          <v-data-table
            ref="patientsDatatable"
            :headers="headerOfTable"
            :items="itemsOfTable"
            item-key="_id"
            class="elevation-1"
            style="width:100%"
            fixed-header
            disable-sort
            :height="tableHeight"
            disable-pagination
            hide-default-footer
            :search="search"
          ></v-data-table>
          <v-btn v-if="showMore" class="primary" tile block @click="loadMoreFn">{{$t("RegisterRoute.ShowMoreBtn")}}</v-btn>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>
<script>
import HisLink from "../../imports/api/collections/hislink.js";
import { Meteor } from "meteor/meteor";
import BrandCollections from "../../imports/api/collections/worklist4hislink.js";
import { Mongo } from "meteor/mongo";
import { Counts } from "meteor/tmeasday:publish-counts";
export default {
  data() {
    return {
      search: "",
      selectedBrand: null,
      HisWorklistLoading: false,
      limit: 5,
      prevLeft: 0,
      showMore: false,
      tableHeight: "62vh",
      count: 0
    };
  },
  computed: {
    itemsOfHISLinks() {
      if (this.hislink && this.hislink.length > 0) {
        return this.hislink;
      }
      return [];
    },
    itemsOfTable() {
      if (this.worklist4hislink && this.worklist4hislink.length > 0) {
        let worklistArray = [];
        for (let worklist of this.worklist4hislink) {
          let tempWorklist = {};
          for (let prop in worklist) {
            tempWorklist[prop] = JSON.stringify(worklist[prop]);
          }
          worklistArray.push(tempWorklist);
        }
        return worklistArray;
      }
      return [];
    },
    headerOfTable() {
      if (this.worklist4hislink && this.worklist4hislink.length > 0) {
        let headerNames = [];
        let worklist = this.worklist4hislink[0];
        for (let prop in worklist) {
          headerNames.push({
            text: prop,
            value: prop,
            class: "text-center",
            width: 180
          });
        }
        return headerNames;
      }
      return [];
    }
  },
  created() {
    if (this.$route.params.selectedBrand)
      this.selectedBrand = this.$route.params.selectedBrand;
  },
  methods: {
    onScroll(e) {
      let currentLeft = e.target.scrollLeft;
      if (this.prevLeft != currentLeft) {
        this.prevLeft = currentLeft;
        return;
      }

      let element = this.$refs.patientsDatatable.$el.querySelector(
        ".v-data-table__wrapper"
      );
      let scrollHeight = element.scrollHeight;
      let divHeight = element.clientHeight;
      let scrollerEndPoint = scrollHeight - divHeight;
      let divScrollerTop = e.target.scrollTop;
      if (divScrollerTop === scrollerEndPoint) {
        this.count = Counts.get("brandCount");
        if (this.worklist4hislink.length < this.count) {
          this.limit += 5;
        }
      }
    },
    loadMoreFn() {
      this.count = Counts.get("brandCount");
      this.worklist4hislink.length < this.count ? (this.limit += 5) : "";
    },
    checkScrollExistiance() {
      if (this.worklist4hislink && this.worklist4hislink.length > 0) {
        let me = this;
        setTimeout(function() {
          let element = me.$refs.patientsDatatable.$el.querySelector(
            ".v-data-table__wrapper"
          );
          let scrollHeight = element.scrollHeight;
          let divHeight = element.clientHeight;

          if (divHeight >= scrollHeight) {
            me.tableHeight = "59vh";
            me.showMore = true;
          } else {
            me.tableHeight = "62vh";
            me.showMore = false;
          }
        }, 500);
      }
    }
  },
  watch: {
    "$subReady.worklist4hislink"(ready) {
      this.HisWorklistLoading = false;
      if (this.$refs.patientsDatatable) {
        this.$refs.patientsDatatable.$el
          .querySelector(".v-data-table__wrapper")
          .removeEventListener("scroll", this.onScroll);
        this.$refs.patientsDatatable.$el
          .querySelector(".v-data-table__wrapper")
          .addEventListener("scroll", this.onScroll);
        this.checkScrollExistiance();
      }
    }
  },
  meteor: {
    $subscribe: {
      hislink: [],

      worklist4hislink: function() {
        this.HisWorklistLoading = true;
        return [{ brand: this.selectedBrand, limit: this.limit }];
      }
    },
    hislink() {
      return HisLink.find({}).fetch();
    },
    worklist4hislink() {
      if (this.selectedBrand == null) return [];
      this.count = Counts.get("brandCount");
      if (BrandCollections[this.selectedBrand])
        return BrandCollections[this.selectedBrand].find({}).fetch();
      else {
        BrandCollections[this.selectedBrand] = new Mongo.Collection(
          this.selectedBrand
        );
        return BrandCollections[this.selectedBrand].find({}).fetch();
      }
    }
  }
};
</script>
<style scoped>
</style>