<template>
  <div>
    <v-dialog persistent v-model="dialogAdd" width="50%">
      <v-card>
        <v-card-title class="headline grey lighten-2" primary-title>
          Serah Terima Hasil
        </v-card-title>

        <v-card-text>
          <v-layout row wrap>
            <v-flex xs12>
              <v-text-field
                label="Penerima"
                v-model="receiver"
                :readonly="!isObjectEmpty(selectedHandover)"
                outline
              ></v-text-field>
            </v-flex>
            <v-flex xs12>
              <v-textarea
                outline
                v-model="note"
                :readonly="!isObjectEmpty(selectedHandover)"
                label="Catatan"
                rows="1"
                auto-grow
              ></v-textarea>
            </v-flex>
            <v-flex xs12 v-if="selectedData.length > 0">
              <fieldset>
                <legend class="px-3">
                  {{ selectedData.length }} item terpilih
                </legend>
                <v-layout row wrap class="pa-2">
                  <v-chip
                    v-for="(data, index) in selectedData"
                    :key="index"
                    class="mr-2"
                    >{{ data.orderNumber }}</v-chip
                  >
                </v-layout>
              </fieldset>
            </v-flex>
          </v-layout>
        </v-card-text>

        <v-divider></v-divider>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="error"
            :disabled="loading"
            flat
            @click="dialogAdd = false"
          >
            Batal
          </v-btn>
          <v-btn color="primary" :disabled="loading" flat @click="saveData()">
            Simpan
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <v-layout column>
      <v-layout align-center column>
        <v-toolbar dark color="primary">
          <v-toolbar-title class="white--text"
            >SERAH TERIMA HASIL</v-toolbar-title
          >
          <v-spacer></v-spacer>

          <v-btn
            v-if="!isObjectEmpty(selectedHandover)"
            @click="print()"
            icon
            v-on="on"
          >
            <v-icon>print</v-icon>
          </v-btn>

          <v-btn
            v-if="!isAdd && !isObjectEmpty(selectedHandover)"
            @click="searchForAdd()"
            color="warning"
            >Tambahkan</v-btn
          >
          <v-btn v-if="isAdd" @click="openDialogSave()" color="warning"
            >Simpan</v-btn
          >
        </v-toolbar>
        <v-card style="width: 100%" class="mb-2 pa-2">
          <v-layout row wrap>
            <v-flex xs3>
              <v-menu
                v-model="menuFormDateStart"
                :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="mr-2"
                    v-model="formatedStartDateDetail"
                    label="Tanggal Awal"
                    outline
                    hide-details
                    readonly
                    v-on="on"
                    @blur="deFormatedDate(formatedStartDateDetail)"
                  ></v-text-field>
                </template>
                <v-date-picker
                  v-model="startDateDetailForm"
                  no-title
                  @input="menuFormDateStart = false"
                ></v-date-picker>
              </v-menu>
            </v-flex>
            <v-flex xs3>
              <v-menu
                v-model="menuFormDateEnd"
                :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="mr-2"
                    v-model="formatedEndDateDetail"
                    label="Tanggal Akhir"
                    outline
                    readonly
                    hide-details
                    v-on="on"
                    @blur="deFormatedDate(formatedEndDateDetail)"
                  ></v-text-field>
                </template>
                <v-date-picker
                  v-model="endDateDetailForm"
                  no-title
                  @input="menuFormDateEnd = false"
                ></v-date-picker>
              </v-menu>
            </v-flex>
            <v-flex xs3>
              <v-text-field
                class="mr-2"
                hide-details
                label="cari"
                v-model="searchDetail"
                outline
              ></v-text-field>
            </v-flex>
            <v-flex xs3>
              <!-- <v-btn @click="addNew" v-if="!isAdd">
                <v-icon>add_box</v-icon>
              </v-btn> -->

              <!-- <div>
                <v-btn v-if="!isAdd" @click="searchForAdd()" color="success"
                  >Tambahkan Hasil</v-btn
                >
              </div> -->
              <v-select
                v-if="isAdd"
                :items="statusDetail"
                label="Status"
                class="mini-select"
                item-text="text"
                item-value="value"
                v-model="selectedStatusDetail"
                hide-details
                outline
              ></v-select>
            </v-flex>
            <v-flex xs12 v-if="selectedData.length > 0">
              <fieldset>
                <legend class="px-3">
                  {{ selectedData.length }} item terpilih
                </legend>
                <v-layout row wrap class="pa-2">
                  <v-chip
                    v-for="(data, index) in selectedData"
                    @input="changeCheckBox(data)"
                    :disabled="loading"
                    :key="index"
                    class="mr-2"
                    close
                    >{{ data.orderNumber }}</v-chip
                  >
                </v-layout>
              </fieldset>
            </v-flex>
          </v-layout>
        </v-card>
      </v-layout>
      <v-card>
        <div class="pa-2">
          <span class="light-green--text font-weight-bold"
            >Sudah Diserahkan : {{ totalHandover }}</span
          >
          |
          <span class="red--text text--lighten-1 font-weight-bold"
            >Belum Diserahkan :{{ totalNotHandover }}</span
          >
          |
          <span class="orange--text font-weight-bold"
            >Total : {{ totalData }}</span
          >
        </div>
        <div style="overflow-y: scroll; height: 65vh" class="fill-height">
          <v-data-table
            :headers="headers"
            :items="handoverDetail"
            :loading="loading"
            hide-actions
            class="elevation-1"
          >
            <template v-slot:headers="props">
              <tr>
                <th class="blue darken-2 white--text">
                  <v-checkbox
                    :disabled="loading"
                    :input-value="headerCheckboxValueAll()"
                    :indeterminate="headerCheckboxValuePartial()"
                    primary
                    hide-details
                    @click.stop="toggleAll"
                  ></v-checkbox>
                </th>
                <th
                  v-for="header in props.headers"
                  :key="header.text"
                  :class="header.class"
                  :width="header.width"
                >
                  {{ header.text }}
                </th>
              </tr>
            </template>
            <v-progress-linear
              v-slot:progress
              color="blue"
              indeterminate
            ></v-progress-linear>
            <template v-slot:items="props">
              <td class="text-xs-center">
                <div class="text-xs-center">
                  <v-checkbox
                    :disabled="loading"
                    @change="changeCheckBox(props.item)"
                    :input-value="checkBoxValue(props.item)"
                    hide-details
                    v-if="props.item.status === 'N'"
                  ></v-checkbox>
                  <v-icon
                    v-if="props.item.status === 'Y'"
                    color="red"
                    @click="deleteData(props.item)"
                    medium
                    >delete</v-icon
                  >
                </div>
              </td>
              <td>{{ props.item.orderNumber }}</td>
              <td class="text-xs-left">{{ props.item.orderDate }}</td>
              <td class="text-xs-left">{{ props.item.patientName }}</td>
              <td class="text-xs-left">{{ props.item.handoverStaff }}</td>
              <td class="text-xs-left">{{ props.item.receivedBy }}</td>
            </template>
          </v-data-table>
        </div>
      </v-card>
      <v-card class="pa-2">
        <div class="text-xs-left">
          <v-pagination
            v-model="detailPage"
            :length="detailTotal"
          ></v-pagination>
        </div>
      </v-card>
    </v-layout>
    <one-dialog-print
      :title="printtitle"
      :width="printwidth"
      :height="500"
      :status="openprint"
      :urlprint="urlprint"
      @close-dialog-print="closePrint"
    ></one-dialog-print>
  </div>
</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;
}

.scroll-container {
  scroll-padding: 50px 0 0 50px;
}

::-webkit-scrollbar {
  width: 7px;
}

/* this targets the default scrollbar (compulsory) */

::-webkit-scrollbar-track {
  background-color: #73baf3;
}

/* the new scrollbar will have a flat appearance with the set background color */

::-webkit-scrollbar-thumb {
  background-color: #2196f3;
}

/* this will style the thumb, ignoring the track */

::-webkit-scrollbar-button {
  background-color: #0079da;
}

/* optionally, you can style the top and the bottom buttons (left and right for horizontal bars) */

::-webkit-scrollbar-corner {
  background-color: black;
}
</style>
<script>
module.exports = {
  //   components: {
  //     "one-dialog-info": httpVueLoader("../../common/oneDialogInfo.vue"),
  //     "one-dialog-alert": httpVueLoader("../../common/oneDialogAlert.vue"),
  //   },
  components: {
    "one-dialog-print": httpVueLoader("../../common/oneDialogPrintX.vue"),
  },
  mounted() {},
  methods: {
    closePrint() {
      this.openprint = false;
    },
    print() {
      let user = one_user();
      var d = new Date();
      var n = d.getTime();
      // https://devcpone.aplikasi.web.id/birt/run?__report=report/one/rekap/rpt_list_handover_001.rptdesign&__format=pdf&PID=4&username=joko@gmail.com&tm=1722401933188
      let rptname = "rpt_list_handover_001";
      this.urlprint =
        "/birt/run?__report=report/one/rekap/" +
        rptname +
        ".rptdesign&__format=pdf&username=" +
        user.M_StaffName +
        "&PID=" +
        this.selectedHandover.handoverID +
        "&tm=" +
        n;
      this.openprint = true;
    },
    deleteData(val) {
      if (this.loading) {
        return;
      }
      let text =
        "Apakah anda yakin menghapus data berikut " +
        val.orderNumber +
        " " +
        val.patientName +
        " ?";
      if (confirm(text)) {
        this.$store.dispatch("handover/deletehandoverdetail", val.detailID);
      } else {
        return;
      }
    },
    saveData() {
      this.$store.dispatch("handover/savehandover");
    },
    isObjectEmpty(objectName) {
      return (
        Object.keys(objectName).length === 0 &&
        objectName.constructor === Object
      );
    },
    openDialogSave() {
      if (this.selectedData.length === 0) {
        alert("Tidak ada hasil yang bisa diserahkan");
        return;
      }
      this.dialogAdd = true;
    },
    toggleAll() {
      let raw = JSON.stringify(this.selectedData);
      let arr = [...JSON.parse(raw)];
      let ckAll = this.headerCheckboxValueAll();
      for (let i = 0; i < this.handoverDetail.length; i++) {
        const element = this.handoverDetail[i];
        let foundItem = arr.find((e) => e.orderID === element.orderID);
        const index = arr.findIndex((e) => e.orderID === element.orderID);
        if (ckAll) {
          arr.splice(index, 1);
        } else {
          if (!foundItem && element.status === "N") {
            arr.push(element);
          }
        }
      }
      this.selectedData = arr;
    },
    headerCheckboxValueAll() {
      // debugger;
      let ret = 0;
      for (let i = 0; i < this.handoverDetail.length; i++) {
        const element = this.handoverDetail[i];
        let foundItem = this.selectedData.find(
          (e) => e.orderID === element.orderID
        );
        if (foundItem) {
          ret = ret + 1;
        }
      }
      if (ret === this.handoverDetail.length && ret > 0) {
        return true;
      } else {
        return false;
      }
    },
    headerCheckboxValuePartial() {
      let ret = 0;
      for (let i = 0; i < this.handoverDetail.length; i++) {
        const element = this.handoverDetail[i];
        let foundItem = this.selectedData.find(
          (e) => e.orderID === element.orderID
        );
        if (foundItem) {
          ret = ret + 1;
        }
      }
      if (ret != this.handoverDetail.length && ret > 0) {
        return true;
      } else {
        return false;
      }
    },
    changeCheckBox(val) {
      // debugger;
      let raw = JSON.stringify(this.selectedData);
      let arr = [...JSON.parse(raw)];
      if (arr.length == 0) {
        arr.push(val);
      } else {
        let foundItem = arr.find((e) => e.orderID === val.orderID);
        const index = arr.findIndex((e) => e.orderID === val.orderID);
        if (foundItem) {
          arr.splice(index, 1);
        } else {
          arr.push(val);
        }
      }
      this.selectedData = arr;
      console.log(val);
    },
    checkBoxValue(val) {
      let foundItem = this.selectedData.find((e) => e.orderID === val.orderID);
      if (foundItem) {
        return true;
      } else {
        return false;
      }
    },
    checkBoxValueFalse(val) {
      let foundItem = this.selectedData.find((e) => e.orderID === val.orderID);
      if (foundItem) {
        return false;
      } else {
        return true;
      }
    },
    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")}`;
    },

    searchForAdd() {
      this.selectedStatusDetail = "N";
      this.isAdd = true;
      this.note = this.selectedHandover.handovernote;
      this.receiver = this.selectedHandover.handoverReceivedBy;
      this.$store.commit("handover/update_detailPage", 1);
      console.log("func search for add");
      this.$store.dispatch("handover/getdetail");
    },
  },
  computed: {
    totalData() {
      return this.$store.state.handover.totalData;
    },
    totalHandover() {
      return this.$store.state.handover.totalHandover;
    },
    totalNotHandover() {
      return this.$store.state.handover.totalNotHandover;
    },
    selectedHandover: {
      get() {
        return this.$store.state.handover.selectedHandover;
      },
      set(val) {
        this.$store.commit("handover/update_selectedHandover", val);
      },
    },
    selectedStatusDetail: {
      get() {
        return this.$store.state.handover.selectedStatusDetail;
      },
      set(val) {
        this.$store.commit("handover/update_selectedStatusDetail", val);
        this.detailPage = 1;
        console.log("func selected status");

        this.$store.dispatch("handover/getdetail");
      },
    },
    note: {
      get() {
        return this.$store.state.handover.note;
      },
      set(val) {
        this.$store.commit("handover/update_note", val);
      },
    },
    receiver: {
      get() {
        return this.$store.state.handover.receiver;
      },
      set(val) {
        this.$store.commit("handover/update_receiver", val);
      },
    },
    dialogAdd: {
      get() {
        return this.$store.state.handover.dialogAdd;
      },
      set(val) {
        this.$store.commit("handover/update_dialogAdd", val);
      },
    },
    selectedData: {
      get() {
        return this.$store.state.handover.selectedData;
      },
      set(val) {
        this.$store.commit("handover/update_selectedData", val);
      },
    },
    isAdd: {
      get() {
        return this.$store.state.handover.isAdd;
      },
      set(val) {
        this.$store.commit("handover/update_isAdd", val);
      },
    },
    handoverDetail() {
      return this.$store.state.handover.handoverDetail;
    },
    detailTotal() {
      return this.$store.state.handover.detailTotal;
    },
    detailPage: {
      get() {
        return this.$store.state.handover.detailPage;
      },
      set(val) {
        this.$store.commit("handover/update_detailPage", val);
        console.log("func detail page");

        this.$store.dispatch("handover/getdetail");
      },
    },
    statusDetail: {
      get() {
        return this.$store.state.handover.statusDetail;
      },
      set(val) {
        this.$store.commit("handover/update_statusDetail", val);
      },
    },
    loading: {
      get() {
        return this.$store.state.handover.loading;
      },
      set(val) {
        this.$store.commit("handover/update_loading", val);
      },
    },
    searchDetail: {
      get() {
        return this.$store.state.handover.searchDetail;
      },
      set(val) {
        this.$store.commit("handover/update_searchDetail", val);
        this.detailPage = 1;
        console.log("func search detail");

        this.$store.dispatch("handover/getdetail");
      },
    },
    errorMsg: {
      get() {
        return this.$store.state.handover.errorMsg;
      },
      set(val) {
        this.$store.commit("handover/update_errorMsg", val);
      },
    },
    snackbarError: {
      get() {
        return this.$store.state.handover.snackbarError;
      },
      set(val) {
        this.$store.commit("handover/update_snackbarError", val);
      },
    },
    snackbarSuccess: {
      get() {
        return this.$store.state.handover.snackbarSuccess;
      },
      set(val) {
        this.$store.commit("handover/update_snackbarSuccess", val);
      },
    },
    successMsg: {
      get() {
        return this.$store.state.handover.successMsg;
      },
      set(val) {
        this.$store.commit("handover/update_successMsg", val);
      },
    },

    startDateDetailForm: {
      get() {
        return this.$store.state.handover.startDateDetail;
      },
      set(val) {
        this.$store.commit("handover/update_startDateDetail", val);
        this.detailPage = 1;
        console.log("func start date");

        this.$store.dispatch("handover/getdetail");
      },
    },
    endDateDetailForm: {
      get() {
        return this.$store.state.handover.endDateDetail;
      },
      set(val) {
        this.$store.commit("handover/update_endDateDetail", val);
        this.detailPage = 1;
        console.log("func end date");

        this.$store.dispatch("handover/getdetail");
      },
    },

    formatedStartDateDetail() {
      return this.formatDate(this.startDateDetailForm);
    },
    formatedEndDateDetail() {
      return this.formatDate(this.endDateDetailForm);
    },
  },
  watch: {
    // search_company(val, old) {
    //   if (val == old) return;
    //   if (!val) return;
    //   if (val.length < 1) return;
    //   if (this.$store.state.patient.update_autocomplete_status == 1) return;
    //   this.thr_search_company();
    // },
    // search_doctor(val, old) {
    //   if (val == old) return;
    //   if (!val) return;
    //   if (val.length < 1) return;
    //   if (this.$store.state.patient.update_autocomplete_status == 1) return;
    //   this.thr_search_doctor();
    // },
    // search_test(val, old) {
    //   if (val == old) return;
    //   if (!val) return;
    //   if (val.length < 1) return;
    //   if (this.$store.state.patient.update_autocomplete_status == 1) return;
    //   this.thr_search_test();
    // },
    searchhandoverHeaderCopy(val, old) {
      if (val == old) return;
      if (!val) return;
      if (val.length < 1) return;
      this.thrsearchphautocomplete();
    },
  },
  data() {
    return {
      printtitle: "",
      printwidth: "80%",
      openprint: false,
      urlprint: "",
      searchhandoverHeaderCopy: "",
      selected_delivery: {},
      search_company: "",
      search_test: "",
      menuFormDateStart: false,
      menuFormDateEnd: false,
      date: new Date().toISOString().substr(0, 10),
      dialogAct: "add",
      items: [],
      menuFormDateEnd: false,
      menuFormDateStart: false,
      errors: [],
      sheet: false,
      indeterminatex: false,
      checkednotall: false,
      bar_chx_all: false,
      selected_barcode: [],
      dialogtimeline: false,
      search_doctor: "",
      headers: [
        {
          text: "NOMOR",
          align: "center",
          sortable: false,
          value: "lab",
          width: "15%",
          class: "pa-2 blue darken-2 white--text",
        },
        {
          text: "TGL. ORDER",
          align: "center",
          sortable: false,
          value: "lab",
          width: "15%",
          class: "pa-2 blue darken-2 white--text",
        },
        {
          text: "NAMA",
          align: "center",
          sortable: false,
          value: "lab",
          width: "25%",
          class: "pa-2 blue darken-2 white--text",
        },
        {
          text: "STAFF",
          align: "center",
          sortable: false,
          value: "name",
          width: "20%",
          class: "pa-2 blue darken-2 white--text",
        },
        {
          text: "PENERIMA",
          align: "center",
          sortable: false,
          value: "name",
          width: "20%",
          class: "pa-2 blue darken-2 white--text",
        },
      ],
    };
  },
};
</script>
