<template>
    <v-layout class="fill-height" column>
        <v-dialog
        v-model="dialog_identifier"
        width="800"
        >
            <v-card>
                <v-card-title
                    class="headline grey lighten-2 pt-2 pb-2"
                    primary-title
                >
                GAGAL, KTP DAN TANGGAL LAHIR HARUS BENAR!!!
                </v-card-title>
                <v-card-text>
                    <v-layout align-center row>
                        <v-flex xs12 pl-2 pr-2 pt-2 pb-2>
                            <v-data-table :headers="headers" :items="xidentifer" hide-actions
                            class="elevation-1">
                                <template slot="items" slot-scope="props">
                                    <td class="text-xs-left pa-2" v-html="props.item.NAMA"></td>
                                    <td class="text-xs-left pa-2" v-html="props.item.KTP"></td>
                                </template>
                            </v-data-table>
                        </v-flex>
                    </v-layout>
                </v-card-text>
                <v-divider></v-divider>

                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn
                        color="primary"
                        flat
                        @click="dialog_identifier = false"
                    >
                        Tutup
                    </v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
        <v-dialog v-model="dialogsuccess" persistent max-width="290">
            <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-card color="orange accent-1" class="mb-2 pa-2 searchbox">
            <v-layout  pt-2 pb-1 row>
                <v-flex class="text-xs-left" xs12>
                    <input  accept=".xlsx" type="file" id="csv_file" name="csv_file" class="form-control" @change="loadCSV($event)">
                    <v-progress-circular v-if="loading_save" :indeterminate="true" color="primary"></v-progress-circular>
                </v-flex>
            </v-layout>
        </v-card>
        <v-card color="orange accent-1" class="mb-2 pa-2 searchbox">
            <v-layout row>
                <v-flex xs12>
                    <v-card>
                        <v-layout pa-2 row>
                            <v-flex xs12>
                                <v-autocomplete :items="xmgmmcu" v-model="selected_mgmmcu" item-text="mcuName" outline
                                    item-value="Mgm_McuID" return-object label="Stage">
                                </v-autocomplete>
                            </v-flex>
                        </v-layout>
                        <v-divider></v-divider>
                        <v-layout row>
                            <v-flex xs12 pa-2>
                                <v-card color="orange" dark>
                                    <v-card-text>
                                        <v-layout align-center row>
                                            <v-flex pb-2 xs12>
                                                STAGE : {{selected_mgmmcu.mcuName}}
                                            </v-flex>
                                        </v-layout>
                                        <v-divider dark></v-divider>
                                        <v-layout row>
                                            <v-flex xs12>
                                                <p class="mb-0 caption"> Uploaded at : {{selected_mgmmcu.created}}</p>
                                            </v-flex>
                                        </v-layout>
                                    </v-card-text>
                                </v-card>
                            </v-flex>
                        </v-layout>
                    </v-card>
                </v-flex>
            </v-layout>
        </v-card>
        
        
        <one-dialog-alert :status="openalertconfirmation" :msg="msgalertconfirmation" @forget-dialog-alert="forgetAlertConfirmation()" @close-dialog-alert="closeAlertConfirmation()"></one-dialog-alert>
    </v-layout>
</template>

<style scoped>
  table.v-table tbody td,table.v-table tbody th {
      height: 35px;
   }

   table.v-table thead tr {
      height: 35px;
   }
</style>
<script>
    module.exports = {
        components: {
            'one-dialog-info' : httpVueLoader('../../common/oneDialogInfo.vue'),
            'one-dialog-alert': httpVueLoader('../../common/oneDialogAlert.vue')
        },
        mounted() {
            //this.setNewSetup()
            this.$store.dispatch("patient/getmgmmcu")
            
        },
        methods: {
            downloadxapp(){
                var start = Date.now()
                location.replace("/install-mcu.zip?tm="+start)
            },
            generateSetup(){
                this.$store.commit("patient/update_patients", [])
                this.$store.commit("patient/update_total_patients", 0)
                this.$store.dispatch("patient/generatesetup", {
                    setupcode : this.setupcode
                })
            },
            downloadcsv(){
               // window.open("./mcu_template.xlsx")
               window.open("./mcu_template_west.xlsx")
            },
            editRow(row){
                console.log(row)
                this.$store.commit("patient/update_act", 'edit')
                this.$store.commit("patient/update_xid", row.McuOfflinePrepareID)
                this.$store.commit("patient/update_companies", [{id:row.McuOfflinePrepareM_CompanyID,name:row.M_CompanyName}])
                this.$store.commit("patient/update_company", {id:row.McuOfflinePrepareM_CompanyID,name:row.M_CompanyName})
                this.$store.commit("patient/update_mous", row.allmous)
                this.$store.commit("patient/update_mou", {})
                this.$store.commit("patient/update_selected_mous", row.mous)
                this.$store.commit("patient/update_selected_doctors", row.doctors)
                
                this.$store.commit("patient/update_start_date", moment(row.McuOfflinePrepareStartDate).format('YYYY-MM-DD'))
                this.$store.commit("patient/update_end_date", moment(row.McuOfflinePrepareEndDate).format('YYYY-MM-DD'))
            },
            isSelected(p) {
                return p.M_PatientID == this.$store.state.patient.selected_patient.M_PatientID
            },
            searchPatient() {
                this.$store.dispatch("patient/search", {
                    status: this.status,
                    current_page: 1,
                    lastid: -1
                })
                this.$store.commit("patient/update_current_page", 1)
            },
            selectMe(pat) {
                if (this.$store.state.patient.no_save == 0) {
                    this.$store.commit("patient/update_selected_patient", pat)
                } else {
                    this.$store.commit("patient/update_open_alert_confirmation", true)
                }
            },
            closeAlertConfirmation() {
                this.$store.commit("patient/update_open_alert_confirmation", false)
            },
            forgetAlertConfirmation() {
                this.$store.commit("patient/update_no_save", 0)
                this.$store.commit("patient/update_open_alert_confirmation", false)
            },
            updateAlert_success(val) {
                this.$store.commit("patient/update_alert_success", val)
            },
            closeDialogSuccess() {
                let arrpatient = this.$store.state.patient.patients
                var idx = _.findIndex(arrpatient, item => item.M_PatientID === this.$store.state.patient.last_id)
                console.log(idx)
                this.$store.dispatch("patient/search", {
                    status: this.status,
                    current_page: this.curr_page,
                    lastid: idx
                })
                this.$store.commit("patient/update_dialog_success", false)
            },
            setNewSetup(){
                this.$store.commit("patient/update_act", 'new')
                this.$store.commit("patient/update_xid", -1)
                this.$store.commit("patient/update_company", {})
                this.$store.commit("patient/update_mous", [])
                this.$store.commit("patient/update_mou", {})
                this.$store.commit("patient/update_default_mou", {})
                this.$store.commit("patient/update_default_doctor", {})
                this.$store.commit("patient/update_selected_mous", [])
                this.$store.commit("patient/update_selected_doctors", [])
                this.$store.commit("patient/update_start_date", moment(new Date()).format('YYYY-MM-DD'))
                this.$store.commit("patient/update_end_date", moment(new Date()).format('YYYY-MM-DD'))
            },
            deleteData(row) {
                this.$store.commit("patient/update_selected_patient", row)
                console.log(this.$store.state.patient.selected_patient)
                let msg = "Yakin, akan menghapus data setup " + this.$store.state.patient.selected_patient.McuOfflinePrepareCode + " ?"
                this.$store.commit("patient/update_msg_confirmation_delete", msg)
                this.$store.commit("patient/update_dialog_confirmation_delete", true)
            },
            doDeleteData() {
                var prm = {}
                prm.id   = this.$store.state.patient.selected_patient.McuOfflinePrepareID
                prm.code = this.$store.state.patient.selected_patient.McuOfflinePrepareCode
                console.log(prm)
                this.$store.dispatch("patient/delete", prm)
            },
            csvJSON(csv){
                var vm = this
                var lines = csv.split("\n")
                var result = []
                var headers = lines[0].split(",")
                vm.parse_header = lines[0].split(",") 
                lines[0].split(",").forEach(function (key) {
                    vm.sortOrders[key] = 1
                })
                
                lines.map(function(line, indexLine){
                    if (indexLine < 1) return // Jump header line
                    
                    var obj = {}
                    var currentline = line.split(",")
                    
                    headers.map(function(header, indexHeader){
                    var header = header.trim();
                    obj[header] = currentline[indexHeader]
                    })
                    
                    result.push(obj)
                })
                
                result.pop() // remove the last item because undefined values
                
                return result // JavaScript object
            },
            loadCSV_old(e) {
                var vm = this
                if (window.FileReader) {
                    var reader = new FileReader();
                    reader.readAsText(e.target.files[0]);
                    // Handle errors load
                    reader.onload = function(event) {
                        var csv = event.target.result;
                        vm.parse_csv = vm.csvJSON(csv)
                        var prm = {xid:vm.$store.state.patient.data_setup.McuOfflinePrepareID,data:vm.parse_csv}
                        console.log(prm)
                        vm.$store.dispatch("patient/savecsv", prm)
                    };
                    reader.onerror = function(evt) {
                    if(evt.target.error.name == "NotReadableError") {
                        alert("Canno't read file !");
                    }
                    };
                } else {
                    alert('FileReader are not supported in this browser.');
                }
            },
            // Validasi KTP sederhana
            // cekKTP(nik,tanggal,bulan,tahun) {
            //     if(strlen(nik) != 16){
            //         return false;
            //     }
            //     var d = substr(nik, 6, 2);
            //     var m = substr(nik, 8, 2);
            //     var y = substr(nik, 10, 2);
                
            //     //jika tahun full, ambil 2 digit terakhir
            //     if(strlen(tahun==4)){
            //         tahun = substr(tahun,2,2);
            //     }
            //     if (intval(d) > 40) {
            //         //Wanita
            //         d = intval(d) - 40; 
            //     }
            //     if(tanggal/d != 1){
            //         return false;
            //     }
                
            //     if(bulan/m != 1){
            //         return false;
            //     }
                
            //     if(tahun/y != 1){
            //         return false;
            //     }
            //     //setelah berhasil melewati rintangan, berarti nomornya valid (tidak 100% valid)
            //     return true;
            // },
            cekKTP(nik,tanggal,bulan,tahun) {
                return true;
                if (nik.length !== 16) {
                    return false;
                }

                let d = parseInt(nik.substr(6, 2));
                let m = parseInt(nik.substr(8, 2));
                let y = parseInt(nik.substr(10, 2));

                // Jika tahun full, ambil 2 digit terakhir
                if (tahun.toString().length === 4) {
                    tahun = tahun.toString().substr(2, 2);
                }

                if (d > 40) {
                    // Wanita
                    d = d + 40;
                }

                if (parseInt(tanggal) !== d) {
                    return false;
                }

                if (parseInt(bulan) !== m) {
                    return false;
                }

                if (parseInt(tahun) !== y) {
                    return false;
                }

                // Setelah berhasil melewati rintangan, berarti nomornya valid (tidak 100% valid)
                return true;
            },
            loadCSV(e) {
                var vm = this
                var files = e.target.files, f = files[0];
                var reader = new FileReader();
                reader.onload = function(e) {
                    var data = new Uint8Array(e.target.result);
                    var workbook = XLSX.read(data, {type: 'array',cellText:true,cellDates: true});
                    let sheetName = workbook.SheetNames[0]
                    /* DO SOMETHING WITH workbook HERE */
                    console.log(workbook);
                    let worksheet = workbook.Sheets[sheetName];
                   // console.log(XLSX.utils.sheet_to_json(worksheet));
                    //var xdata = XLSX.utils.sheet_to_json(worksheet,{ raw:false,  dateNF: 'FMT 22'})
                    var data_json = []
                   // console.log(xdata)
                    var date_data = XLSX.utils.sheet_to_json(worksheet, {raw:false,dateNF:'22'});
                    var ktp_data = XLSX.utils.sheet_to_json(worksheet, {cellText:true});
                    var error = []
                    // console.log("ktp_data", ktp_data)
                    date_data.forEach(function(entry,iidx) {
                        data_json.push(entry)
                    })
                    var prm = {
                        xid:vm.selected_mgmmcu.Mgm_McuID,
                        corporateID:vm.selected_mgmmcu.Mgm_McuCorporateID,
                        data:data_json}
                    console.log(data_json)
                    // console.log("data prm",prm)
                    //XLSX.utils.sheet_to_json(ws, {dateNF:"YYYY-MM-DD"})
                    if (error.length != 0) {
                        // console.log("error", error)
                        vm.$store.commit("patient/update_error_identifier", error)
                        vm.dialog_identifier = true
                    } else {
                        // console.log("prm",prm)
                        vm.$store.dispatch("patient/savecsv", prm)
                    }
                };
                reader.readAsArrayBuffer(f);
            }
        },
        computed: {
            xidentifer() {
                return this.$store.state.patient.error_identifier
            },
            xmgmmcu() {
                return this.$store.state.patient.mgmmcu
            },
            selected_mgmmcu: {
                get() {
                    return this.$store.state.patient.selected_mgmmcu
                },
                set(val) {
                    this.$store.commit("patient/update_selected_mgmmcu", val)
                    this.$store.dispatch("patient/search", {
                        search: '',
                        current_page: this.$store.state.patient.current_page,
                        xid:this.$store.state.patient.selected_mgmmcu.Mgm_McuID,
                        lastid: -1
                    })
                }
            },
            setupcode: {
                get() {
                    return this.$store.state.patient.setupcode
                },
                set(val) {
                    this.$store.commit("patient/update_setupcode", val)
                }
            },
            xsetup() {
                return this.$store.state.patient.data_setup
            },
            dialogconfirmationdelete: {
                get() {
                    return this.$store.state.patient.dialog_confirmation_delete
                },
                set(val) {
                    this.$store.commit("patient/update_dialog_confirmation_delete", val)
                }
            },
            msgconfirmationdelete() {
                return this.$store.state.patient.msg_confirmation_delete
            },
            status: {
                get() {
                    return this.$store.state.patient.status
                },
                set(val) {
                    this.$store.commit("patient/update_status", val)
                    this.$store.dispatch("patient/search", {
                        status: val,
                        current_page: this.curr_page,
                        lastid: -1
                    })
                }
            },
            dialogsuccess: {
                get() {
                    return this.$store.state.patient.dialog_success
                },
                set(val) {
                    this.$store.commit("patient/update_dialog_success", val)
                }
            },
            msgsuccess() {
                return this.$store.state.patient.msg_success
            },
            snackbar: {
                get() {
                    return this.$store.state.patient.alert_success
                },
                set(val) {
                    this.$store.commit("patient/update_alert_success", val)
                }
            },
            isLoading() {
                return this.$store.state.patient.search_status == 1
            },
            openalertconfirmation: {
                get() {
                    return this.$store.state.patient.open_alert_confirmation
                },
                set(val) {
                    this.$store.commit("patient/update_open_alert_confirmation", val)
                }
            },
            loading_save: {
                get() {
                    return this.$store.state.patient.loading_save
                },
                set(val) {
                    this.$store.commit("patient/update_loading_save", val)
                },
            },

        },
        filters: {
            capitalize: function (str) {
            return str.charAt(0).toUpperCase() + str.slice(1)
            }
        },
        data() {
            return {
                files: [], 
                dialog_identifier: false,
                channel_name: '',
                channel_fields: [],
                channel_entries: [],
                parse_header: [],
                parse_csv: [],
                sortOrders:{},
                sortKey: '',
                statuses:[{id:"N",name:"Belum di download"},{id:"Y",name:"Sudah di download"}],
                msgalertconfirmation: "Perubahan yang telah dilakukan belum disimpan dong !",
                items: [],
                name: '',
                snorm: '',
                page: 1,
                headers: [
                    {
                        text: "NAMA",
                        align: "left",
                        sortable: false,
                        value: "mr",
                        width: "50%",
                        class: "pa-2 deep-orange accent-1 white--text"
                    },
                    {
                        text: "KTP",
                        align: "left",
                        sortable: false,
                        value: "lab",
                        width: "50%",
                        class: "pa-2 deep-orange accent-1 white--text"
                    }
                ],
                pagination: {
                    descending: false,
                    page: 1,
                    rowsPerPage: 5,
                    sortBy: 'M_PatientName',
                    totalItems: this.$store.state.patient.total_patients
                }
            };
        }
    }
</script>