<template>
      <div>
            <v-dialog v-model="dialog_card" width="65%">
                  <v-card>
                        <v-card-title class="teal subheading  white--text pt-2 pb-2" primary-title align-center>
                              <span class="font-weight-thin">KARTU ANGGOTA</span>
                        </v-card-title>
                        <v-card-text class="pt-2 pb-1">
                              <v-layout>
                                    <v-flex xs12>
                                          <object :data="rpt_card" width="100%" height="512px"></object>
                                    </v-flex>
                              </v-layout>
                        </v-card-text>
                  </v-card>
            </v-dialog>
            <v-layout>
                  <v-flex xs12>
                        <v-card tile flat color=" pa-2 teal lighten-4">
                              <h5 class=" subtitle-1 font-weight-bold">DAFTAR PASIEN</h5>
                        </v-card>
                  </v-flex>
            </v-layout>
            <v-layout>
                  <v-flex xs12>
                        <table>
                              <tr style="background:#64b2cd">
                                    <th style="width:5%;font-weight:bold;font-size:12px;color:#fff" class="text-md-center pt-2 pb-2"></th>
                                    <th style="width:15%;font-weight:bold;font-size:12px;color:#fff" class="text-md-center pt-2 pb-2">NAMA</th>
                                    <th style="width:30%;font-weight:bold;font-size:12px;color:#fff" class="text-md-center pt-2 pb-2">ALAMAT</th>
                                    <th style="width:30%;font-weight:bold;font-size:12px;color:#fff" class="text-md-center pt-2 pb-2">ALAMAT HS</th>
                                    <th style="width:15%;font-weight:bold;font-size:12px;color:#fff" class="text-md-center pt-2 pb-2">NO. HP</th>
                                    <th style="width:5%;font-weight:bold;font-size:12px;color:#fff" class="text-md-center pt-2 pb-2">AKSI</th>
                              </tr>
                              <tr v-if="s_patient.length === 0">
                                    <td class="pa-2 text-xs-center caption" colspan="6">Belum ada data pasien</td>
                              </tr>
                              <tr v-if="s_patient.length > 0" style="font-size:12px" v-for="p in s_patient" v-bind:key="p.M_PatientID">
                                    <td class="text-md-center pl-3">
                                          <v-checkbox style="padding-top:0;margin-top:0" color="blue lighten-3" hide-details v-model="p.M_PatientIsDefault" @change="checkTop(p)"></v-checkbox>
                                    </td>
                                    <td class="text-md-left pl-3">
                                          <p class="mb-1">{{ p.M_PatientName}}</p>
                                    </td>
                                    <td class="text-md-left pl-3">{{ p.M_PatientAddress }}</td>
                                    <td class="text-md-left pl-3">{{ p.alamaths }}</td>
                                    <td class="text-md-right mono pr-2">{{ p.M_PatientHP }}</td>
                                    <td class="text-md-center">
                                          <v-icon color="#ee7777" @click="deletePasien(p)">delete</v-icon>
                                    </td>
                              </tr>
                        </table>
                  </v-flex>
            </v-layout>
            <v-layout>
                  <v-flex xs12>
                        <v-card tile flat color=" pa-2 teal lighten-4">
                              <h5 class=" subtitle-1 font-weight-bold">ALAMAT HOME SERVICE</h5>
                        </v-card>
                  </v-flex>
            </v-layout>
            <v-layout>
                  <v-flex xs12>
                        <v-btn v-if="this.hspatientid > 0" color="blue" dark class="one-btn-icon ma-1" @click="add_hsaddress">
                              TAMBAH ALAMAT HOME SERVICE
                        </v-btn>
                  </v-flex>
            </v-layout>
            <v-layout mt-1 row wrap>
                  <v-flex class="row" ma-1 xs11 v-for="(a,idx) in s_address">
                        <v-layout align-center row>
                              <v-flex xs1>
                                    <v-btn v-if="a.chex  === 'N'" @click="changeBoxRight(a,idx)" dark style="min-width:20px" small color="grey darken-1">
                                          <v-icon small>close</v-icon>
                                    </v-btn>
                                    <v-btn v-if="a.chex  === 'Y'" @click="changeBoxRight(a,idx)" depressed style="min-width:20px" small color="teal lighten-4">
                                          <v-icon color="teal" small>check</v-icon>
                                    </v-btn>
                              </v-flex>
                              <v-flex mb-1 pl-2 xs11>
                                    <p v-if="a.chex  === 'Y'" class="mb-0 font-weight-black" style="font-size:12px">
                                          {{a.HS_AddressLabel}} | Jarak : {{distance_km_list}} km, Biaya : {{hspricelist}} 
                                    </p> 
                                    <p v-if="a.chex  === 'N'" class="mb-0 font-weight-black" style="font-size:12px">
                                          {{a.HS_AddressLabel}}
                                    </p> 
                                    <p class="mb-0 font-weight-black" style="font-size:11px">
                                          {{a.HS_AddressAddress}}
                                    </p>
                              </v-flex>
                        </v-layout>
                  </v-flex>
            </v-layout>

            <v-dialog v-model="dialog_hsaddress" width="65%">
                  <v-layout align-center row>
                        <v-flex xs12>
                              <v-card tile flat color=" pa-2 teal lighten-4">
                                    <h5 class=" subtitle-1 font-weight-bold">ALAMAT</h5>
                              </v-card>
                        </v-flex>
                  </v-layout>
                  <v-card-text class="pt-2 pb-2" style="background:white">
                        <v-form ref="formregionalbranch" v-model="validbranch" lazy-validation>
                        <v-layout row wrap>

                              <v-flex xs12>

                                    <v-layout>


                                          <v-flex xs9>
                                                <v-flex xs12>
                                                      <v-layout class="text-truncate" pt-2>
                                                            <v-flex xs8 pa-1>
                                                                  <label>
      Place:
      <gmap-autocomplete
      style="border:1px solid #bdbdbd;width:400px;height:40px"
        @place_changed="setPlace">
      </gmap-autocomplete>
      
    <br/>
                                                </v-flex>
                                                <v-flex xs4 pa-1>Jarak : {{this.distance_km}} km, Biaya : {{hsprice}}
                                                </v-flex>
                                                <v-flex xs2 pa-1>
                                                </v-flex>
                                                <v-flex xs2 pa-1>
                                                </v-flex>
                                                <v-flex xs3 pa-1>
                                               </v-flex>
                                          </v-layout>

                                    </v-flex>

<v-flex xs12 pa-1>
                                     <gmap-map
                        :center='center'
                        :zoom='16'
                        style='width:100%;  height: 400px;'
                        >
                        <gmap-marker
                            :key="index"
                            v-for="(m, index) in markers"
                            :position="m.position"
                            :clickable="true"
                            :draggable="true"
                            @dragend="updateCoordinates" 
                            @click="center=m.position"
                         
                        />
                      </gmap-map>
                      </v-flex>
                                    <v-flex xs12 pa-1>
                                    </v-flex>
                                    <v-flex xs12 pa-1>
                                    <v-text-field v-model="hslabel" label="Label" style="font-size:12px;padding:4px 0" placeholder="misal : Alamat Rumah/Kantor" :rules="labelRules" required></v-text-field>
                                    </v-flex>
                                    <v-flex xs12 pa-1>
                                    <v-textarea v-model="hsaddress" readonly style="font-size:12px;padding:4px 0" auto-grow rows="3" label="Alamat" :rules="alamatRules" required></v-textarea>
                                    </v-flex> 
                                    <v-flex xs12 pa-1>
                                    <v-textarea v-model="hsdetailaddress" style="font-size:12px;padding:4px 0" auto-grow rows="3" label="Catatan"></v-textarea>
                                    </v-flex>
                                    <v-checkbox v-model="hsisutama" label="Sebagai Alamat HS Utama"></v-checkbox>
                                    <v-flex xs12 pa-1>
                                    </v-flex>

                              </v-flex>
                        </v-layout>

                  </v-flex>
            </v-layout>
            <v-card-actions>
                        <v-spacer></v-spacer>
                        <v-btn color="primary" flat @click="dialog_hsaddress = false">
                            Tutup
                        </v-btn>
                        <v-btn color="primary" flat @click="saveHsAddress()">
                            Simpan
                        </v-btn>
                    </v-card-actions>
                  </v-form>
                </v-card>
            </v-dialog>
            
            

      </div>
</template>

<style scoped>
      .v-messages {
            display: none;
      }

      .v-input__slot {
            margin-bottom: 0px;
      }
.nota {
   font-size: 2em;
   font-weight: bold;
   text-align: left;
}
.total {
   min-height:76px;
}
table {
   font-family: arial, sans-serif;
   border-collapse: collapse;
   width: 100%;
   background:white;
   border: 0px;
}

th, td {
   border: 1px solid black;
   border-collapse: collapse;
   padding-top: 2px;
   padding-bottom: 2px;
}
table>tr>td {
   padding: 8px;
}
table>tr>td:first {
   padding-left:15px!important;
}

.vintage-text{
   text-shadow: 0px -2px 0px #fff, 0px 2px 3px #fff;
}

.v-input--selection-controls {
    margin-top: 0px;
    padding-top: 0px;
}

</style>

<script>
      module.exports = {
            components: {
                  'order-search-dialog': httpVueLoader('./orderSearchDialog.vue'),
                  'order-history-dialog': httpVueLoader('./orderHistoryDialog.vue'),
                  'order-photo-dialog': httpVueLoader('./oneDialogPhoto.vue')
            },
            data() {
                  return {
                        new_lat:null,
                        new_lng:null,
                        harga_hs_now:0,
                        idx_address:-1,
                        showinfo: false,
                        dialog_card: false,
                        rpt_card: '',
                        places: null,
      lat:null,
      lng:null,
      new_address:[],
      markers:[],
      current_pdefault_change: [],
      distance_km:0,
      validbranch: false,
      labelRules: [
                    v => !!v || 'Label harus diisi'
                ],
                alamatRules : [
                    v => !!v || 'Alamat harus diisi'
                ]
                  };
            },
            computed: {
                  diagnosa: {
                        get() {
                              return this.$store.state.order.diagnosa
                        },
                        set(val) {
                              this.$store.commit('order/update_diagnosa', val)
                        }
                  },
                  dialog_hsaddress: {
                        get() {
                              return this.$store.state.patient.dialog_hsaddress
                        },
                        set(val) {
                              this.$store.commit('patient/update_dialog_hsaddress', val)
                        }
                  },
                  patient() {
                        return this.$store.state.patient.selected_patient
                  },
                  s_patient() {
                        return this.$store.state.patient.s_patient
                  },
                  s_address() {
                        return this.$store.state.patient.s_address
                  },
                  hsprice: {
                        get() {
                              return this.$store.state.order.hsprice
                        },
                        set(val) {
                              this.$store.commit('order/update_hsprice', val)
                        }
                  },
                  hspricelist: {
                        get() {
                              return this.$store.state.order.hspricelist
                        },
                        set(val) {
                              this.$store.commit('order/update_hspricelist', val)
                        }
                  },
                  distance_km_list: {
                        get() {
                              return this.$store.state.order.distance_km_list
                        },
                        set(val) {
                              this.$store.commit('order/update_distance_km_list', val)
                        }
                  },
                  hs_lat: {
                        get() {
                              return this.$store.state.order.hs_lat
                        },
                        set(val) {
                              this.$store.commit('order/update_hs_lat', val)
                        }
                  },
                  hs_lang : {
                        get() {
                              return this.$store.state.order.hs_lang
                        },
                        set(val) {
                              this.$store.commit('order/update_hs_lang', val)
                        }
                  },
                  hspatientid: {
                        get() {
                              return this.$store.state.patient.hspatientid
                        },
                        set(val) {
                              this.$store.commit('patient/update_hspatientid', val)
                        }
                  },
                  hslabel: {
                        get() {
                              return this.$store.state.patient.hslabel
                        },
                        set(val) {
                              this.$store.commit('patient/update_hslabel', val)
                        }
                  },
                  hsaddress: {
                        get() {
                              return this.$store.state.patient.hsaddress
                        },
                        set(val) {
                              this.$store.commit('patient/update_hsaddress', val)
                        }
                  },
                  hsdetailaddress: {
                        get() {
                              return this.$store.state.patient.hsdetailaddress
                        },
                        set(val) {
                              this.$store.commit('patient/update_hsdetailaddress', val)
                        }
                  },
                  hsisutama: {
                        get() {
                              return this.$store.state.patient.hsisutama
                        },
                        set(val) {
                              this.$store.commit('patient/update_hsisutama', val)
                        }
                  },
                  center: {
                        get() {
                              return this.$store.state.order.center
                        },
                        set(val) {
                              this.$store.commit('order/update_center', val)
                        }
                  },
                  hs_addressidlist: {
                        get() {
                              return this.$store.state.patient.hs_addressidlist
                        },
                        set(val) {
                              this.$store.commit('patient/update_hs_addressidlist', val)
                              // console.log('hs_addressidlist')
                              
                        }
                  },
                  origin_lat: {
                        get() {
                              return this.$store.state.order.origin_lat
                        },
                        set(val) {
                              this.$store.commit('order/update_origin_lat', val)
                        }
                  },
                  origin_lang : {
                        get() {
                              return this.$store.state.order.origin_lang
                        },
                        set(val) {
                              this.$store.commit('order/update_origin_lang', val)
                        }
                  },
                  patient_note: {
                        get() {
                              return this.$store.state.order.patient_note
                        },
                        set(val) {
                              this.$store.commit('order/update_patient_note', val)
                        }
                  },

                  patient_age: {
                        get() {
                              return this.$store.state.patient.selected_patient.patient_age
                        },

                        set(v) {
                              return
                        }
                  },

                  patient_dob() {
                        try {
                              return this.$store.state.patient.selected_patient.M_PatientDOB.split('-').reverse()
                                    .join('-')
                        } catch (e) {}

                  },
                  patient_photo() {
                        return this.$store.state.photo.photo_url
                  },
            },
            methods: {
                  checkTop(pat) {
                let patients = this.$store.state.patient.s_patient
                let idx = _.findIndex(patients, function (p) {
                    return p.M_PatientID == pat.M_PatientID
                });
                patients.forEach(function(t,idx) {
                  if (t.M_PatientID == pat.M_PatientID) {
                     t.M_PatientIsDefault = true
                  }else{
                      t.M_PatientIsDefault = false  
                  }
               })
               /* patients[idx].M_PatientIsDefault = !patients[idx].M_PatientIsDefault
                var selected = _.filter(patients, function (o) {
                    return o.M_PatientIsDefault;
                })
                */
                this.$store.commit("delivery/update_data_deliveries",'')
                this.$store.commit("patient/update_hspatientid", pat.patientidhs)
                this.$store.commit("patient/update_hs_name", pat.M_PatientName)
                
                var t_hshp = pat.M_PatientHP
                var hshp = t_hshp.replace("/", "|");
                if(hshp.match(/^.*,.*$/)){
                  var M_PatientHP = hshp.split(",")[0]
                }else if(hshp.match(/^.*|.*$/)){
                  var M_PatientHP = hshp.split("|")[0]
                }else{
                  M_PatientHP = pat.M_PatientHP
                }
                
                this.$store.commit("patient/update_hs_hp", M_PatientHP)
                this.$store.commit("delivery/update_xpatientid", pat.M_PatientID)
                this.$store.dispatch('delivery/search_deliveries',{type:'patient',id:pat.M_PatientID})
                this.$store.dispatch('patient/search_hsaddress',{patientid:pat.patientidhs})

            },
            changeBoxRight(p,i) {
                let saddress = this.$store.state.patient.s_address
                var _this = this
                saddress.forEach(function(t,idx) {
                  if (t.HS_AddressID == p.HS_AddressID) {
                     t.chex = 'Y'    
                     _this.getDistanceList(p.HS_AddressLat,p.HS_AddressLng)
                  }else{
                      t.chex = 'N'  
                  }
               })
               
               // this.$store.commit("patient/update_hs_price", p.hsprice)
                this.$store.commit("patient/update_hs_addressid", p.HS_AddressID)

                let tests = this.s_patient
                testvisit = 0
                testcovid = 0
                tests.forEach(function (t, idx) {
                    let visit = t.testvisit
                    let covid = t.testcovid
                    testvisit += visit
                    testcovid += covid
                })
                if(testcovid === 0 && testvisit > 0){
                    let visit = (this.$store.state.patient.hs_config.HS_ConfigSecondVisitPercent/100) * this.$store.state.patient.hs_price
                    this.$store.commit("patient/update_hs_priceother", visit)

                }
            },
                  deletePasien(patient) {
                  this.$store.dispatch("patient/delete_patient", patient)
                  },
                  update_photo() {
                        this.$store.commit('photo/update_dialog_photo', true)
                  },
                  edit_patient() {
                        this.$store.commit('patient/update_edit', true)
                        this.$store.commit('patient/update_patient_new_dialog_is_active', true)
                  },
                  saveHsAddress () {
                        
                this.$store.commit('patient/update_s_address', [])
                if (this.$refs.formregionalbranch.validate()) {
                let prm = {
                patientid : this.hspatientid,
                label : this.hslabel,
                address : this.hsaddress,
                detail : this.hsdetailaddress,
                lat : this.new_lat,
                long : this.new_lng,
                isutama : this.hsisutama === true ? "Y" : "N"
           }
           this.$store.dispatch('patient/save_hsaddress', prm)
      }
           
       },
                  getHistories(visit) {
                        console.log(visit)
                        if (parseInt(visit) > 1) {
                              this.$store.dispatch('history/search')
                        }
                  },
                  generate_card() {
                        var xid = this.$store.state.patient.selected_patient.M_PatientID
                        this.rpt_card =
                              "/birt/run?__report=report/one/fo/rpt_card.rptdesign&__format=pdf&username=admin%20&PID=" +
                              xid
                        this.dialog_card = true
                  },
                  add_hsaddress() {
                        this.dialog_hsaddress = true
                        this.hslabel = ''
                        this.hsaddress = ''
                        this.hsdetailaddress = ''
                        this.hsisutama = false
                        
                  },
      setDescription(description) {
        this.description = description;
      },
      getDistance(destination){
       var origin = {"lat":this.origin_lat, "lng":this.origin_lang};
       var destination = {"lat":destination.lat, "lng":destination.lng};
        //var origin = "'"+this.origin_lat+","+this.origin_lang+"'"
		    //var destination = "'"+destination.lat+","+destination.lng+"'"
                this.lat = destination.lat;
                this.lng = destination.lng;
        console.log(origin)
        console.log(destination)

        
        var service = new google.maps.DistanceMatrixService();
        service.getDistanceMatrix(
          {
            origins: [origin],
            destinations: [destination],
            travelMode: "DRIVING",
            avoidHighways: false,
            avoidTolls: false
          }, this.callback);

      },
      callback(response, status) {
        if (status != google.maps.DistanceMatrixStatus.OK) {
              alert('Error was: biasa ' + status);
        } else {
              
            console.log(response)
            var totalDistance = response.rows[0].elements[0].distance.value;
           var totalTime = response.rows[0].elements[0].duration.value;
           var distance_km = Math.round((totalDistance/1000)  * 10) / 10
            this.distance_km = distance_km
           console.log(distance_km)
           console.log(this.lat)
           this.$store.dispatch('order/search_hsprice',{distance_km: this.distance_km,lat:this.lat,long:this.lng,origin_lat:this.origin_lat,origin_lang:this.origin_lang})
        
              
        }
      },
      setPlace(place) {
        var newaddrs = this.new_address
        newaddrs.address = place.formatted_address
        this.$store.commit('patient/update_hsaddress', place.formatted_address)
        newaddrs.details = ''
        newaddrs.lat = place.geometry.location.lat()
        newaddrs.lng =  place.geometry.location.lng()
        this.new_lat = place.geometry.location.lat()
        this.new_lng = place.geometry.location.lng()
        const marker = {
          lat: place.geometry.location.lat(),
          lng: place.geometry.location.lng()
        };
        this.lat = place.geometry.location.lat()
        this.lng = place.geometry.location.lng()
        this.markers = []
        this.markers.push({ position: marker });
        this.places = []
        this.places.push(this.currentPlace);
        this.center = marker;
        this.getDistance(newaddrs)

    },
    getDistanceList(lat,lng){


      //alert('getDistanceList')
      var xlat = 1* lat//parseFloat(lat).toFixed(8)
 var xlng  = 1*lng//parseFloat(lng).toFixed(8)
 
      var origin = {lat:this.origin_lat,lng:this.origin_lang};
      var destination = {lat:Number(parseFloat(lat).toFixed(8)),lng:Number(parseFloat(lng).toFixed(8))};
     // var destination = {lat:xlat,lng:xlng}
                this.lat = destination.lat;
                this.lng = destination.lng;
                //console.log(xlat)
                //console.log(origin)
                console.log("hahah")
                console.log(typeof destination.lat)
        console.log(destination)
        var service = new google.maps.DistanceMatrixService();
        service.getDistanceMatrix(
          {
            origins: [origin],
            destinations: [destination],
            travelMode: "DRIVING",
            avoidHighways: false,
            avoidTolls: false
          }, this.callbackList);

      },
      callbackList(response, status) {
        if (status != google.maps.DistanceMatrixStatus.OK) {
              alert('Error was list: ' + status);
        } else {
              
            

            var totalDistance = response.rows[0].elements[0].distance.value;
           var totalTime = response.rows[0].elements[0].duration.value;
           var distance_km = Math.round((totalDistance/1000)  * 10) / 10
            this.distance_km_list = distance_km
            console.log('distance km list')
            console.log(this.distance_km_list)
            
            console.log(this.origin_lat)
            console.log(this.origin_lang)
            console.log(this.lat)
            console.log(this.lng)
            console.log(this.origin_lat)
            this.$store.dispatch('order/search_hspricelist',{distance_km: this.distance_km_list,lat:this.lat,long:this.lng,origin_lat:this.origin_lat,origin_lang:this.origin_lang})
        
              
        }
      },
    updateCoordinates(location) {
      this.center = {
        lat: location.latLng.lat(),
        lng: location.latLng.lng(),
      };
    }
            },
            watch: {
        }
      }
</script>