<template>
  <v-container fluid>
    <v-snackbar color="primary" v-model="snackbar" top>
      {{$t("HISLink.DeleteMessage")}}
      <v-btn color="pink" @click="deleteHislink">{{$t("HISLink.YesBtn")}}</v-btn>
      <v-btn color="pink" @click="snackbar = false">{{$t("HISLink.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("HISLink.newText"):$t("HISLink.editText")}} {{$t("HISLink.HISLinkName")}}</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="Name" v-model="HisLinkForm.Name"></v-text-field>
              </v-col>
              <v-col cols="12" md="6">
                <v-autocomplete :items="itemsOfBrands" label="Brand" v-model="HisLinkForm.Brand"></v-autocomplete>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field label="UserName" type="text" v-model="HisLinkForm.UserName"></v-text-field>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field label="Password" type="text" v-model="HisLinkForm.Password"></v-text-field>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field label="Address" type="text" v-model="HisLinkForm.Address"></v-text-field>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field label="Database Name" type="text" v-model="HisLinkForm.DatabaseName"></v-text-field>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field
                  label="Link Server Name"
                  type="text"
                  v-model="HisLinkForm.LinkServerName"
                ></v-text-field>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field label="Schema" type="text" v-model="HisLinkForm.Schema"></v-text-field>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field
                  label="CaseId Expression"
                  type="text"
                  v-model="HisLinkForm.CaseExpression"
                >></v-text-field>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field
                  label="Transform Expression"
                  type="text"
                  v-model="HisLinkForm.TransformExpression"
                ></v-text-field>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field
                  label="Source Expression"
                  type="text"
                  v-model="HisLinkForm.SourceExpression"
                ></v-text-field>
              </v-col>
              <v-col cols="12">
                <v-textarea
                  label="Description"
                  type="text"
                  v-model="HisLinkForm.Description"
                  height="150px"
                  hide-details
                  no-resize
                  readonly
                ></v-textarea>
              </v-col>
            </v-row>
          </v-container>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="blue darken-1"
            text
            @click="createOrEditHisLink"
          >{{newOrEdit=="new"?$t("HISLink.createBtn"):$t("HISLink.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-btn color="rgb(94, 181, 177,.85)" class="white--text" @click="activeHislink">
                  <strong>{{$t("HISLink.activeBtn")}}</strong>
                </v-btn>
                <v-btn color="rgb(94, 181, 177,.85)" class="white--text" @click="deactiveHislink">
                  <strong>{{$t("HISLink.deactiveBtn")}}</strong>
                </v-btn>
                <v-btn
                  color="rgb(94, 181, 177,.85)"
                  class="white--text"
                  @click="authenticateHislink"
                >
                  <strong>{{$t("HISLink.authenticateBtn")}}</strong>
                </v-btn>
                <v-btn color="rgb(94, 181, 177,.85)" class="white--text" @click="getWorklist">
                  <strong>{{$t("HISLink.getWorklistBtn")}}</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>
    <his-worklist
      :HisWorklistDialogProp="HisWorklistDialog"
      :closeDialog="closeHisWorklistMethod"
      :selectedBrand="selectedBrand"
    ></his-worklist>
  </v-container>
</template>
<script>
import HisLink from "../../imports/api/collections/hislink.js";
import Brands from "../../imports/api/collections/brands.js";
import { Meteor } from "meteor/meteor";
import HisWorklist from "./HisWorklist.vue";
export default {
  components: {
    HisWorklist
  },
  data() {
    return {
      sortByTable: undefined,
      sortDescTable: undefined,
      selectedItemInTable: [],
      dialog: false,
      newOrEdit: "",
      HisLinkForm: {
        Name: "",
        Brand: "",
        UserName: "",
        Password: "",
        Address: "",
        DatabaseName: "",
        LinkServerName: "",
        Schema: "",
        CaseExpression: "",
        TransformExpression: "",
        SourceExpression: "",
        Description: "",
        _id: ""
      },
      snackbar: false,
      alertSnackbar: false,
      alertText: "",
      loading: false,
      HisWorklistDialog: false,
      selectedBrand: null
    };
  },
  mounted() {
    Meteor.call("getBrands");
  },
  computed: {
    headerOfTable() {
      let headers = [
        "Name",
        "Brand",
        "UserName",
        "Address",
        "DatabaseName",
        "LinkServerName",
        "Schema",
        "CaseExpression",
        "TransformExpression",
        "SourceExpression",
        "Active"
      ];
      let headerObjs = [];
      for (let header of headers) {
        headerObjs.push({
          text: header,
          value: header,
          class: "text-center",
          width: 180
        });
      }
      return headerObjs;
    },
    itemsOfTable() {
      this.dialog = false;
      this.loading = false;
      if (this.hislink && this.hislink.length > 0) {
        return this.hislink;
      }
      return [];
    },
    itemsOfBrands() {
      if (this.brands && this.brands.length > 0) {
        return this.brands.map(brand => {
          return brand.Name;
        });
      }
      return [];
    }
  },
  methods: {
    closeHisWorklistMethod() {
      this.HisWorklistDialog = false;
      this.selectedBrand = null;
    },
    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.HisLinkForm) {
        this.$set(this.HisLinkForm, prop, "");
      }
      this.$set(this.HisLinkForm, "_id", "");
      this.newOrEdit = "new";
      this.dialog = true;
    },
    openEditDialog() {
      if (this.selectedItemInTable.length == 0) {
        this.alertSnackbarMethod(this.$t("HISLink.hislinkSelectStatement"));
        return;
      }
      for (let prop in this.HisLinkForm) {
        if (this.selectedItemInTable[0][prop] != undefined) {
          this.$set(this.HisLinkForm, prop, this.selectedItemInTable[0][prop]);
        }
      }
      this.$set(this.HisLinkForm, "_id", this.selectedItemInTable[0]["_id"]);
      this.newOrEdit = "edit";
      this.dialog = true;
    },
    createOrEditHisLink() {
      let me = this;
      this.loading = true;
      if (this.newOrEdit == "new") {
        Meteor.call("createHisLink", this.HisLinkForm, function() {
          // me.dialog = false;
        });
      }
      if (this.newOrEdit == "edit") {
        Meteor.call("editHisLink", this.HisLinkForm, function() {
          // me.dialog = false;
          me.selectedItemInTable = [];
        });
      }
    },
    deleteHislink() {
      let me = this;
      this.snackbar = false;
      if (this.selectedItemInTable.length == 0) {
        me.alertSnackbarMethod(me.$t("HISLink.hislinkSelectStatement"));
        return;
      }
      let deleteHislink = {};
      deleteHislink._id = this.selectedItemInTable[0]["_id"];

      Meteor.call("deleteHisLink", deleteHislink, function() {
        me.alertSnackbarMethod(me.$t("HISLink.hislinkDeleteStatement"));
      });
    },
    deleteSnackbar() {
      this.snackbar = true;
    },
    alertSnackbarMethod(text) {
      this.alertText = text;
      this.alertSnackbar = true;
    },
    activeHislink() {
      let me = this;
      if (this.selectedItemInTable.length == 0) {
        me.alertSnackbarMethod(me.$t("HISLink.hislinkSelectStatement"));
        return;
      }
      let activeHislink = {};
      activeHislink._id = this.selectedItemInTable[0]["_id"];

      Meteor.call("activeHisLink", activeHislink, function() {
        me.alertSnackbarMethod(me.$t("HISLink.hislinkActiveStatement"));
      });
    },
    deactiveHislink() {
      let me = this;
      if (this.selectedItemInTable.length == 0) {
        me.alertSnackbarMethod(me.$t("HISLink.hislinkSelectStatement"));
        return;
      }
      let deactiveHislink = {};
      deactiveHislink._id = this.selectedItemInTable[0]["_id"];

      Meteor.call("deactiveHisLink", deactiveHislink, function() {
        me.alertSnackbarMethod(me.$t("HISLink.hislinkDeactiveStatement"));
      });
    },
    authenticateHislink() {
      let me = this;
      if (this.selectedItemInTable.length == 0) {
        me.alertSnackbarMethod(me.$t("HISLink.hislinkSelectStatement"));
        return;
      }
      let authenticateHislink = {
        HISLink: {
          ...this.selectedItemInTable[0]
        }
      };

      // let authenticateHislink = {
      //   HISLink: {
      //     _id: "5def5c2bd2a494489d9dfee4",
      //     Name: "Broker",
      //     Brand: "TestWLS",
      //     Address: "192.168.0.15",
      //     UserName: "HISROUser",
      //     Password: "800400",
      //     Description:
      //       "CaseInfo Query =>\nselect * from ServicesForPACS where RecordNo='{0}'\n---------\nRe portInfo Query =>\n---------\nWorkList Query =>",
      //     DatabaseName: "mv",
      //     Active: true,
      //     LinkServerName: null,
      //     MatchExpression: null,
      //     TransformExpression: null,
      //     SourceExpression: null,
      //     Schema: null,
      //     HDRef: null
      //   }
      // };
      Meteor.call("authenticateHisLink", authenticateHislink, function(
        err,
        result
      ) {
        if (err) {
          me.alertSnackbarMethod(me.$t("HISLink.hislinkAuthenticateFailed"));
        }
        me.alertSnackbarMethod(
          JSON.parse(result.content).Result == true
            ? me.$t("HISLink.hislinkAuthenticateSuccess")
            : me.$t("HISLink.hislinkAuthenticateFailed")
        );
      });
    },
    getWorklist() {
      let me = this;
      if (this.selectedItemInTable.length == 0) {
        me.alertSnackbarMethod(me.$t("HISLink.hislinkSelectStatement"));
        return;
      }

      let Brand = this.selectedItemInTable[0].Brand;
      this.selectedBrand = Brand;
      this.HisWorklistDialog = true;
      
    }
  },
  meteor: {
    $subscribe: {
      hislink: [],
      brands: []
    },
    hislink() {
      return HisLink.find({}).fetch();
    },
    brands() {
      return Brands.find({}).fetch();
    }
  },
  watch: {
    "HisLinkForm.Brand"(newvalue, oldvalue) {
      let selectedBrand = this.brands.filter(brand => {
        return brand.Name == newvalue;
      });
      this.HisLinkForm.Description = selectedBrand[0].InfoGetter;
    }
  }
};
</script>
<style scoped>
</style>