<template>

   <v-dialog
        persistent
        v-model="dialog"
        width="1000"
      >
        <v-btn 
            class="mt-1" 
            fab 
            small  
            slot="activator" 
            title="tambahkan pasien baru"  
            @click="new_patient"  
            dark 
            color="teal lighten-2">
        <v-icon dark>add</v-icon>
      </v-btn>
         <v-card>
            <v-card-title
               class="teal lighten-2 white--text pt-2 pb-2"
               primary-title
               >
               {{ dialog_title }}            
               </v-card-title>
               <v-card-text class="pt-2 pb-2">
                  
                   <v-layout pt-2 row>
                       <v-flex xs6 pr-3>
                           <v-layout row wrap>
                                <v-flex xs3 pr-1>
                                   <v-text-field
                                        style="font-size:12px;padding:4px 0"
                                        v-model="patient_new.M_PatientPrefix"
                                        label="Awalan"
                    
                     
                                
                                    ></v-text-field>
                                </v-flex>
                                <v-flex xs6>
                                   <v-text-field
                                        style="font-size:12px;padding:4px 0"
                                        v-model="patient_new.M_PatientName"
                                        label="Nama Pasien"
                                        :error="errors.name"
                                        :rules="[rules.name]"
                                        :disabled="edit"
                                    ></v-text-field>
                                </v-flex>
                                <v-flex xs3 pl-1>
                                   <v-text-field
                                        style="font-size:12px;padding:4px 0"
                                        v-model="patient_new.M_PatientSuffix"
                                        label="Akhiran"
                                     
                                    ></v-text-field>
                                </v-flex>
                                <v-flex xs6 pr-2>
                                    <v-select
                                        style="font-size:12px;padding:4px 0"
                                        v-model="selected_sex"
                                        :items="sex"
                                        item-value="M_SexID"
                                        item-text="M_SexName"
                                        label="Jenis Kelamin"
                                        return-object
                                        :error="errors.sex"
                                        :rules="[rules.sex]"
                                        :disabled="edit"
                                    >
                                    </v-select>
                                </v-flex>
                                <v-flex xs6 pl-2>
                                    <v-select
                                        style="font-size:12px;padding:4px 0"
                                        item-text="M_TitleName"
                                        return-object
                                        :items="title"
                                        v-model="selected_title"
                                        hide-details
                                        label="Title"
                                        :error="errors.title"
                                        :rules="[rules.title]"
                                    ></v-select>
                                </v-flex>
                                <v-flex xs5 pr-2>
                                    <v-text-field
                                        style="font-size:12px;padding:4px 0"
                                        v-model="patient_new.M_PatientPOB"
                                        label="Tempat Lahir"
                                        :error="errors.pob"
                                        :rules="[rules.pob]"
                                    ></v-text-field>
                                </v-flex>
                                <v-flex xs3 pr-2>
                                    <v-text-field
                                        style="font-size:12px;padding:4px 0"
                                        v-model="patient_new.M_PatientAge"
                                        :disabled="edit"
                                        :rules="[ageRules]"
                                        label="Umur"
                                        @change="changeAge($event)"
                                        hint="isi tahun"
                                    ></v-text-field>
                                </v-flex>
                                <v-flex xs4>
                                    <v-text-field
                                        style="font-size:12px;padding:4px 0"
                                        v-model="xdob"
                                        label="Tanggal Lahir"
                                        return-masked-value
                                        mask="##-##-####"
                                        :rules="[rules.dob]"
                                        :error="errors.dob"
                                        v-if="dialog"
                                        :disabled="edit"
                                        :readonly="patient_new.M_PatientAge != '' && patient_new.M_PatientAge"
                                    ></v-text-field>
                                </v-flex>
                                <v-flex xs6 pr-3>
                                    <v-select
                                        style="font-size:12px;padding:4px 0"
                                        item-text="M_ReligionName"
                                        return-object
                                        :items="religions"
                                        v-model="selected_religion"
                                        hide-details
                                        label="Agama"
                                    ></v-select>
                                </v-flex>
                                <v-flex xs6>
                                   <v-text-field
                                        style="font-size:12px;padding:4px 0"
                                        v-model="patient_new.M_PatientHP"
                                        label="No HP"
                                        :error="errors.hp"
                                        :rules="[rules.hp]"
                                    ></v-text-field>
                                </v-flex>
                                <v-flex xs12>
                                   <v-text-field
                                        style="font-size:12px;padding:4px 0"
                                        v-model="my_email"
                                        label="Email"
                                        hint="Pisahkan dengan (koma) jika email lebih dari satu"
                                    ></v-text-field>
                                </v-flex>
                                <v-flex xs12>
                                   <v-text-field
                                        style="font-size:12px;padding:4px 0"
                                        v-model="patient_new.M_PatientJob"
                                        label="Pekerjaan"
                                    ></v-text-field>
                                </v-flex>
                                <v-flex xs4 pr-2>
                                    <v-select
                                        style="font-size:12px;padding:4px 0"
                                        v-model="selected_idtype"
                                        :items="idtypes"
                                        item-value="M_IdTypeID"
                                        item-text="M_IdTypeName"
                                        label="Tipe ID"
                                        return-object
                                        clearable
                                    >
                                    </v-select>
                                </v-flex>
                                <v-flex xs8>
                                    <v-text-field
                                        style="font-size:12px;padding:4px 0"
                                        v-model="patient_new.M_PatientIDNumber"
                                        label="Nomor ID"
                                    ></v-text-field>
                                </v-flex>   
                                <v-flex xs12>
                                    <v-textarea
                                        style="font-size:12px;padding:4px 0"
                                        v-model="patient_new.M_PatientNote"
                                        label="Catatan Pasien"
                                        auto-grow
                                        rows="1">
                                    </v-textarea>
                                </v-flex>
                           </v-layout>
                        </v-flex>
                        <v-flex xs6 pl-3>
                            <v-layout row wrap>
                                <v-flex xs12>
                                    <v-autocomplete
                                        style="font-size:12px;padding:4px 0"
                                        :items="provinces"
                                        item-text="M_ProvinceName"
                                        item-value="M_ProvinceID"
                                        label="Propinsi"
                                        v-model="selected_province"
                                        clearable
                                        return-object
                                    ></v-autocomplete>
                                </v-flex>
                                <v-flex xs12>
                                    <v-autocomplete
                                        style="font-size:12px;padding:4px 0"
                                        :items="cities"
                                        item-text="M_CityName"
                                        item-value="M_CityID"
                                        label="Kota"
                                        v-model="selected_city"
                                        clearable
                                        return-object
                                    ></v-autocomplete>
                                </v-flex>
                                <v-flex xs12>
                                    <v-autocomplete
                                        style="font-size:12px;padding:4px 0"
                                        :items="districts"
                                        item-text="M_DistrictName"
                                        item-value="M_DistrictID"
                                        label="Kecamatan"
                                        v-model="selected_district"
                                        clearable
                                        return-object
                                    ></v-autocomplete>
                                </v-flex>
                                <v-flex xs12>
                                    <v-autocomplete
                                        style="font-size:12px;padding:4px 0"
                                        :items="villages"
                                        item-text="M_KelurahanName"
                                        item-value="M_KelurahanID"
                                        label="Kelurahan"
                                        clearable
                                        v-model="selected_village"
                                        :error="errors.kelurahan"
                                        :rules="[rules.kelurahan]"
                                        return-object
                                    ></v-autocomplete>
                                </v-flex>
                                <v-flex xs12>
                                    <v-textarea
                                        style="font-size:12px;padding:4px 0"
                                        auto-grow
                                        rows="1"
                                        v-model="patient_new.M_PatientAddressDescription"
                                        label="Alamat"
                                        :error="errors.address"
                                        :rules="[rules.address]">
                                    </v-textarea>
                                   
                                </v-flex>
                            </v-layout>
                        </v-flex>
                    </v-layout>
                </v-card-text>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn
                        color="teal"
                        dark
                        @click="add_use()"
                        :disabled="!btn_save_enabled"
                        v-show="!edit"
                    >
                    Simpan dan Gunakan
                    </v-btn>
                    <v-btn
                        dark
                        color="teal"
                        @click="add_new()"
                        v-show="edit"
                        :disabled="!btn_save_enabled"
                        >
                        Simpan
                    </v-btn>
                    <v-btn
                        color="grey"
                        flat
                        @click="dialog = false"
                    >
                    Tutup
                    </v-btn>
                </v-card-actions>
         </v-card>
   </v-dialog>
</template>
<style scoped>
.v-dialog__container {
   display: block !important;
}
</style>
<script>
module.exports = {
    components : {
        'one-date-picker' : httpVueLoader('../../common/oneDatePicker.vue')
    },
    data() {
        return {
            dialog_title: 'Data Pasien Baru',
            ageRules:value => {
                if(value.length > 2)
                return 0 || 'Max 2 char'
            },
            emailRules:[],
            email: value => {
                const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
                return pattern.test(value) || 'Invalid e-mail.'
            },
            id_number: '',
            my_email: '',
            rules: {
                name: value => { this.errors.name = !value; return !!value || "Harus diisi !" },
                sex: value => { this.errors.sex = !value.M_SexID; return !!value.M_SexID || "Harus diisi !" },
                title: value => { this.errors.title = !value.M_TitleID; return !!value.M_TitleID || "Harus diisi !" }
            },
            errors: { name: false, sex: false, title: false
            }
        }
    },
   computed: {
       xdob : {
            get () {
               return this.$store.state.patient.xdob
            },
            set (v) {
               this.$store.commit('patient/update_xdob', v)
            }
        },
        patient_new : {
            get () {
               return this.$store.state.patient.patient_new
            },
            set (v) {
               this.$store.commit('patient/update_patient_new', v)
            }
        }, 
        dialog: {
            get() {
                return this.$store.state.patient.patient_new_dialog_is_active
            },
            set(val) {
                this.$store.commit('patient/update_patient_new_dialog_is_active', val)
            }
        },
        sex () {
            return this.$store.state.other.sex
        },
        selected_sex : {
            get () {
                return this.$store.state.other.selected_sex
            },
            set (val) {
                this.$store.commit('other/update_selected_sex', val)
            }
        },
        title () {
            return this.$store.state.other.title
        },
        selected_title : {
            get () {
                return this.$store.state.other.selected_title
            },
            set (val) {
                this.$store.commit('other/update_selected_title', val)
            }
        },
        provinces () { return this.$store.state.area.provinces },
        selected_province : { 
            get () { return this.$store.state.area.selected_province },
            set (v) { 
                this.$store.commit('area/update_selected_area', {type:'province',val:v})
                this.$store.dispatch('area/search_city') 
            }          
        },

        cities () { return this.$store.state.area.cities },
        selected_city : { 
            get () { return this.$store.state.area.selected_city },
            set (v){ 
                        this.$store.commit('area/update_selected_area', {type:'city',val:v})
                        this.$store.dispatch('area/search_district') 
            }
        },
        districts () { return this.$store.state.area.districts },
        selected_district : { 
            get () { return this.$store.state.area.selected_district },
            set (v) { this.$store.commit('area/update_selected_area', {type:'district',val:v})
                    this.$store.dispatch('area/search_kelurahan') }
        },
        villages () { return this.$store.state.area.villages },
        selected_village : { 
            get () {
                let x = this.$store.state.area.selected_village
                if (x) if(x.M_KelurahanID) this.errors.kelurahan = false
                return x 
            },
            set (v) { 
              this.$store.commit('area/update_selected_area', {type:'village',val:v}) 
              let x = this.$store.state.area.selected_village
              if (x) if(x.M_KelurahanID) this.errors.kelurahan = false
            }
        },
        idtypes () {
            return this.$store.state.patient.idtypes
        },
        selected_idtype : {
            get () { return this.$store.state.patient.selected_idtype },
            set (v) { this.$store.commit('patient/update_selected_idtype', v) }
        },
        btn_save_enabled () {
            let xxx = true
            if (this.errors.name || this.errors.sex || this.errors.dob ||
                this.errors.title || this.errors.pob || this.errors.hp ||
                this.errors.address || this.errors.kelurahan) xxx = false
            if (!this.selected_village)
                xxx = false

            return xxx
            return true
        },

        edit() {
            return this.$store.state.patient.edit
        },

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

        religions () {
            return this.$store.state.other.religions
        },

        selected_religion : {
            get () {
                return this.$store.state.other.selected_religion
            },
            set (val) {
                this.$store.commit('other/update_selected_religion', val)
            }
        }
   },

   methods : {
       changeAge(value){
         console.log(value)
           var pat = this.patient_new
           if(value !== '' && value.length <= 2){
               var xy = new Date().getFullYear() - value
               var a = new Date(); 
               var xm = ("0" + (a.getMonth() + 1)).slice(-2); 
               var xd = ("0" + a.getDate()).slice(-2); 
               this.xdob = xd+'-'+xm+'-'+xy
              // console.log(pat)
               //this.$store.commit('patient/update_patient_new', pat)
           }
           else
                this.patient_new.M_PatientAge = ''
       },
       get_city() {
           return
       },
       add_new (use) {
           religion = 0
           if(this.selected_religion)
            religion = this.selected_religion.M_ReligionID
           let prm = {
                M_PatientName : this.patient_new.M_PatientName,
                M_PatientM_TitleID : this.selected_title.M_TitleID,
                M_PatientPrefix : this.patient_new.M_PatientPrefix,
                M_PatientSuffix : this.patient_new.M_PatientSuffix,
                M_PatientM_SexID : this.selected_sex ? this.selected_sex.M_SexID : 0,
                M_PatientM_ReligionID : religion,
                M_PatientPOB : this.patient_new.M_PatientPOB,
                M_PatientDOB : this.xdob,
                M_PatientHP : this.patient_new.M_PatientHP,
                M_PatientPhone : this.patient_new.M_PatientPhone,
                M_PatientEmail : this.my_email,
                M_PatientJob:this.patient_new.M_PatientJob,
                M_PatientM_IdTypeID : (this.selected_idtype ? this.selected_idtype.M_IdTypeID : 0),
                M_PatientIDNumber : this.patient_new.M_PatientIDNumber,
                M_PatientNote : this.patient_new.M_PatientNote,

                M_PatientAddressDescription : this.patient_new.M_PatientAddressDescription,
                M_PatientAddressM_KelurahanID : this.selected_village.M_KelurahanID
           }
           if (use || this.edit) { prm.use = true }

           this.$store.dispatch('patient/add_new', prm)
           this.dialog = false
       },

       add_use () {
           this.add_new(true)
       },

       set_date (x) {
           this.patient_new.M_PatientDOB = x.new_date
       },

        new_patient() {
            this.$store.commit('patient/update_edit', false)
        }
   },

   watch : {
       my_email (v, o) {
           if (v == "") {
               this.email = value => {
                   return /\s/ || 'Hahaha'
               }
           } else {
               this.email = value => {
                    const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
                    return pattern.test(value) || 'Invalid e-mail.'
                }
           }
       },
       
       async dialog (val, old) {
            if (val && !old) {

                if (this.edit) {
                    this.dialog_title = 'PERUBAHAN DATA PASIEN'
                    let x = this.patient_new
                    let y = this.selected_patient
                    x.M_PatientPrefix = y.M_PatientPrefix
                    x.M_PatientName = y.M_PatientRealName
                    x.M_PatientSuffix = y.M_PatientSuffix
                    this.xdob = y.M_PatientDOB.split('-').reverse().join('-')
                    x.M_PatientPOB = y.M_PatientPOB
                    x.M_PatientHP = y.M_PatientHP
                    x.M_PatientEmail = y.M_PatientEmail
                    x.M_PatientJob = y.M_PatientJob
                    x.M_PatientNote = y.M_PatientNote
                    x.M_PatientIDNumber = y.M_PatientIDNumber
                    x.M_PatientAddressDescription = y.M_PatientAddressDescription
                    this.my_email = y.M_PatientEmail
                    this.patient_new = x
                    console.log(this.selected_patient)
                    
                    // SEX
                    await this.$store.dispatch("other/search_sex")
                    let sex = this.$store.state.other.sex
                    console.log("sex")
                    console.log(sex)
                    console.log(this.selected_patient.M_SexID)
                    let x_sexid = this.selected_patient.M_SexID
                    let idx_sex = _.findIndex(sex, function(o) { return parseInt(o.M_SexID) === parseInt(x_sexid) })
                    this.selected_sex = sex[idx_sex]
                    console.log('selected_sex')
                    console.log(this.selected_sex)
                    let titles = sex[idx_sex].title
                    this.$store.commit("other/update_title", titles)
                    // TITLE
                    //let title = this.$store.state.other.title
                    console.log('title')
                    console.log(titles)
                    console.log('patient title : '+this.selected_patient.M_TitleID)
                    let x_titleid = this.selected_patient.M_TitleID
                    let idx_title = _.findIndex(titles, function(o) { return parseInt(o.M_TitleID) === parseInt(x_titleid) })
                    console.log('idx title : '+idx_title)
                    this.selected_title = titles[idx_title]
                    console.log('selected title')
                    console.log(this.selected_title)
                    console.log(titles[idx_title])
                    // ID TYPE
                    this.selected_idtype = null
                    let idtype = this.$store.state.patient.idtypes
                    for (let i in idtype)
                        if (idtype[i].M_IdTypeID == y.M_PatientM_IdTypeID)
                            this.selected_idtype = idtype[i] 

                    // RELIgION
                    let religions = this.$store.state.other.religions
                    let x_religionid = this.selected_patient.M_PatientM_ReligionID
                    let idx_religion = _.findIndex(religions, function(o) { return parseInt(o.M_ReligionID) === parseInt(x_religionid) })
                    this.selected_religion = religions[idx_religion]
                    // ERRORS
                    let err = { dob: false, name: false, sex: false, title: false, hp: false,
                      address: false, province: false, city: false, district: false, kelurahan: false}
                    this.errors = err
                    
                } else {
                    this.dialog_title = 'DATA PASIEN BARU'
                    let x = this.patient_new
                    this.my_email = ""
                    x.M_PatientNote = ""
                    x.M_PatientPrefix = ""
                    x.M_PatientName = ""
                    x.M_PatientSuffix = ""
                    x.M_PatientDOB = ""
                    x.M_PatientPOB = ""
                    x.M_PatientHP = ""
                    x.M_PatientEmail = ""
                    x.M_PatientJob = ""
                    x.M_PatientAddressDescription = ""
                    x.M_PatientIDNumber = ""
                    this.patient_new = x
                    this.selected_sex = {}
                    this.selected_title = {}
                    this.selected_idtype = {}
                    this.selected_religion = {}
                    
                }

                this.$store.dispatch('area/search_province')
           }
       }
   },

   mounted () {
    //    this.$store.dispatch('area/search_province')
       this.$store.dispatch('other/search_sex')
        this.$store.dispatch('other/search_religion')
       this.$store.dispatch('patient/search_idtype')
    //    this.$store.dispatch('area/search_city')
   }
}
</script>
