<template>
   <v-layout class="fill-height" column>
      <v-dialog v-model="dialogsuccess" persistent  max-width="450">
        <v-card>
            <v-card-title color="success"  class="headline">Berhasil !</v-card-title>
            <v-card-text>
                {{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-dialog v-model="xdialogaction" persistent  max-width="350">
            <v-card>
                <v-card-title color="warning"  class="headline">Konfirmasi</v-card-title>
                <v-card-text v-html="xmsgaction">
                    
                </v-card-text>
                <v-card-actions>
                <v-spacer></v-spacer>
                    <v-btn color="primary darken-1" flat @click="closeDialogAction()">OK</v-btn>
                    <v-btn color="error darken-1" flat @click="xdialogaction = false">Tutup</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
      <v-dialog v-model="dialogbarcode" persistent  max-width="490">
        <v-card>
            <v-card-title style="color:#fff" class="headline grey darken-1">Cetak Barcode</v-card-title>
            <v-card-text>
               <v-layout pa-2 class="grey lighten-2" row>
                  <v-flex xs1>
                     <v-checkbox style="padding-top:0;margin-top:0"
                        hide-details
                        color="grey darken-1"
                        :indeterminate="indeterminatex"
                        @change="changeCbxAll(bar_chx_all)"
                        v-model="bar_chx_all"
                     ></v-checkbox>
                  </v-flex>
                  <v-flex xs5>
                     SPECIMEN
                  </v-flex>
                  <v-flex xs4>
                     BARCODE
                  </v-flex>
                  <v-flex xs2>
                     CETAK
                  </v-flex>
               </v-layout>
               <v-layout align-center pa-2 v-for="(vs,idx) in barcodes" :key="vs.id" class="grey lighten-4" row>
                 
                  <v-flex xs1>
                     <v-checkbox style="padding-top:0;margin-top:0"
                        color="grey darken-1"
                        hide-details
                        v-model="vs.chex"
                        @change="checkTop()"
                     ></v-checkbox>
                  </v-flex>
                  <v-flex class="text-xs-left" xs1>
                     <v-btn @click="addNewLabel(vs)" small style="margin:0;min-width:15px" class="white--text" color="grey darken-1"><v-icon small>add</v-icon></v-btn>
                  </v-flex>
                  <v-flex xs4>
                    {{vs.T_SampleTypeName}}
                  </v-flex>
                  <v-flex xs4>
                     {{vs.T_BarcodeLabBarcode}}
                  </v-flex>
                  <v-flex xs2>
                     <span @click="printSingleBarcode(vs)" class="icon-medium-fill-base-small xs1 white--text grey darken-1  ml-1 icon-print"></span>
                  </v-flex>
               </v-layout>
            </v-card-text>
            <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="grey darken-1" flat @click="dialogbarcode = false">Tutup</v-btn>
            <v-btn dark color="grey darken-3"  @click="printRobo">Cetak Robo </v-btn>
            <v-btn dark color="grey darken-1"  @click="printMultipleBarcode">Cetak terpilih [ {{selected_barcode.length}} ]</v-btn>
            
            </v-card-actions>
        </v-card>
      </v-dialog>
      <v-card   class="mb-2 pa-2 searchbox">
         <v-layout row >
            <v-flex xs4 pr-2>
               <v-menu 
                          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="mt-1"
                              v-model="filterComputedDateFormattedStart"
                              label="Tanggal Awal"
                              outline
                              hide-details
                              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 xs4 pr-2>
               <v-menu
                          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="mt-1"
                              v-model="filterComputedDateFormattedEnd"
                              label="Tanggal Akhir"
                              outline
                              readonly
                              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 xs4 mt-1>
                      <v-text-field 
                             
                             label="Cari ..."
                             placeholder="No Reg / Nama"
                             outline
                             v-on:keyup.enter="searchTransaction"
                             v-model="search"
                             hide-details
                             ></v-text-field>
            </v-flex>
            <!--<span @click="searchTransaction"  class="icon-medium-fill-base xs1 white--text success iconsearch-search"></span>-->
            
         </v-layout>
      </v-card>
      <v-card >
         <v-layout row>
            <v-flex xs12 pl-2 pr-2 pt-2 pb-2>
               <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)}" @click="selectMe(props.item)">{{ props.item.M_PatientNoReg }}</td>
                     <td class="pa-2" v-bind:class="{'amber lighten-4':isSelected(props.item)}" @click="selectMe(props.item)">{{ props.item.T_OrderHeaderLabNumber}}</td>
                     <td class="text-xs-left pa-2" v-bind:class="{'amber lighten-4':isSelected(props.item)}" @click="selectMe(props.item)">{{ props.item.M_PatientName}}</td>
                     <td class="text-xs-center pa-2" v-bind:class="{'amber lighten-4':isSelected(props.item)}" @click="selectMe(props.item)">
                        <v-btn dark color="grey darken-1" small @click="openbarcodeprint(props.item)">Cetak Barcode</v-btn>
                     </td>
                  </template>
               </v-data-table>
               <v-divider></v-divider>
               <v-pagination
                  style="margin-top:10px;margin-bottom:10px"
                  v-model="curr_page"
                  :length="xtotal_page"
               
               
               ></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:40px;
}
.searchbox .v-btn {
   min-height:40px;
}
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() {
      //this.$store.dispatch("form/getalmaries")
      this.$store.dispatch("done/search",{
         startdate:this.xdatestart,
         enddate: this.xdateend,
         search:this.search,
         current_page:1,
         lastid:-1
      })
   },
   methods : {
      addNewLabel(sampletype){
         this.$store.commit("done/update_selected_sampletype",sampletype)
         var sample = sampletype.T_SampleTypeName
         var patient = this.$store.state.done.selected_transaction
         console.log(patient)
         var msg = "Anda yakin akan melakukan penambahan label spesimen "+sample+" untuk pasien "+patient.M_PatientName+" ? "
         this.$store.commit("done/update_msg_action",msg)
         this.$store.commit("done/update_dialog_action",true)
      },
      changeCbxAll(value){
         var arr = this.barcodes
         this.indeterminatex = false
         arr.forEach((el)=>{el.chex = value})
         var selected =  _.filter(arr, function(o) { return o.chex; })
         this.selected_barcode = selected
      },
      printSingleBarcode(value){
         var label = value.T_BarcodeLabBarcode
         if(value.type === 'barcode')
            this.$store.dispatch("done/printbarcode_log",{label:label,value:0,'type':'pk'})//one_print_barcode_pk(label)
         else
            this.$store.dispatch("done/printbarcode_log",{label:label,value:value.id,'type':'formulir'})//one_print_barcode_formulir(value.id)
      },
      printRobo() {
         var arr = this.barcodes
         var xarrtojoin = []
         _.forEach(arr, function(value) {
            if( value.type === 'barcode'){
               xarrtojoin.push(value.T_BarcodeLabBarcode)
            }
         })
         if(xarrtojoin.length > 0 ){
            this.$store.dispatch("done/printbarcode_log",{label:xarrtojoin.join(','),value:0,'type':'robo'})//one_print_robo(xarrtojoin.join(','))
         }
      },
      printMultipleBarcode(){
         var arr = this.barcodes
         var xarrtojoin = []
         var xformulir = {}
         _.forEach(arr, function(value) {
            //console.log(value)
            if(value.chex && value.type === 'barcode'){
               xarrtojoin.push(value.T_BarcodeLabBarcode)
            }
            if(value.chex && value.type === 'formulir'){
               xformulir = value
            }
         })
         if(xarrtojoin.length > 0 ){
            this.$store.dispatch("done/printbarcode_log",{label:xarrtojoin.join(','),value:0,'type':'pk'})//one_print_barcode_pk(xarrtojoin.join(','))
         }
         
         if(!_.isEmpty(xformulir)){
            //console.log("oeoeooeoe")
            this.$store.dispatch("done/printbarcode_log",{label:'',value:xformulir.id,'type':'formulir'})//one_print_barcode_formulir(xformulir.id)
         }
            
      },
      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.ohid == this.$store.state.done.selected_transaction.ohid
      },
      searchTransaction() {
         this.$store.dispatch("done/search",{
            startdate:this.xdatestart,
            enddate: this.xdateend,
             search:this.search,
            current_page:1,
            lastid:-1
         })
      },
      selectMe(trx) {
         if(this.$store.state.done.no_save == 0 ){
            console.log(trx)
            this.$store.commit("done/update_selected_transaction",trx)
            this.$store.commit("done/update_act",'edit')
           
         }else{
            this.$store.commit("done/update_open_alert_confirmation",true)
         }
      },
      closeAlertConfirmation(){
          this.$store.commit("done/update_open_alert_confirmation",false)
      },
      forgetAlertConfirmation(){
          this.$store.commit("done/update_no_save",0)
          this.$store.commit("done/update_open_alert_confirmation",false)
      },
      updateAlert_success(val){
         this.$store.commit("done/update_alert_success",val)
      },
      setNewTransaction(){
         this.$store.commit("done/update_selected_transaction",{})
         this.$store.commit("done/update_act",'new')
         
      },
      closeDialogSuccess(){
         let arrtrx = this.$store.state.done.transactions
         var idx = _.findIndex(arrtrx, item => item.T_SampleStorageID === this.$store.state.done.last_id)
         console.log(idx)
         this.$store.dispatch("done/search",{
            startdate:this.xdatestart,
            enddate: this.xdateend,
             search:this.search,
            current_page:1,
            lastid: idx
         })
         this.$store.commit("done/update_dialog_success",false)
      },
      closeDialogInfo(){
         this.$store.commit("done/update_open_dialog_info",false)
      },
      openbarcodeprint(value){
         this.bar_chx_all = false
         this.indeterminatex = false
         this.dialogbarcode = true
         this.selected_barcode = []
         this.$store.dispatch("patient/lookup_barcodes",value)
      },
      checkTop(){
        var barcodes = this.barcodes
        var selected =  _.filter(barcodes, function(o) { return o.chex; })
        this.bar_chx_all = false
        this.indeterminatex = false
        if(selected.length > 0 && barcodes.length === selected.length){
           this.bar_chx_all = true
           this.indeterminatex = false
        }
        if(selected.length > 0 && barcodes.length > selected.length){
           this.bar_chx_all = false
           this.indeterminatex = true
        }
         this.selected_barcode = selected
         
      },
      closeDialogAction(){
         var prm = this.$store.state.done.selected_sampletype
         this.$store.dispatch("patient/addnewlabel",prm)
         
      },
      
   },
   computed: {
      xdialogaction:{
         get() {
               return this.$store.state.done.dialog_action
         },
         set(val) {
               this.$store.commit("done/update_dialog_action",val)
         }
      },
      xmsgaction:{
         get() {
               return this.$store.state.done.msg_action
         },
         set(val) {
               this.$store.commit("done/update_msg_action",val)
         }
      },
      search: {
         get() {
            return this.$store.state.done.search
         },
         set(val) {
            this.$store.commit("done/update_search",val)
         }
      },
      dialogsuccess: {
         get() {
            return this.$store.state.done.dialog_success
         },
         set(val) {
            this.$store.commit("done/update_dialog_success",val)
         }
      },
      msgsuccess(){
         return this.$store.state.done.msg_success
      }, 
      snackbar: {
         get() {
            return this.$store.state.done.alert_success
         },
         set(val) {
            this.$store.commit("done/update_alert_success",val)
         }
      },
      barcodes: {
         get() {
            return this.$store.state.patient.barcodes
         },
         set(val) {
            this.$store.commit("done/update_patient_barcodes",val)
         }
      },
      isLoading() {
         return this.$store.state.done.search_status == 1
      },
      xdatestart : {
         get() {
            return this.$store.state.done.start_date
         },
         set(val) {
            this.$store.commit("done/update_start_date",val)
            this.searchTransaction()
         }
      },
      xdateend : {
         get() {
            return this.$store.state.done.end_date
         },
         set(val) {
            this.$store.commit("done/update_end_date",val)
            this.searchTransaction()
         }
      },
      filterComputedDateFormattedStart () {
         return this.formatDate(this.xdatestart)
      },
      filterComputedDateFormattedEnd () {
         return this.formatDate(this.xdateend)
      },
      xtransactions() {
         console.log(this.$store.state.done.transactions)
         return this.$store.state.done.transactions
      },
      openalertconfirmation: {
         get() {
            return this.$store.state.done.open_alert_confirmation
         },
         set(val) {
            this.$store.commit("done/update_open_alert_confirmation",val)
         }
      },
      opendialoginfo: {
            get() {
                  return this.$store.state.done.open_dialog_info
            },
            set(val) {
                  this.$store.commit("done/update_open_dialog_info",false)
            }
      },
      msginfo(){
            return this.$store.state.done.msg_info
      },
      curr_page: {
         get() {
            return this.$store.state.done.current_page
         },
         set(val) { 
            this.$store.commit("done/update_current_page",val)
            this.$store.dispatch("done/search",{
                  startdate:this.xdatestart,
                  enddate: this.xdateend,
                  current_page:val,
                  lastid:-1
            })
         }
      },
      xtotal_page: {
         get() {
            return this.$store.state.done.total_page
         },
         set(val) {
            this.$store.commit("done/update_total_page",val)
         }
      },
   },
   data() {
      return {
         msgalertconfirmation:"Perubahan yang telah dilakukan belum disimpan dong !",
         menufilterdatestart:false,
         menufilterdateend:false,
         dialogbarcode:false,
         date: new Date().toISOString().substr(0, 10),
         items: [],
         name: '',
         page:1,
         indeterminatex:false,
         checkednotall:false,
         bar_chx_all:false,
         selected_barcode:[],
         headers: [
            {
               text: "PID",
               align: "left",
               sortable: false,
               value: "mr",
               width: "10%",
               class: "pa-2 grey darken-1 white--text"
            },
            {
               text: "NO REG",
               align: "left",
               sortable: false,
               value: "lab",
               width: "12%",
               class: "pa-2 grey darken-1 white--text"
            },
            {
               text: "NAMA",
               align: "left",
               sortable: false,
               value: "name",
               width: "20%",
               class: "pa-2 grey darken-1 white--text"
            },
            {
               text: "AKSI",
               align: "center",
               sortable: false,
               value: "status",
               width: "15%",
               class: "pa-2 grey darken-1 white--text"
            }
         ],
         pagination:{
            descending: false,
            page: 1,
            rowsPerPage: 5,
            sortBy: 'T_SampleStorageDate',
            totalItems: this.$store.state.done.total_transactions
         }
      };
   }
}
</script>
