<template>
  <v-layout class="fill-height" column>
    <v-dialog v-model="dialogsuccess" persistent max-width="350">
      <v-card>
        <v-card-title color="success" class="headline">Berhasil !</v-card-title>
        <v-card-text v-html="msgsuccess"> </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="green darken-1" flat @click="closeDialogSuccess">OK</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <v-card class="mb-1 pa-2 searchbox">
      <v-layout row>
        <v-flex xs2>
          <v-menu class="pr-2" v-model="menufilterdatestart" :close-on-content-click="false" :nudge-right="40" lazy
            transition="scale-transition" offset-y full-width max-width="290px" min-width="290px">
            <template v-slot:activator="{ on }">
              <v-text-field class="ma-1" v-model="filterComputedDateFormattedStart" label="Tgl. Awal" outline
                hide-details style="font-size: 11px" readonly v-on="on"
                @blur="date = deFormatedDate(filterComputedDateFormattedStart)"></v-text-field>
            </template>
            <v-date-picker v-model="xdatestart" no-title @input="menufilterdatestart = false"></v-date-picker>
          </v-menu>
        </v-flex>
        <v-flex xs2>
          <v-menu class="pl-2" v-model="menufilterdateend" :close-on-content-click="false" :nudge-right="40" lazy
            transition="scale-transition" offset-y full-width max-width="290px" min-width="290px">
            <template v-slot:activator="{ on }">
              <v-text-field class="ma-1" v-model="filterComputedDateFormattedEnd" label="Tgl. Akhir" outline readonly
                style="font-size: 11px" hide-details v-on="on"
                @blur="date = deFormatedDate(filterComputedDateFormattedEnd)"></v-text-field>
            </template>
            <v-date-picker v-model="xdateend" no-title @input="menufilterdateend = false"></v-date-picker>
          </v-menu>
        </v-flex>
        <v-flex xs3>
          <v-text-field class="ma-1" label="Cari..." placeholder="Nama / No Reg" outline style="font-size: 11px"
            v-model="xnamelab" v-on:keyup.enter="searchTransaction" hide-details></v-text-field>
        </v-flex>
        <v-flex xs5>
          <v-layout align-center row>
            <!--<v-flex class="text-xs-center" xs3>
              <span
                title="tidak termasuk"
                v-if="switch_exclude"
                @click="switch_exclude = !switch_exclude"
                class="icon-medium-fill-base-small xs1 white--text red"
                ><v-icon dark>assignment_late</v-icon></span
              >
              <span
                title="termasuk"
                v-if="!switch_exclude"
                @click="switch_exclude = !switch_exclude"
                class="icon-medium-fill-base-small xs1 white--text blue"
                ><v-icon dark>assignment_turned_in</v-icon></span
              >
            </v-flex>-->
            <v-flex xs9>
              <v-select :search-input.sync="search_company" autocomplete v-model="selected_company" :items="xcompanies"
                outline="outline" style="font-size: 12px" auto-select-first item-text="name" return-object
                style="font-size: 11px" label="Corporate" hide-details class="ma-1">
                <template slot="item" slot-scope="{ item }">
                  <v-list-tile-content>
                    <v-list-tile-title v-text="item.name"></v-list-tile-title>
                  </v-list-tile-content>
                </template>
              </v-select>
            </v-flex>
            <v-flex xs3>
              <v-btn @click="searchTransaction"
                class="icon-medium-fill-base xs1 white--text warning iconsearch-search"></v-btn>
            </v-flex>
          </v-layout>
        </v-flex>
      </v-layout>
      <v-layout row>
        <v-flex xs12><kbd style="font-size: 10px;">Tekan tombol search (kuning) untuk memulai pencarian</kbd></v-flex>
      </v-layout>
      <v-layout v-if="loading_search" row>
        <v-flex xs12>
          <v-progress-linear :indeterminate="true"></v-progress-linear>
        </v-flex>
      </v-layout>
    </v-card>
    <v-card>
      <v-layout align-center row>
        <v-flex xs12 pl-2 pr-2 pt-2 pb-2>
          <div style="overflow-y: auto; height: 68vh">
            <v-data-table :headers="headers" :items="xtransactions" :loading="isLoading" hide-actions
              class="elevation-1">
              <template slot="items" slot-scope="props">
                <td class="text-xs-left pa-2" v-bind:class="{
                  'amber lighten-4': isSelected(props.item),
                  amber: props.item.iscito === 'Y',
                }" @click="selectMe(props.item)">
                  <p class="font-weight-black mb-0">
                    {{ props.item.ordernumber }}
                  </p>
                  <p style="color: #800000" class="caption mb-1 font-weight-bold">
                    {{ props.item.test_name }}
                  </p>
                </td>
                <td class="text-xs-left pa-2" v-bind:class="{
                  'amber lighten-4': isSelected(props.item),
                  amber: props.item.iscito === 'Y',
                }" @click="selectMe(props.item)">
                  {{ props.item.orderdate }}
                </td>
                <td class="text-xs-left pa-2" v-bind:class="{
                  'amber lighten-4': isSelected(props.item),
                  amber: props.item.iscito === 'Y',
                }" @click="selectMe(props.item)">
                  <p class="mb-0">{{ props.item.patient_fullname }}</p>
                  <p style="font-size: 10px !important; font-weight: bold" class="blue--text caption">
                    {{ props.item.company_name }}
                  </p>
                </td>
                <td class="text-xs-center pa-2" v-bind:class="{
                  'amber lighten-4': isSelected(props.item),
                  amber: props.item.iscito === 'Y',
                }" @click="selectMe(props.item)">
                  {{ props.item.status_name }}
                </td>
              </template>
            </v-data-table>
          </div>
          <v-divider></v-divider>
          <v-pagination style="margin-top: 10px; margin-bottom: 5px" v-model="curr_page" :length="xtotal_page"
            @input="thr_search"></v-pagination>
        </v-flex>
      </v-layout>
    </v-card>
    <one-dialog-alert :status="openalertconfirmation" :msg="msgalertconfirmation"
      @forget-dialog-alert="forgetAlertConfirmation()"
      @close-dialog-alert="closeAlertConfirmation()"></one-dialog-alert>
    <one-dialog-info :status="opendialoginfo" :msg="msginfo" @close-dialog-info="closeDialogInfo()"></one-dialog-info>
  </v-layout>
</template>

<style scoped>
.searchbox .v-input.v-text-field .v-input__slot {
  min-height: 60px;
}

.searchbox .v-btn {
  min-height: 60px;
}

table.v-table tbody td,
table.v-table tbody th {
  height: 40px;
}

table.v-table thead tr {
  height: 40px;
}
</style>

<script>
module.exports = {
  components: {
    "one-dialog-info": httpVueLoader("../../common/oneDialogInfo.vue"),
    "one-dialog-alert": httpVueLoader("../../common/oneDialogAlert.vue"),
  },
  mounted() {
    if (localStorage.getItem("startdate") != null) {
      this.xdatestart = localStorage.getItem("startdate")
    }

    if (localStorage.getItem("enddate") != null) {
      this.xdateend = localStorage.getItem("enddate")
    }



    var url_string = window.location.href;
    var url = new URL(url_string);
    var id = url.searchParams.get("id");
    var stat_id = url.searchParams.get("stat");
    var loc_id = url.searchParams.get("loc");
    var type = url.searchParams.get("type");
    console.log(url_string)
    console.log(id)
    if (id) {
      console.log("in")
      this.$store.commit("sample/update_search_lab_no", id);
      this.$store.commit("sample/update_search_type", type);
      this.$store.commit("sample/update_station_id", stat_id);
      this.$store.commit("sample/update_location_id", loc_id);
      this.$store.dispatch("sample/search_bynolab");
    } else {
      //this.searchTransaction();
      let start_date = moment(this.xdatestart, 'YYYY-MM-DD')
      let end_date = moment(this.xdateend, 'YYYY-MM-DD')
      const diffInDays = Math.abs(start_date.diff(end_date, 'days'))
      console.log(diffInDays)
      if (diffInDays > 14) {
        this.xdateend = this.xdatestart
      }
      console.log('search')
      this.loading_search = true
      this.$store.dispatch("sample/search", {
        startdate: this.xdatestart,
        enddate: this.xdateend,
        search: this.xnamelab,
        companyid: this.selected_company.id,
        switch_exclude: this.switch_exclude,
        stationid: this.xselectedstation.id,
        groupid: this.$store.state.sample.select_item_group.id,
        subgroupid: this.$store.state.sample.select_item_subgroup.id,
        current_page: 1,
        lastid: -1,
      });

    }
  },
  methods: {
    formatDate(date) {
      if (!date) return null;

      const [year, month, day] = date.split("-");
      return `${day}-${month}-${year}`;
    },
    deFormatedDate(date) {
      if (!date) return null;

      const [day, month, year] = date.split("-");
      return `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")}`;
    },
    isSelected(p) {
      return p.re_id == this.$store.state.sample.selected_transaction.re_id;
      console.log(p.re_id);
    },
    searchTransaction() {
      let start_date = moment(this.xdatestart, 'YYYY-MM-DD')
      let end_date = moment(this.xdateend, 'YYYY-MM-DD')
      const diffInDays = Math.abs(start_date.diff(end_date, 'days'))
      console.log(diffInDays)
      if (diffInDays <= 14) {
        this.$store.commit("sample/update_last_id", -1);
        this.$store.commit("sample/update_current_page", 1);
        this.thr_search();
      } else {
        alert("Makan tomat jangan dicampur kedongdong, aduh berat...maksimal 2 minggu dong")
      }

    },
    selectMe(trx) {
      if (this.$store.state.sample.no_save == 0) {
        var trxs = this.xtransactions;
        var idx = _.findIndex(trxs, function (o) {
          return o.re_id === trx.re_id;
        });
        this.$store.commit("sample/update_last_id", trx.re_id);
        this.$store.commit("sample/update_selected_transaction", trx);
        this.$store.commit("sample/update_sellang", {
          id: "1",
          name: "Bahasa Indonesia",
          code: "INA",
        });
        console.log(trx);
        if (trx.status_name !== "BARU")
          this.$store.commit("sample/update_cantedit", true);
        else this.$store.commit("sample/update_cantedit", false);

        this.$store.commit("sample/update_act", "edit");
        this.$store.dispatch("sample/get_details", trx)

        /*if (trx.details.length > 0) {
          this.$store.commit("sample/update_details", trx.details);
          console.log("before");
          console.log(trx.details[0].template_name);
          if (
            trx.details[0].template_name === "Fisik Umum" ||
            trx.details[0].template_name === "Fisik Umum K3" ||
            trx.details[0].template_name === "Fisik Umum Konsul"
          ) {
            console.log(trx.details[0].template_name);
            if (trx.details[0].template_name === "Fisik Umum")
              this.$store.commit("sample/update_tabs_fisik", [
                { id: 1, name: "RIWAYAT" },
                { id: 2, name: "FISIK" },
              ]);
            if (trx.details[0].template_name === "Fisik Umum K3")
              this.$store.commit("sample/update_tabs_fisik", [
                { id: 1, name: "RIWAYAT" },
                { id: 2, name: "FISIK" },
                { id: 3, name: "PAJANAN" },
              ]);
            if (trx.details[0].template_name === "Fisik Umum Konsul")
              this.$store.commit("sample/update_tabs_fisik", [
                { id: 1, name: "RIWAYAT" },
                { id: 2, name: "FISIK" },
                { id: 3, name: "KONSULTASI" },
              ]);
            var prm = trx.details[0];
            prm.act = trx.details[0].template_name;
            prm.language_id = this.$store.state.sample.sellang.id;
            prm.language_name = this.$store.state.sample.sellang.name;
            this.$store.dispatch("sample/getumum", prm);
            // this.generateRiwayatRow()
          } else if (trx.details[0].template_name === "6MWT") {
            console.log(trx.details[0].template_name);
            var prm = trx.details[0];
            prm.language_id = this.$store.state.sample.sellang.id;
            prm.language_name = this.$store.state.sample.sellang.name;
            this.$store.dispatch("sample/get6mwt", prm);
            // this.generateRiwayatRow()
          } else if (trx.details[0].template_name === "SDS") {
            console.log(trx.details[0].template_name);
            var prm = trx.details[0];
            prm.language_id = this.$store.state.sample.sellang.id;
            prm.language_name = this.$store.state.sample.sellang.name;
            this.$store.dispatch("sample/getsds", prm);
            // this.generateRiwayatRow()
          } else {
            var prm = {
              selected_trx: trx,
              trx: trx.details[0],
              lang: this.$store.state.sample.sellang,
              idx: 0,
              detail: trx.details[0],
            };
            this.$store.dispatch("sample/getrstbylang", prm);
          }
        } else {
          this.$store.commit("sample/update_details", []);
          this.$store.commit("sample/update_data_6mwt", []);
        }*/
      } else {
        this.$store.commit("sample/update_open_alert_confirmation", true);
      }
    },
    closeAlertConfirmation() {
      this.$store.commit("sample/update_open_alert_confirmation", false);
    },
    forgetAlertConfirmation() {
      this.$store.commit("sample/update_no_save", 0);
      this.$store.commit("sample/update_open_alert_confirmation", false);
    },
    updateAlert_success(val) {
      this.$store.commit("sample/update_alert_success", val);
    },
    setNewTransaction() {
      this.$store.commit("sample/update_selected_transaction", {});
      this.$store.commit("sample/update_details", []);
      this.$store.commit("sample/update_selected_detail", {});
      this.$store.commit("sample/update_selected_doctor", {});
      this.$store.commit("sample/update_selected_doctor_address", {});
      this.$store.commit("sample/update_selected_courier", {});
      this.$store.commit(
        "sample/update_trx_date",
        moment(new Date()).format("YYYY-MM-DD")
      );
      this.$store.commit("sample/update_trx_note", "");
      this.$store.commit("sample/update_act", "new");
    },
    closeDialogSuccess() {
      let arrtrx = this.$store.state.sample.transactions;
      //var idx = _.findIndex(arrtrx, item => item.re_id === this.$store.state.sample.last_id)
      // console.log(idx)
      this.$store.dispatch("sample/search", {
        startdate: this.xdatestart,
        enddate: this.xdateend,
        search: this.xnamelab,
        companyid: this.selected_company.id,
        switch_exclude: this.switch_exclude,
        stationid: this.xselectedstation.id,
        groupid: this.$store.state.sample.select_item_group.id,
        subgroupid: this.$store.state.sample.select_item_subgroup.id,
        lastid: this.$store.state.sample.last_id,
      });
      this.$store.commit("sample/update_dialog_success", false);
    },
    closeDialogInfo() {
      this.$store.commit("sample/update_open_dialog_info", false);
    },
    selectgroup(value) {
      this.selected_itemgroup = value;
    },
    selectsubgroup(value) {
      this.selected_itemsubgroup = value;
    },
    generateRiwayatRow() {
      var riwayats = this.$store.state.sample.riwayats.details;
      var row_riwayats = [];
      var rows = [];
      riwayats.forEach(function (item, index) {
        rows.push(item);
        if (index % 2 === 0) row_riwayats.push(rows);
      });
      this.$store.commit("sample/update_riwayats_row", row_riwayats);
    },
    thr_search_company: _.debounce(function () {
      this.$store.dispatch("sample/searchcompany", this.search_company);
    }, 2000),
    thr_search() {
      this.loading_search = true
      this.$store.dispatch("sample/search", {
        startdate: this.xdatestart,
        enddate: this.xdateend,
        search: this.xnamelab,
        companyid: this.selected_company.id,
        switch_exclude: this.switch_exclude,
        stationid: this.xselectedstation.id,
        groupid: this.$store.state.sample.select_item_group.id,
        subgroupid: this.$store.state.sample.select_item_subgroup.id,
        current_page: this.curr_page,
        lastid: -1,
      });
    },
  },
  computed: {

    search_lab_no() {
      return this.$store.state.sample.search_lab_no;
    },
    selected_company: {
      get() {
        return this.$store.state.sample.selected_company;
      },
      set(val) {
        this.$store.commit("sample/update_selected_company", val);
        //this.searchTransaction();
      },
    },
    switch_exclude: {
      get() {
        return this.$store.state.sample.switch_exclude;
      },
      set(val) {
        this.$store.commit("sample/update_switch_exclude", val);
        //this.searchTransaction();
      },
    },
    dialogsuccess: {
      get() {
        return this.$store.state.sample.dialog_success;
      },
      set(val) {
        this.$store.commit("sample/update_dialog_success", val);
      },
    },
    msgsuccess() {
      return this.$store.state.sample.msg_success;
    },
    snackbar: {
      get() {
        return this.$store.state.sample.alert_success;
      },
      set(val) {
        this.$store.commit("sample/update_alert_success", val);
      },
    },
    isLoading() {
      return this.$store.state.sample.search_status == 1;
    },
    itemgroups() {
      return this.$store.state.sample.item_groups;
    },
    selected_itemgroupname() {
      return this.$store.state.sample.selected_itemgroupname;
    },
    selected_itemgroup: {
      get() {
        //console.log(this.$store.state.sample.select_item_group)
        return this.$store.state.sample.select_item_group;
      },
      set(val) {
        this.$store.commit("sample/update_select_item_group", val);
        this.$store.commit("sample/update_selected_itemgroupname", val.fulltitle);
        this.$store.commit("sample/update_item_subgroups", val.childrens);
        this.$store.commit("sample/update_select_item_subgroup", val.childrens[0]);
        this.$store.commit(
          "sample/update_selected_itemsubgroupname",
          val.childrens[0].fulltitle
        );
      },
    },
    itemsubgroups() {
      return this.$store.state.sample.item_subgroups;
    },
    selected_itemsubgroupname() {
      return this.$store.state.sample.selected_itemsubgroupname;
    },
    selected_itemsubgroup: {
      get() {
        return this.$store.state.sample.select_item_subgroup;
      },
      set(val) {
        this.$store.commit("sample/update_select_item_subgroup", val);
        this.$store.commit("sample/update_selected_itemsubgroupname", val.fulltitle);
      },
    },
    xdatestart: {
      get() {
        return this.$store.state.sample.start_date;
      },
      set(val) {
        this.$store.commit("sample/update_start_date", val);
        localStorage.setItem("startdate", val);
        //this.searchTransaction();
        console.log(val)
      },
    },
    xdateend: {
      get() {
        return this.$store.state.sample.end_date;
      },
      set(val) {
        this.$store.commit("sample/update_end_date", val);
        localStorage.setItem("enddate", val);
        //this.searchTransaction();
      },
    },
    min_start_date: {
      get() {
        return this.$store.state.sample.min_start_date;
      },
      set(val) {
        this.$store.commit("sample/update_min_start_date", val);
      },
    },
    max_start_date: {
      get() {
        return this.$store.state.sample.max_start_date;
      },
      set(val) {
        this.$store.commit("sample/update_max_start_date", val);
      },
    },
    min_end_date: {
      get() {
        return this.$store.state.sample.min_end_date;
      },
      set(val) {
        this.$store.commit("sample/update_min_end_date", val);
      },
    },
    max_end_date: {
      get() {
        return this.$store.state.sample.max_end_date;
      },
      set(val) {
        this.$store.commit("sample/update_max_end_date", val);
      },
    },
    xnamelab: {
      get() {
        return this.$store.state.sample.name_lab;
      },
      set(val) {
        this.$store.commit("sample/update_name_lab", val);
      },
    },
    filterComputedDateFormattedStart() {
      return this.formatDate(this.xdatestart);
    },
    filterComputedDateFormattedEnd() {
      return this.formatDate(this.xdateend);
    },
    xstations() {
      return this.$store.state.sample.stations;
    },
    xselectedstation: {
      get() {
        return this.$store.state.sample.selected_station;
      },
      set(val) {
        this.$store.commit("sample/update_selected_station", val);
      },
    },
    xtransactions() {
      //console.log(this.$store.state.sample.transactions)
      return this.$store.state.sample.transactions;
    },
    openalertconfirmation: {
      get() {
        return this.$store.state.sample.open_alert_confirmation;
      },
      set(val) {
        this.$store.commit("sample/update_open_alert_confirmation", val);
      },
    },
    opendialoginfo: {
      get() {
        return this.$store.state.sample.open_dialog_info;
      },
      set(val) {
        this.$store.commit("sample/update_open_dialog_info", false);
      },
    },
    msginfo() {
      return this.$store.state.sample.msg_info;
    },
    curr_page: {
      get() {
        return this.$store.state.sample.current_page;
      },
      set(val) {
        this.$store.commit("sample/update_current_page", val);
        this.$store.commit("sample/update_last_id", -1);
      },
    },
    xtotal_page: {
      get() {
        return this.$store.state.sample.total_page;
      },
      set(val) {
        this.$store.commit("sample/update_total_page", val);
      },
    },
    xcompanies() {
      return this.$store.state.sample.companies;
    },
    selected_company: {
      get() {
        return this.$store.state.sample.selected_company;
      },
      set(val) {
        this.$store.commit("sample/update_selected_company", val);
        //this.searchTransaction();
      },
    },
    loading_search: {
      get() {
        return this.$store.state.sample.loading_search;
      },
      set(val) {
        this.$store.commit("sample/update_loading_search", val);
        //this.searchTransaction();
      },
    },
  },
  data() {
    return {
      search_company: "",
      msgalertconfirmation: "Perubahan yang telah dilakukan belum disimpan dong !",
      menufilterdatestart: false,
      menufilterdateend: false,
      date: new Date().toISOString().substr(0, 10),
      items: [],
      name: "",
      page: 1,
      headers: [
        {
          text: "NO REG",
          align: "left",
          sortable: false,
          width: "8%",
          class: "pa-2 blue  white--text",
        },
        {
          text: "TANGGAL",
          align: "left",
          sortable: false,
          width: "8%",
          class: "pa-2 blue  white--text",
        },
        {
          text: "PASIEN",
          align: "left",
          sortable: false,
          width: "18%",
          class: "pa-2 blue  white--text",
        },
        {
          text: "STATUS",
          align: "center",
          sortable: false,
          width: "10%",
          class: "pa-2 blue white--text",
        },
      ],
      pagination: {
        descending: false,
        page: 1,
        rowsPerPage: 5,
        sortBy: "trx_id ASC",
        totalItems: this.$store.state.sample.total_transactions,
      },
    };

  },
  watch: {

  },
};
</script>
