<template>
  <v-container fluid>
    <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">
              <v-col cols="12" sm="8" class="d-flex justify-space-around align-baseline">
                <v-combobox
                  v-model="selectedDevice"
                  :items="deviceCodeItems"
                  :search-input.sync="deviceComboSearch"
                  hide-selected
                  :label="$t('WorkList.deviceComboboxLabel')"
                  persistent-hint
                  small-chips
                  clearable
                  dense
                  class="ma-4"
                  item-text="Text"
                  item-value="Value"
                >
                  <template v-if="noDataCombo" v-slot:no-data>
                    <v-list-item>
                      <v-list-item-content>
                        <v-list-item-title>
                          {{$t('WorkList.deviceComboboxNoDataMatch')}} "
                          <strong>{{ deviceComboSearch }}</strong>
                          " {{$t('WorkList.deviceComboboxNoDataMatch1')}}
                        </v-list-item-title>
                      </v-list-item-content>
                    </v-list-item>
                  </template>
                </v-combobox>
                <v-btn
                  color="rgb(94, 181, 177,.85)"
                  class="white--text"
                  @click="searchPatients()"
                  :disabled="btnDisabled"
                >{{$t('WorkList.seachBtn')}}</v-btn>
              </v-col>
              <v-col cols="12" sm="4" class="d-flex justify-space-around align-center">
                <v-btn color="success" text @click="toggleAllOrUnknown=0">
                  <v-icon left v-if="toggleAllOrUnknown==0">done</v-icon>
                  <strong>{{$t("WorkList.AllBtn")}}</strong>
                </v-btn>
                <v-btn color="success" text @click="toggleAllOrUnknown=1">
                  <v-icon left v-if="toggleAllOrUnknown==1">done</v-icon>
                  <strong>{{$t("WorkList.UnknownBtn")}}</strong>
                </v-btn>
              </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-data-table
          ref="patientsDatatable"
          v-model="selectedPatientInTable"
          :headers="headerOfTable"
          :items="patientsOfTable"
          single-select
          item-key="_id"
          class="elevation-1"
          style="width:100%"
          show-select
          fixed-header
          hide-default-footer
          disable-pagination
          :sort-by.sync="sortByTable"
          :sort-desc.sync="sortDescTable"
          height="550"
        >
          <template v-slot:top>
            <v-toolbar flat color="white">
              <v-toolbar-title>{{devicemap==""?$t("WorkList.noDevicemap"):devicemap}}</v-toolbar-title>

              <v-divider class="mx-4" inset vertical></v-divider>
            </v-toolbar>
          </template>
          <template v-slot:item.Action="{ item }">
            <v-icon small>edit</v-icon>
          </template>
        </v-data-table>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import Worklist from "../../imports/api/collections/worklist.js";
import DeviceCode from "../../imports/api/collections/devicecode.js";
import { Tracker } from "meteor/tracker";
export default {
  methods: {
    searchPatients() {
      if (this.selectedDevice && this.devicemap != this.selectedDevice.Value) {
        let self = this;
        this.btnDisabled = true;
        Meteor.call("Fetchworklist", this.selectedDevice.Value, function() {
          self.devicemap = self.selectedDevice.Value;
          self.btnDisabled = false;
        });
      }

      if (this.selectedDevice == undefined || this.selectedDevice == null) {
        alert("لطفا یک مقدار را انتخاب نمایید");
      }
    }
  },
  data: () => ({
    devicemap: "",
    selectedDevice: undefined,
    deviceComboSearch: null,
    btnDisabled: false,
    noDataCombo: true,
    toggleAllOrUnknown: 0,
    selectedPatientInTable: undefined,
    sortByTable: undefined,
    sortDescTable: undefined
  }),
  mounted() {
    Meteor.call("getDeviceCodes");
    // this.selected = [this.desserts[1]];
  },
  computed: {
    deviceCodeItems() {
      return this.devicecode;
    },
    headerOfTable() {
      let headers = [];
      if (this.worklist && this.worklist.length > 0) {
        const sampleWorkList = this.worklist[0];

        for (let prop in sampleWorkList) {
          if (
            prop != "_id" &&
            !Array.isArray(sampleWorkList[prop]) &&
            [
              "AdmissionID",
              "EnglishFirstName",
              "EnglishLastName",
              "FarsiFirstName",
              "FarsiLastName",
              "HISID",
              "Modality",
              "PatientAge"
            ].indexOf(prop) >= 0
          )
            headers.push({
              text: prop,
              value: prop,
              class: "text-center"
            });
        }
        headers.unshift({
          text: "Action",
          value: "Action",
          class: "text-center"
        });
        return headers;
      }
      return [];
    },
    patientsOfTable() {
      if (this.worklist && this.worklist.length > 0) {
        if (this.toggleAllOrUnknown == 1) {
          return this.worklist.filter(patient => {
            return (
              patient.EnglishFirstName.includes("?") ||
              patient.EnglishLastName.includes("?")
            );
          });
        }

        return this.worklist;
      }
      return [];
    }
  },
  meteor: {
    $subscribe: {
      worklist: function() {
        return [this.devicemap];
      },
      devicecode: []
    },
    worklist() {
      return Worklist.find({}).fetch();
    },
    devicecode() {
      return DeviceCode.find({}).fetch();
    }
  },
  watch: {
    worklist: (newWorklist, oldWorklist) => {
      console.log(newWorklist);
    },
    "$subReady.worklist"(ready) {
      this.btnDisabled = !ready;
    },
    selectedPatientInTable(newSelected, oldSelected) {
      // console.log(this.desserts);
      // console.log(this.sortByTable);
      // console.log(this.sortDescTable);
      // console.log(newSelected);

      if (this.sortByTable && this.sortByTable.length > 0) {
        const items = this.desserts.sort((a, b) => {
          const sortA = a[this.sortByTable[0]];
          const sortB = b[this.sortByTable[0]];

          if (this.sortDescTable && this.sortDescTable[0] == true) {
            if (sortA < sortB) return 1;
            if (sortA > sortB) return -1;
            return 0;
          } else {
            if (sortA < sortB) return -1;
            if (sortA > sortB) return 1;
            return 0;
          }
        });
        console.log(items);
      }
    }
  }
};
</script>


<style lang="less" scoped>
.wholeLayout {
  height: calc(~"98vh - 106px");
}
td,
th {
  width: 50px !important;
}
</style>