var VPAttendance = (function () {
    let vp_template = `
    <div class="card p-4">
            <div class="row">
                <div class="col-md-6">
                    <h3>Guru</h3>
                    <label>Jam Masuk <span class="text-success"></span></label>
                    <div class="input-style-2">
                        <input type="text" @change="saveTimePresence('staff','in')" class="form-control" :class="attendance_time.staff.in.errMsg?'is-invalid':''" required v-model="attendanceStaffTimeIn" placeholder="Contoh 07:00">
                        <span class="icon">
                            <i id="StaffTimeIn" style="cursor:pointer" class="far fa-clock">
                            </i>
                        </span>
                        <div class="invalid-feedback">
                        {{attendance_time.staff.in.errMsg}}
                        </div>
                    </div>

                    <label>Jam Keluar <span class="text-success"></span></label>
                    <div class="input-style-2">
                        <input type="text" @change="saveTimePresence('staff','out')" class="form-control" :class="attendance_time.staff.out.errMsg?'is-invalid':''" required v-model="attendanceStaffTimeOut" placeholder="Contoh 17:00">
                        <span class="icon">
                            <i id="StaffTimeOut" style="cursor:pointer" class="far fa-clock">
                            </i>
                        </span>
                        <div class="invalid-feedback">
                            {{attendance_time.staff.out.errMsg}}
                        </div>    

                    </div>
                </div>
                <div class="col-md-6">
                    <h3>Siswa</h3>
                    <label>Jam Masuk <span class="text-success"></span></label>
                    <div class="input-style-2">
                        <input type="text" @change="saveTimePresence('siswa','in')" class="form-control" :class="attendance_time.siswa.in.errMsg?'is-invalid':''" required v-model="attendanceSiswaTimeIn" placeholder="Contoh 07:00">
                        <span class="icon">
                            <i id="SiswaTimeIn" style="cursor:pointer" class="far fa-clock">
                            </i>
                        </span>
                        <div class="invalid-feedback">
                        {{attendance_time.siswa.in.errMsg}}
                        </div>
                    </div>

                    <label>Jam Keluar <span class="text-success"></span></label>
                    <div class="input-style-2">
                        <input type="text" @change="saveTimePresence('siswa','out')" class="form-control" :class="attendance_time.siswa.out.errMsg?'is-invalid':''" required v-model="attendanceSiswaTimeOut" placeholder="Contoh 17:00">
                        <span class="icon">
                            <i id="SiswaTimeOut" style="cursor:pointer" class="far fa-clock">
                            </i>
                        </span>
                        <div class="invalid-feedback">
                            {{attendance_time.siswa.out.errMsg}}
                        </div>    

                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-8 ">
                    <label>URL Pengingat Presensi</label>
                    <div><small>{{attendance_time.staff.in.endpoint}}</small></div>
                    <div><small>{{attendance_time.staff.out.endpoint}}</small></div>
                    <div><small>{{attendance_time.siswa.in.endpoint}}</small></div>
                    <div><small>{{attendance_time.siswa.out.endpoint}}</small></div>
                </div>

                <div class="col-md-4 d-flex justify-content-center">
                    <!-- <div class="col-md-6 d-flex"> -->
                    <div>
                        <label>QR Presensi</label>
                        <div v-show="qrcode.loading" title="Memuat QR" class="text-center py-5" style="width:128px;height:128px;">
                            <div class="spinner-border" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                        </div>
                        <div v-show="!qrcode.loading" style="width:128px;height:140px;">
                            <div style="cursor: pointer;" id="qrcode"></div>
                            <span>{{qrcode.code}}</span>
                        </div>
                    </div>
                </div>
            </div>
            <hr>
            
            <div class="row">
                <div class="col-6">
                    <label>Radius Pelajar <span class="text-danger">{{conf_radius.student<=0?'Tidak Aktif':''}} </span> <small>(meter)</small> </label>
                    <div class="input-style-2">
                        <input type="text" @change="saveMap()" required v-model="conf_radius.student" placeholder="Untuk Pelajar">
                        <span class="icon"> <i class="fas fa-street-view"></i> </span>
                    </div>
                </div>
                <div class="col-6">
                    <label>Radius Pengajar <span class="text-danger">{{conf_radius.staff<=0?'Tidak Aktif':''}} </span> <small>(meter)</small> </label>
                    <div class="input-style-2">
                        <input type="text" @change="saveMap()" required v-model="conf_radius.staff" placeholder="Untuk Pengajar">
                        <span class="icon"> <i class="fas fa-street-view"></i> </span>
                    </div>
                </div>
            </div>

            <label>Latitude,Longitude Pusat</label>
            <div class="input-style-2">
                <input type="text" required v-model="latlonmarker" placeholder="0000000,11111111">
                <span class="icon"> <i class="fas fa-map-marker"></i> </span>
            </div>

            <div v-if="mapReady==null" class="text-center">
                <span class="spinner-grow spinner-grow" role="status" aria-hidden="true"></span>
            </div>
            <div v-else-if="mapReady==false" class="text-center">
                <button id="load-map" @click="initMap()" class="btn btn-primary">Buka Peta</button>
            </div>
            <div v-show="mapReady" style="height: 500px;width:100%">
                <peta @pusat-change="apusat=$event;saveMap()" :pusat="apusat" :radius="conf_radius" id="map-absensi" ref="peta" class="w-100 h-100"></peta>
            </div>
    </div>
    `
    return {
        name: "attendance",
        template: vp_template,

        data() {
            return {

                qrcode: {
                    loading: true,
                    code: null,
                    instance: null,
                },
                conf_radius: {
                    student: 0,
                    staff: 0
                },
                attendance_time: {
                    staff: {
                        in: {
                            instance: null,
                            errMsg: '',
                            endpoint: '',
                            value: '',
                        },
                        out: {
                            instance: null,
                            errMsg: '',
                            endpoint: '',
                            value: '',
                        },
                    },
                    siswa: {
                        in: {
                            instance: null,
                            errMsg: '',
                            endpoint: '',
                            value: '',
                        },
                        out: {
                            instance: null,
                            errMsg: '',
                            endpoint: '',
                            value: '',
                        },
                    },
                    In: {
                        instance: null,
                        value: '', errMsg: '', Endpoint: {
                            guru: '',
                            siswa: ''
                        }
                    },
                    Out: {
                        instance: null,
                        value: '', errMsg: '', Endpoint: {
                            guru: '',
                            siswa: ''
                        }
                    },
                },
                mapReady: null,
                apusat: {
                    lat: null,
                    lon: null
                },
            }
        },
        mounted() {

            this.loadMap()
            this.loadQR()
            this.timePicker()
            this.loadTimePresence('staff');
            this.loadTimePresence('siswa');
        },
        watch: {
            latlonmarker(v) {
                try {
                    if (!this.mapReady) this.saveMap();
                    this.$refs.peta.setPusat(null, this.apusat.lat, this.apusat.lon);
                } catch (error) {

                }
            },
            myQRCode(code) {
                this.qrcode.loading = false;
                if (this.qrcode.instance) {
                    this.qrcode.instance.clear();
                    this.qrcode.instance.makeCode(code);
                    return;
                }
                document.getElementById('qrcode').addEventListener('click', (e) => {
                    this.generateQR();
                })
                this.qrcode.instance = new QRCode("qrcode", {
                    text: code,
                    width: 128,
                    height: 128,
                    colorDark: "#000000",
                    colorLight: "#ffffff",
                    correctLevel: QRCode.CorrectLevel.H
                });
            },
        },
        methods: {
            initMap() {
                this.mapReady = true;
                setTimeout(() => this.$refs.peta.init(), 50);
            },
            timePicker() {
                this.attendance_time.staff.in.instance = new NJTimePicker({
                    targetID: 'StaffTimeIn',
                    format: '24',
                    autoSave: true
                });
                this.attendance_time.staff.out.instance = new NJTimePicker({
                    targetID: 'StaffTimeOut',
                    format: '24',
                    autoSave: true
                });
                this.attendance_time.siswa.in.instance = new NJTimePicker({
                    targetID: 'SiswaTimeIn',
                    format: '24',
                    autoSave: true
                });
                this.attendance_time.siswa.out.instance = new NJTimePicker({
                    targetID: 'SiswaTimeOut',
                    format: '24',
                    autoSave: true
                });

                this.attendance_time.staff.in.instance.on('save', (data) => {
                    if (data.fullResult.length < 6) {
                        data.fullResult += ":00";
                    }
                    this.attendance_time.staff.in.value = data.fullResult;
                    this.saveTimePresence('staff', 'in');
                });
                this.attendance_time.staff.out.instance.on('save', (data) => {
                    if (data.fullResult.length < 6) {
                        data.fullResult += ":00";
                    }
                    this.attendance_time.staff.out.value = data.fullResult
                    this.saveTimePresence('staff', 'out');
                });
                this.attendance_time.staff.in.instance.setValue(this.attendance_time.staff.in.value);
                this.attendance_time.staff.out.instance.setValue(this.attendance_time.staff.out.value);

                this.attendance_time.siswa.in.instance.on('save', (data) => {
                    if (data.fullResult.length < 6) {
                        data.fullResult += ":00";
                    }
                    this.attendance_time.siswa.in.value = data.fullResult;
                    this.saveTimePresence('siswa', 'in');
                });
                this.attendance_time.siswa.out.instance.on('save', (data) => {
                    if (data.fullResult.length < 6) {
                        data.fullResult += ":00";
                    }
                    this.attendance_time.siswa.out.value = data.fullResult
                    this.saveTimePresence('siswa', 'out');
                });
                this.attendance_time.siswa.in.instance.setValue(this.attendance_time.siswa.in.value);
                this.attendance_time.siswa.out.instance.setValue(this.attendance_time.siswa.out.value);
            },
            loadQR() {
                this.qrcode.loading = true;
                axios({
                    method: 'get',
                    url: window.location.href + '/config_qr',
                }).then((response) => {
                    if (!isObject(response.data)) return setTimeout(() => this.loadQR(), 500);
                    this.myQRCode = response.data.data;
                }, (err) => {
                    return console.log(gaem(err));
                });
            },
            generateQR() {
                this.qrcode.loading = true;
                axios({
                    method: 'get',
                    url: window.location.href + '/generate_qr',
                }).then((response) => {
                    if (!isObject(response.data)) return setTimeout(() => this.generateQR(), 500);
                    this.myQRCode = response.data.qr;
                }, (err) => {
                    return console.log(gaem(err));
                });
            },
            loadTimePresence(type) {
                axios({
                    method: 'get',
                    url: window.location.href + '/timePresence/' + type,
                }).then((response) => {
                    if (!isObject(response.data)) return setTimeout(() => this.loadTimePresence(), 500);
                    if (response.data.timeIn) {
                        let tim = mm({ unix: response.data.timeIn || mm().unix() });
                        if (type == 'staff') {
                            this.attendanceStaffTimeIn = tim.format("HH:mm");
                            this.attendance_time.staff.in.endpoint = response.data.endpointin;
                        } else {
                            this.attendanceSiswaTimeIn = tim.format("HH:mm");
                            this.attendance_time.siswa.in.endpoint = response.data.endpointin;
                        }
                    }
                    if (response.data.timeOut) {
                        let tom = mm({ unix: response.data.timeOut || mm().unix() });
                        if (type == 'staff') {
                            this.attendanceStaffTimeOut = tom.format("HH:mm");
                            this.attendance_time.staff.out.endpoint = response.data.endpointout;
                        } else {
                            this.attendanceSiswaTimeOut = tom.format("HH:mm");
                            this.attendance_time.siswa.out.endpoint = response.data.endpointout;
                        }
                    }
                }, (err) => {

                });
            },
            saveTimePresence(type, state) {
                if (!this.attendance_time[type][state].value.length && type == 'siswa') return this.attendance_time[type][state].errMsg = 'Waktu Perlu Diisi';
                else time = this.attendance_time[type][state].value;
                let attendance = this.attendance_time[type][state];
                attendance.errMsg = '';
                attendance.value = attendance.value.replace(/[^\d:]/g, '');
                axios({
                    method: 'patch',
                    data: {
                        [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value,
                        time: time.length ? mm().hours(time.split(':')[0]).minutes(time.split(':')[1]).unix() : time,
                        state: state,
                    },
                    url: window.location.href + '/timePresence/' + type,
                }).then((response) => {
                    if (!isObject(response.data)) return attendance.errMsg = gaem({ response }, response.data);
                    attendance.errMsg = '';
                }, (err) => {
                    attendance.errMsg = gaem(err);
                });
            },
            loadMap() {
                axios({
                    method: 'get',
                    url: window.location.href + '/config_map',
                }).then((response) => {
                    if (!isObject(response.data)) return setTimeout(() => this.loadMap(), 500);
                    this.mapReady = false;
                    try {
                        let data = JSON.parse(response.data.data);
                        this.apusat = {
                            lat: data.lat,
                            lon: data.lon
                        };
                        this.conf_radius.student = data.student_radius;
                        this.conf_radius.staff = data.staff_radius;
                    } catch (error) {
                        return console.log(gaem(error));
                    }
                }, (err) => {

                });
            },
            saveMap() {
                axios({
                    method: 'patch',
                    data: {
                        [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value,
                        lat: this.apusat.lat,
                        lon: this.apusat.lon,
                        student_radius: this.conf_radius.student,
                        staff_radius: this.conf_radius.staff,
                    },
                    url: window.location.href + '/save_map',
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire("Gagal", gaem({ response }, response.data), 'error');
                }, (err) => {
                    Swal.fire("Gagal", gaem(err), 'error');
                });
            }
        },
        computed: {
            latlonmarker: {
                get() {
                    return `${this.apusat.lat},${this.apusat.lon}`;
                },
                set(c) {
                    if (c == null) {
                        this.apusat.lat = null;
                        this.apusat.lon = null;
                        return
                    }
                    this.apusat.lat = c.split(',')[0] || null;
                    this.apusat.lon = c.split(',')[1] || null;
                }
            },
            attendanceStaffTimeIn: {
                get() {
                    return this.attendance_time.staff.in.value
                },
                set(v) {
                    this.attendance_time.staff.in.instance.setValue(v);
                    this.attendance_time.staff.in.value = v;
                }
            },
            attendanceStaffTimeOut: {
                get() {
                    return this.attendance_time.staff.out.value
                },
                set(v) {
                    this.attendance_time.staff.out.instance.setValue(v);
                    this.attendance_time.staff.out.value = v;
                }
            },
            attendanceSiswaTimeIn: {
                get() {
                    return this.attendance_time.siswa.in.value
                },
                set(v) {
                    this.attendance_time.siswa.in.instance.setValue(v);
                    this.attendance_time.siswa.in.value = v;
                }
            },
            attendanceSiswaTimeOut: {
                get() {
                    return this.attendance_time.siswa.out.value
                },
                set(v) {
                    this.attendance_time.siswa.out.instance.setValue(v);
                    this.attendance_time.siswa.out.value = v;
                }
            },
            attendance_timeIn: {
                get() {
                    return this.attendance_time.In.value
                },
                set(v) {
                    this.attendance_time.In.instance.setValue(v);
                    this.attendance_time.In.value = v;
                }
            },
            attendance_timeOut: {
                get() {
                    return this.attendance_time.Out.value
                },
                set(v) {
                    this.attendance_time.Out.instance.setValue(v);
                    this.attendance_time.Out.value = v;
                }
            },
            myQRCode: {
                get() {
                    return this.qrcode.code;
                },
                set(v) {
                    this.qrcode.code = v;
                }
            }
        }
    }
})();
