<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="error" v-model="alertSnackbar" :timeout="2000">{{alertText}}</v-snackbar>

    <v-row justify="center" align="center" dense class="flex-wrap mb-6">
      <v-col md="3" lg="3" style="height:100%">
        <v-card tile height="100%">
          <v-card-actions>
            <v-row style="margin:auto" class="justify-center align-center flex-wrap">
              <v-col>
                <v-autocomplete
                  :items="itemsOfHISLinks"
                  :label="$t('RegisterRoute.HISLinkCombo')"
                  v-model="selectedBrand"
                  item-text="Name"
                  item-value="Brand"
                  clearable
                ></v-autocomplete>
              </v-col>
              <!-- <v-col cols="6">
                <v-bottom-sheet v-model="sheet" hide-overlay inset>
                  <template v-slot:activator="{ on }">
                    <v-btn color="green" dark v-on="on">Open Persistent</v-btn>
                  </template>
                  <v-sheet height="400px" color="grey lighten-3">
                    <v-container fill-height>
                      <v-row align="center">
                        <v-col xl="3" md="3" sm="12">
                          <v-card class="mx-auto" height="330" tile>
                            <v-content class="pa-4">
                              <strong>Worklist date / time</strong>
                              <v-checkbox
                                v-model="fromCheckbox"
                                value="fromDate"
                                label="Show only worklist items from"
                                type="checkbox"
                                required
                              ></v-checkbox>
                              <v-checkbox
                                v-model="fromCheckbox"
                                value="fromDate"
                                label="Show only worklist items to"
                                type="checkbox"
                                required
                              ></v-checkbox>
                              <v-dialog
                                ref="dateDialog"
                                v-model="modal"
                                :return-value.sync="date"
                                persistent
                                width="290px"
                              >
                                <template v-slot:activator="{ on }">
                                  <v-text-field
                                    v-model="date"
                                    label="Picker in dialog"
                                    prepend-icon="event"
                                    readonly
                                    v-on="on"
                                  ></v-text-field>
                                </template>
                                <v-date-picker v-model="date" scrollable>
                                  <v-spacer></v-spacer>
                                  <v-btn text color="primary" @click="modal = false">Cancel</v-btn>
                                  <v-btn
                                    text
                                    color="primary"
                                    @click="$refs.dateDialog.save(date)"
                                  >OK</v-btn>
                                </v-date-picker>
                              </v-dialog>

                              <v-dialog
                                ref="timeDialog"
                                v-model="timeModal"
                                :return-value.sync="time"
                                persistent
                                width="290px"
                              >
                                <template v-slot:activator="{ on }">
                                  <v-text-field
                                    v-model="time"
                                    label="Picker in dialog"
                                    prepend-icon="access_time"
                                    readonly
                                    v-on="on"
                                  ></v-text-field>
                                </template>
                                <v-time-picker v-if="timeModal" v-model="time" full-width>
                                  <v-spacer></v-spacer>
                                  <v-btn text color="primary" @click="timeModal = false">Cancel</v-btn>
                                  <v-btn
                                    text
                                    color="primary"
                                    @click="$refs.timeDialog.save(time)"
                                  >OK</v-btn>
                                </v-time-picker>
                              </v-dialog>
                            </v-content>
                          </v-card>
                        </v-col>
                        <v-col xl="3" md="3" sm="12">
                          <v-card class="mx-auto" style="overflow-y:auto" height="330" tile>
                            <v-list-item-content class="pa-4">
                              <strong>Modality</strong>
                              <v-checkbox
                                v-model="fromCheckbox"
                                value="fromDate"
                                label="Show only worklist for modality"
                                type="checkbox"
                                required
                              ></v-checkbox>
                              <v-list
                                subheader
                                two-line
                                flat
                                max-height="207"
                                style="overflow-y:auto"
                              >
                                <v-list-item-group v-model="settings" multiple>
                                  <v-list-item>
                                    <template v-slot:default="{ active, toggle }">
                                      <v-list-item-action>
                                        <v-checkbox :value="active" color="primary" @click="toggle"></v-checkbox>
                                      </v-list-item-action>

                                      <v-list-item-content>
                                        <v-list-item-title>Notifications</v-list-item-title>
                                      </v-list-item-content>
                                    </template>
                                  </v-list-item>
                                  <v-list-item>
                                    <template v-slot:default="{ active, toggle }">
                                      <v-list-item-action>
                                        <v-checkbox color="primary" @click="toggle" :value="active"></v-checkbox>
                                      </v-list-item-action>

                                      <v-list-item-content>
                                        <v-list-item-title>Invites</v-list-item-title>
                                      </v-list-item-content>
                                    </template>
                                  </v-list-item>

                                  <v-list-item>
                                    <template v-slot:default="{ active, toggle }">
                                      <v-list-item-action>
                                        <v-checkbox :value="active" color="primary" @click="toggle"></v-checkbox>
                                      </v-list-item-action>

                                      <v-list-item-content>
                                        <v-list-item-title>Sound</v-list-item-title>
                                      </v-list-item-content>
                                    </template>
                                  </v-list-item>
                                </v-list-item-group>
                              </v-list>
                            </v-list-item-content>
                          </v-card>
                        </v-col>
                        <v-col xl="3" md="3" sm="12">
                          <v-card class="mx-auto" style="overflow-y:auto" height="330" tile>
                            <v-list-item-content class="pa-4">
                              <strong>AETitle</strong>
                              <v-checkbox
                                v-model="fromCheckbox"
                                value="fromDate"
                                label="Show only worklist for AETitle"
                                type="checkbox"
                                required
                              ></v-checkbox>
                              <v-text-field label="AETitle"></v-text-field>
                            </v-list-item-content>
                          </v-card>
                        </v-col>
                        <v-col xl="3" md="3" sm="12">
                          <v-card class="mx-auto" style="overflow-y:auto" height="330" tile>
                            <v-list-item-content class="pa-4">
                              <strong>Patient</strong>
                              <v-checkbox
                                v-model="fromCheckbox"
                                value="fromDate"
                                label="Show only Patients with Name"
                                type="checkbox"
                                required
                              ></v-checkbox>
                              <v-text-field label="Patient Name"></v-text-field>
                            </v-list-item-content>
                            <v-list-item-content class="pa-4">
                              <v-checkbox
                                v-model="fromCheckbox"
                                value="fromDate"
                                label="Show only patient of Sex"
                                type="checkbox"
                                required
                              ></v-checkbox>
                              <v-spacer></v-spacer>
                              <v-checkbox
                                v-model="fromCheckbox"
                                value="fromDate"
                                label="M"
                                type="checkbox"
                                required
                              ></v-checkbox>
                              <v-checkbox
                                v-model="fromCheckbox"
                                value="fromDate"
                                label="F"
                                type="checkbox"
                                required
                              ></v-checkbox>
                              <v-checkbox
                                v-model="fromCheckbox"
                                value="fromDate"
                                label="O"
                                type="checkbox"
                                required
                              ></v-checkbox>
                            </v-list-item-content>
                          </v-card>
                        </v-col>
                      </v-row>
                    </v-container>
                  </v-sheet>
                </v-bottom-sheet>
              </v-col>-->
            </v-row>
          </v-card-actions>
        </v-card>
      </v-col>
      <v-col md="7" lg="7">
        <v-card>
          <v-card-actions>
            <v-col cols="10">
              <v-text-field
                :label="$t('RegisterRoute.advancedSearchLabel')"
                v-model="queryText"
                style="direction:ltr"
              ></v-text-field>
            </v-col>
            <v-col cols="2" class="d-flex align-center justify-center">
              <v-btn icon @click="searchServerSide" class="ma-1"><v-icon color="success">search</v-icon></v-btn>
              <v-btn
                icon
                href="https://kb.marcopacs.com/pages/viewpage.action?pageId=69796098"
                target="_blank"
                class="ma-1"
              >
                <v-icon color="success">live_help</v-icon>
              </v-btn>
            </v-col>
          </v-card-actions>
        </v-card>
      </v-col>
    </v-row>
    <v-row justify="center" dense class="flex-wrap mt-6">
      <v-col md="10" 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!=undefined?worklist4hislink.length:0}}/{{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-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: 40,
      prevLeft: 0,
      tableHeight: "62vh",
      count: 0,
      alertSnackbar: false,
      alertText: "",
      // sheet: false,
      // date: new Date().toISOString().substr(0, 10),
      // modal: false,
      // fromCheckbox: false,
      // timeModal: false,
      // time: null,
      // settings: [],
      query: null,
      queryText: ""
    };
  },
  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;
        }
      }
    },
    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);
      }
    },
    searchServerSide() {
      try {
        this.limit = 40;
        this.query = JSON.parse(this.queryText);
      } catch (e) {
        this.alertText = this.$t("RegisterRoute.jsonParseError");
        this.alertSnackbar = true;
        this.limit = 40;
        this.query = null;
      }
    }
  },
  watch: {
    "$subReady.worklist4hislink"(ready) {
      this.HisWorklistLoading = !ready;
      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: [],
      brandCount: function() {
        return [{ brand: this.selectedBrand, query: this.query }];
      },
      worklist4hislink: function() {
        this.HisWorklistLoading = true;

        return [
          { brand: this.selectedBrand, limit: this.limit, query: this.query },
          {
            onStop: error => {
              if (error != undefined) {
                this.alertText = this.$t("RegisterRoute.dbError");
                this.alertSnackbar = true;
                this.limit = 40;
                this.query = null;
              }
            }
          }
        ];
      }
    },
    hislink() {
      return HisLink.find({}).fetch();
    },
    worklist4hislink() {
      try {
        if (this.selectedBrand == null) return [];
        this.count = Counts.get("brandCount");
        if (BrandCollections[this.selectedBrand])
          if (this.query != null)
            return BrandCollections[this.selectedBrand]
              .find(this.query, { limit: this.limit })
              .fetch();
          else
            return BrandCollections[this.selectedBrand]
              .find({}, { limit: this.limit })
              .fetch();
        else {
          BrandCollections[this.selectedBrand] = new Mongo.Collection(
            this.selectedBrand
          );
          if (this.query == null)
            return BrandCollections[this.selectedBrand]
              .find({}, { limit: this.limit })
              .fetch();
          else
            return BrandCollections[this.selectedBrand]
              .find(this.query, { limit: this.limit })
              .fetch();
        }
      } catch (e) {
        this.alertText = this.$t("RegisterRoute.dbError");
        this.alertSnackbar = true;
        return [];
      }
    }
  }
};
</script>
<style scoped>
</style>