<template>
    <v-layout class="fill-height" column>
        <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 row>
                <v-flex xs12><h4>UPLOAD DB</h4></v-flex>
            </v-layout>
            <v-layout  pt-2 pb-1 row>
                <v-flex class="text-xs-left" xs8>
                    <input  type="file" id="file" ref="file" name="data_file" class="form-control" @change="handleFilesUpload()">
                </v-flex>
                <v-flex class="text-xs-right" xs4>
                    <v-btn small @click="submitFile()" color="info">upload</v-btn>
                </v-flex>
            </v-layout>
           
            <v-progress-linear v-if="onprogress" :indeterminate="true"></v-progress-linear>

        </v-card>
        <v-card color="orange accent-1" class="mb-2 pa-2 searchbox">
            <v-layout row>
                <v-flex xs12><h4>UPLOAD FOTO</h4></v-flex>
            </v-layout>
            <v-layout  pt-2 pb-1 row>
                <v-flex class="text-xs-left" xs8>
                    <input  type="file" id="filephoto" ref="filephoto" name="data_file" class="form-control" 
                    @change="handleFilesUploadPhoto()">
                </v-flex>
                <v-flex class="text-xs-right" xs4>
                    <v-btn small @click="submitPhoto()" dark color="info">upload</v-btn>
                </v-flex>
            </v-layout>
           
            <v-progress-linear v-if="onprogress" :indeterminate="true"></v-progress-linear>

        </v-card>
        
        <v-card color="#57c492">
            <v-layout row>
                <v-flex xs12  pa-1>
                    <v-card>
                         <v-text-field 
                             label="Cari ..."
                             @keyup.enter="searchDoctor"
                             outline
                             single-line
                             v-model="name"
                             placeholder="Cari dengan kode"
                             hide-details
                             ></v-text-field>
                    </v-card>
                </v-flex>
            </v-layout>
            <v-layout row>
                <v-flex xs12 pa-1>
                    <v-card >
                        <v-card-text>
                        <v-data-table
                            :headers="headers"
                            :items="datas"
                            hide-actions
                            class="elevation-1"
                        >
                            <template v-slot:items="props">
                            <td v-bind:class="{'amber lighten-4':isSelected(props.item)}" @click="selectMe(props.item)" class="text-xs-left">{{ props.item.McuOfflinePrepareCode }}</td>
                            <td v-bind:class="{'amber lighten-4':isSelected(props.item)}" @click="selectMe(props.item)" class="text-xs-center">{{ props.item.M_CompanyName }}</td>
                            </template>
                        </v-data-table>
                        </v-card-text>
                        <v-card-actions>
                            <v-pagination  style="margin-top:10px;margin-bottom:10px" 
                            color="#57c492"
                            :total-visible="15" 
                            v-model="curr_page" 
                            :length="xtotal_page">
                            </v-pagination>
                        </v-card-actions>
                    </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/search_left", {
                name:this.name,
                current_page: this.$store.state.patient.current_page_left,
                lastid: -1
            })
        },
        methods: {
          
            downloadcsv(){
                window.open("./csv-mcu.xls")
            },
            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.McuOfflinePrepareID == this.$store.state.patient.selected_patient.McuOfflinePrepareID
            },
            searchDoctor() {
                this.$store.dispatch("patient/search_left", {
                    name: this.name,
                    current_page: 1,
                    lastid: -1
                })
                this.$store.commit("patient/update_current_page_left", 1)
            },
            selectMe(pat) {
                this.$store.commit("patient/update_selected_patient", pat)
                var prm = pat
                prm.current_page = 1
                prm.lastid = -1
                this.$store.dispatch("patient/search",prm)
            },
            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() {
                this.$store.commit("patient/update_dialog_success", false)
            },
            
            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
            },
            
           
        submitFile(){
                /*
                        Initialize the form data
                    */
                    let formData = new FormData();

                    /*
                        Add the form data we need to submit
                    */
                    formData.append('file', this.file);
                    var xx = this

                /*
                Make the request to the POST /single-file URL
                */
                this.$store.commit("patient/update_onprogress", true)
                    axios.post( '/one-api/tools/temptosession/savedata',
                        formData,
                        {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    }
                    ).then(function(){
                       xx.onprogress = false
                      // var msg = "Berhasil upload data"
                       xx.$store.commit("patient/update_msg_success", "Berhasil upload data")
                       xx.$store.commit("patient/update_onprogress", false)
                       xx.dialogsuccess = true
                console.log('SUCCESS!!');
                })
                .catch(function(){
                    xx.onprogress = false
                    //var msg = "Gagal upload data"
                    xx.$store.commit("patient/update_msg_success", "Gagal upload data")
                       xx.$store.commit("patient/update_onprogress", false)
                       xx.dialogsuccess = true
                console.log('FAILURE!!');
                });
      },
      submitPhoto(){
                /*
                        Initialize the form data
                    */
                    let formData = new FormData();

                    /*
                        Add the form data we need to submit
                    */
                    formData.append('filephoto', this.filephoto);
                    var xx = this

                /*
                Make the request to the POST /single-file URL
                */
                this.$store.commit("patient/update_onprogress", true)
                    axios.post( '/one-api/tools/imagetofolder/savedata',
                        formData,
                        {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    }
                    ).then(function(){
                       xx.onprogress = false
                      // var msg = "Berhasil upload data"
                       xx.$store.commit("patient/update_msg_success", "Berhasil upload data")
                       xx.$store.commit("patient/update_onprogress", false)
                       xx.dialogsuccess = true
                console.log('SUCCESS!!');
                })
                .catch(function(){
                    xx.onprogress = false
                    //var msg = "Gagal upload data"
                    xx.$store.commit("patient/update_msg_success", "Gagal upload data")
                       xx.$store.commit("patient/update_onprogress", false)
                       xx.dialogsuccess = true
                console.log('FAILURE!!');
                });
      },
      /*
        Handles a change on the file upload
      */
      handleFilesUpload(){
          //console.log(this.$refs)
       this.file = this.$refs.file.files[0];

      },
      handleFilesUploadPhoto(){
          //console.log(this.$refs)
       this.filephoto = this.$refs.filephoto.files[0];

      },
            loadCSV(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.');
                }
            }
        },
        computed: {
            datas() {
                return this.$store.state.patient.datas
            },
            curr_page: {
                get() {
                    return this.$store.state.patient.current_page_left
                },
                set(val) {
                    this.$store.commit("patient/update_current_page_left", val)
                    this.$store.dispatch("patient/search_left", {
                        current_page: val,
                        lastid: -1
                    })
                }
            },
            onprogress: {
                get() {
                    return this.$store.state.patient.onprogress
                },
                set(val) {
                    this.$store.commit("patient/update_onprogress", val)
                }
            },
            xtotal_page: {
                get() {
                    return this.$store.state.patient.total_patient_left
                },
                set(val) {
                    this.$store.commit("patient/update_total_patient_left", 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)
                }
            },


        },
        filters: {
            capitalize: function (str) {
            return str.charAt(0).toUpperCase() + str.slice(1)
            }
        },
        data() {
            return {
                name:'',
                file: '',
                filephoto:'',
                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: "KODE",
                        align: "left",
                        sortable: false,
                        value: "mr",
                        width: "35%",
                        class: "pa-2 deep-orange accent-1 white--text"
                    },
                    {
                        text: "KEL. PELANGGAN",
                        align: "left",
                        sortable: false,
                        value: "lab",
                        width: "55%",
                        class: "pa-2 deep-orange accent-1 white--text"
                    }
                ],
                pagination: {
                    descending: false,
                    page: 1,
                    rowsPerPage: 5,
                    
                    totalItems: this.$store.state.patient.total_patients
                }
            };
        }
    }
</script>