<template>
  <v-container>
    <v-snackbar color="primary" v-model="snackbar" top>
      {{$t("DeviceMap.DeleteMessage")}}
      <v-btn color="pink" @click="deleteDevicemap">{{$t("DeviceMap.YesBtn")}}</v-btn>
      <v-btn color="pink" @click="snackbar = false">{{$t("DeviceMap.NoBtn")}}</v-btn>
    </v-snackbar>
    <v-snackbar color="primary" v-model="alertSnackbar" :timeout="2000">{{alertText}}</v-snackbar>
    <v-dialog v-model="dialog" max-width="600px">
      <v-card>
        <v-card-title>
          <span>{{newOrEdit=="new"?$t("DeviceMap.newText"):$t("DeviceMap.editText")}} {{$t("DeviceMap.devicemapName")}}</span>
        </v-card-title>
        <v-card-text>
          <v-container>
            <div>
              <v-progress-linear :active="loading" :indeterminate="loading" color="cyan lighten-2"></v-progress-linear>
            </div>
            <v-row dense>
              <v-col cols="12" md="6">
                <v-text-field label="Group Name" v-model="DevicemapForm.GroupName"></v-text-field>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field label="Code in HIS" v-model="DevicemapForm.CodeInHIS"></v-text-field>
              </v-col>
              <v-col cols="12" md="6">
                <v-autocomplete
                  :items="itemsOfClients"
                  label="Code in Pacs"
                  v-model="selectedClient"
                  item-text="Caption"
                  item-value="Caption"
                  return-object
                ></v-autocomplete>
              </v-col>
              <v-col cols="12" md="6">
                <v-autocomplete
                  :items="itemsOfHisLink"
                  label="HIS Name"
                  v-model="selectedHisLink"
                  item-text="Name"
                  item-value="Name"
                  return-object
                ></v-autocomplete>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field label="Modality" type="text" v-model="DevicemapForm.Modality"></v-text-field>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field label="Max Length" type="number" v-model="DevicemapForm.MaxLen"></v-text-field>
              </v-col>
            </v-row>
          </v-container>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="blue darken-1"
            text
            @click="createOrEditDevicemap"
          >{{newOrEdit=="new"?$t("DeviceMap.createBtn"):$t("DeviceMap.editBtn")}}</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <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" class="d-flex justify-center align-center flex-wrap">
                <v-btn color="rgb(94, 181, 177,.85)" class="white--text" @click="openNewDialog">
                  <strong>{{$t("HISLink.newBtn")}}</strong>
                </v-btn>
                <v-btn color="rgb(94, 181, 177,.85)" class="white--text" @click="openEditDialog">
                  <strong>{{$t("HISLink.editBtn")}}</strong>
                </v-btn>
                <v-btn color="rgb(94, 181, 177,.85)" class="white--text" @click="deleteSnackbar">
                  <strong>{{$t("HISLink.deleteBtn")}}</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
          v-model="selectedItemInTable"
          :headers="headerOfTable"
          :items="itemsOfTable"
          item-key="_id"
          class="elevation-1"
          style="width:100%"
          fixed-header
          hide-default-footer
          disable-pagination
          show-select
          single-select
          :sort-by.sync="sortByTable"
          :sort-desc.sync="sortDescTable"
          height="73vh"
          @click:row="clickRow"
        ></v-data-table>
      </v-col>
    </v-row>
  </v-container>
</template>
<script>
import Devicemap from "../../imports/api/collections/devicemap.js";
import HisLink from "../../imports/api/collections/hislink.js";
import Client from "../../imports/api/collections/clients.js";
import { Meteor } from "meteor/meteor";
export default {
  data() {
    return {
      sortByTable: undefined,
      sortDescTable: undefined,
      selectedItemInTable: [],
      dialog: false,
      newOrEdit: "",
      selectedClient: undefined,
      selectedHisLink: undefined,
      DevicemapForm: {
        GroupName: "",
        CodeInHIS: "",
        CodeInPacs: "",
        Modality: "",
        HisLinkId: "",
        MaxLen: 0,
        _id: ""
      },
      snackbar: false,
      alertSnackbar: false,
      alertText: "",
      loading: false
    };
  },
  computed: {
    headerOfTable() {
      let headers = [
        "GroupName",
        "CodeInHIS",
        "CodeInPacs",
        "Modality",
        "HisName"
      ];
      let headerObjs = [];
      for (let header of headers) {
        headerObjs.push({
          text: header,
          value: header,
          class: "text-center",
          width: 180
        });
      }
      return headerObjs;
    },
    itemsOfTable() {
      this.loading = false;
      this.dialog = false;
      if (this.devicemaps && this.devicemaps.length > 0) {
        let currentDevicemap = [];
        for (let devicemap of this.devicemaps) {
          let hislink = HisLink.find(
            { _id: devicemap.HisLinkId },
            { fields: { Name: 1 } }
          ).fetch();
          if (
            hislink != undefined &&
            hislink != null &&
            hislink[0].Name != undefined
          )
            currentDevicemap.push({ ...devicemap, HisName: hislink[0].Name });
        }

        return currentDevicemap;
      }
      return [];
    },
    itemsOfClients() {
      if (this.clients && this.clients.length > 0) {
        return this.clients;
      }
      return [];
    },
    itemsOfHisLink() {
      if (this.hislink && this.hislink.length > 0) {
        return this.hislink;
      }
      return [];
    }
  },
  methods: {
    clickRow(item) {
      if (
        this.selectedItemInTable.length > 0 &&
        this.selectedItemInTable[0]._id == item._id
      ) {
        this.selectedItemInTable = [];
      } else {
        this.selectedItemInTable = [];
        this.selectedItemInTable = [item];
      }
    },
    openNewDialog() {
      for (let prop in this.DevicemapForm) {
        this.$set(this.DevicemapForm, prop, "");
        if (prop == "MaxLen") this.$set(this.DevicemapForm, prop, 0);
      }
      this.selectedClient = undefined;
      this.selectedHisLink = undefined;
      this.$set(this.DevicemapForm, "_id", "");
      this.newOrEdit = "new";
      this.dialog = true;
    },
    openEditDialog() {
      if (this.selectedItemInTable.length == 0) {
        this.alertSnackbarMethod(this.$t("DeviceMap.devicemapSelectStatement"));
        return;
      }
      for (let prop in this.DevicemapForm) {
        if (this.selectedItemInTable[0][prop] != undefined) {
          this.$set(
            this.DevicemapForm,
            prop,
            this.selectedItemInTable[0][prop]
          );
        }
      }

      this.selectedClient = undefined;
      this.selectedHisLink = undefined;
      let me = this;
      this.selectedClient = this.clients.filter(client => {
        return client.Caption == me.DevicemapForm.CodeInPacs;
      })[0];

      this.selectedHisLink = HisLink.find({
        _id: me.DevicemapForm.HisLinkId
      }).fetch()[0];

      this.$set(this.DevicemapForm, "_id", this.selectedItemInTable[0]["_id"]);
      this.newOrEdit = "edit";
      this.dialog = true;
    },
    createOrEditDevicemap() {
      this.loading = true;
      let me = this;
      if (this.newOrEdit == "new") {
        if (this.selectedClient != undefined && this.selectedClient != null)
          this.DevicemapForm.CodeInPacs = this.selectedClient.Caption;

        if (this.selectedHisLink != undefined && this.selectedHisLink != null) {
          this.DevicemapForm.HisLinkId = this.selectedHisLink._id;
        }

        Meteor.call("createDevicemap", this.DevicemapForm, function() {});
      }
      if (this.newOrEdit == "edit") {
        if (this.selectedClient != undefined && this.selectedClient != null)
          this.DevicemapForm.CodeInPacs = this.selectedClient.Caption;

        if (this.selectedHisLink != undefined && this.selectedHisLink != null) {
          this.DevicemapForm.HisLinkId = this.selectedHisLink._id;
        }

        Meteor.call("editDevicemap", this.DevicemapForm, function() {
          // me.dialog = false;
          me.selectedItemInTable = [];
        });
      }
    },
    deleteDevicemap() {
      let me = this;
      this.snackbar = false;
      if (this.selectedItemInTable.length == 0) {
        me.alertSnackbarMethod(me.$t("DeviceMap.devicemapSelectStatement"));
        return;
      }
      let deleteHislink = {};
      deleteHislink._id = this.selectedItemInTable[0]["_id"];

      Meteor.call("deleteDevicemap", deleteHislink, function() {
        me.alertSnackbarMethod(me.$t("DeviceMap.devicemapDeleteStatement"));
      });
    },
    deleteSnackbar() {
      this.snackbar = true;
    },
    alertSnackbarMethod(text) {
      this.alertText = text;
      this.alertSnackbar = true;
    }
  },
  meteor: {
    $subscribe: {
      devicemaps: [],
      hislink: [],
      clients: []
    },
    devicemaps() {
      return Devicemap.find({}).fetch();
    },
    hislink() {
      return HisLink.find({}).fetch();
    },
    clients() {
      return Client.find({}).fetch();
    }
  }
};
</script>
<style>
</style>