var VPEditWaktu = (function () {
    let template = `
    <div class="modal fade" :ref="mdl.ref"  tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-centered">
          <div class="modal-content card-style">
            <div class="modal-header px-0 border-0">
              <h4 class="text-bold">Ubah Waktu Ujian</h4>
              <button class="border-0 bg-transparent h1" data-bs-dismiss="modal">
                <i class="lni lni-cross-circle"></i>
              </button>
            </div>
            <div class="modal-body px-0">
              <div class="content">
                <div v-show="errorMsg" class="alert custom-alert-2 alert-danger alert-dismissible fade show" role="alert"><i class="bi bi-x-circle"></i>{{errorMsg}}
                    <button class="btn btn-close btn-close-white position-relative p-1 ms-auto" type="button" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <div class="row">
                  <div class="col-md-3 col-sm-6 col-xs-12">
                    <span>Status</span>
                    <div class="form-check form-switch">
                      <input class="form-check-input" v-model="status" type="checkbox" >
                      <label @click="status=!status" class="form-check-label">{{status?'Aktif':'Tidak Aktif'}}</label>
                    </div>
                  </div>
                  <div class="col-md-3 col-sm-6 col-xs-12">
                    <span>Token</span>
                    <div class="form-check form-switch">
                      <input class="form-check-input" v-model="use_token" type="checkbox" >
                      <label @click="use_token=!use_token" class="form-check-label">{{use_token?'Aktif':'Tidak Aktif'}}</label>
                    </div>
                  </div>
                  <div class="col-md-3 col-sm-6 col-xs-12">
                    <span>Show Point</span>
                    <div class="form-check form-switch">
                      <input class="form-check-input" v-model="show_point" type="checkbox" >
                      <label @click="show_point=!show_point" class="form-check-label">{{show_point?'Aktif':'Tidak Aktif'}}</label>
                    </div>
                  </div>
                  <div class="col-md-3 col-sm-6 col-xs-12">
                    <span>Multi Login</span>
                    <div class="form-check form-switch">
                      <input class="form-check-input" v-model="multi_login" type="checkbox" >
                      <label @click="multi_login=!multi_login" class="form-check-label">{{multi_login?'Aktif':'Tidak Aktif'}}</label>
                    </div>
                  </div>

                  <div>
                    <label>Waktu Pelaksanaan</label>
                    <div class="row">
                        <div class="col-sm-6 col-xs-12">
                            <div class="input-style-1">
                                <label>Tanggal Mulai</label>
                                <input required type="date" v-model="startDate" placeholder="--:--">
                            </div>
                        </div>
                        <div class="col-sm-6 col-xs-12">
                            <div class="input-style-2">
                                <label>Jam Mulai</label>
                                <input required v-model="startTime" placeholder="--:--">
                                <span style="cursor:pointer" class="icon">
                                <i class="far fa-clock" id="ewstartTime" ref="startTime">
                                </i>
                                </span>
                            </div>
                        </div>
                        <div class="col-sm-6 col-xs-12">
                            <div class="input-style-1">
                                <label>Tanggal Selesai</label>
                                <input required type="date" v-model="endDate" placeholder="--:--">
                            </div>
                        </div>
                        <div class="col-sm-6 col-xs-12">
                            <div class="input-style-2">
                                <label>Jam Selesai</label>
                                <input required v-model="endTime" placeholder="--:--">
                                <span style="cursor:pointer" class="icon">
                                <i class="far fa-clock" id="ewendTime" ref="endTime">
                                </i>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                  <template v-if="query">
                  Jadwal {{filteredJadwal.length}} dari {{jadwalUjian.length}} 
                  </template>
                  <template v-else>
                  Jadwal : {{filteredJadwal.length}}
                  </template>
                    <div class="input-style-1 my-1">
                        <input type="text" v-model="query" placeholder="Cari Jadwal">
                    </div>
                    <div class="siswa-list overflow-auto">
                      <template v-if="filteredJadwal.length">
                        <div v-for="j in filteredJadwal" :title="j.selected?'Jadwal Sudah Dipilih':'Pilih Jadwal'" @click="j.selected=!j.selected" :class="j.selected?'text-white bg-primary':''" class="border border-light shadow-sm rounded px-1 siswa-item" style="cursor:pointer;">{{j.nama}}</div>
                      </template>
                      <template v-else>
                        <div class="text-center my-2">
                          <span v-if="loading" class="text-bold">Sedang Memuat...</span>
                          <span v-else class="text-bold">Tidak Ada Jadwal</span>
                        </div>
                      </template>
                    </div>
                </div>

              </div>
            </div>
            
            <div class="modal-footer px-0">
                <button v-if="startDate&&endDate&&startTime&&endTime&&jadwalUjian.filter(v=>v.selected).length>0" type="button" @click="simpanWaktu" :disabled="loading" class="main-btn btn-sm success-btn btn-hover">
                    <template v-if="loading"> 
                        <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                    </template>
                    <template v-else>
                        Simpan
                    </template>
                </button>
            </div>

          </div>
        </div>
    </div>`;
    return {
        name: "edit-waktu",
        template: template,
        data() {
            return {

                errorMsg: '',
                mdl: {
                    ref: 'modal',
                    datetime: {
                        start: {
                            instance: null,
                            date: null,
                            time: null,
                        },
                        end: {
                            instance: null,
                            date: null,
                            time: null,
                        }
                    },
                },
                loading: false,
                jadwal: [],
                query: '',
                status: false,
                use_token: false,
                show_point: false,
                multi_login: false,
            }
        },
        mounted() {
            this.eventListener();
            this.setWaktuPelaksanaan();
        },
        methods: {

            setWaktuPelaksanaan() {
                this.mdl.datetime.start.instance = new NJTimePicker({
                    targetID: 'ewstartTime',
                    format: '24',
                    autoSave: true
                });
                this.mdl.datetime.end.instance = new NJTimePicker({
                    targetID: 'ewendTime',
                    format: '24',
                    autoSave: true
                });

                this.mdl.datetime.start.instance.on('save', (data) => {
                    if (data.fullResult.length < 6) {
                        data.fullResult += ":00";
                    }
                    this.startTime = data.fullResult
                });
                this.mdl.datetime.end.instance.on('save', (data) => {
                    if (data.fullResult.length < 6) {
                        data.fullResult += ":00";
                    }
                    this.endTime = data.fullResult
                });
                this.mdl.datetime.start.instance.setValue(this.mdl.datetime.start.time);
                this.mdl.datetime.end.instance.setValue(this.mdl.datetime.end.time);
            },
            init(refresh = false) {
                if (refresh || this.jadwal.length < 1) this.loadJadwal();
                this.modal('show');
            },
            loadJadwal() {
                this.loading = true;
                axios({
                    method: 'get',
                    url: window.location.href + "/all",
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.jadwal = response.data.data;
                }, (error) => {
                    if (typeof error.response == 'undefined') return;
                    Swal.fire('Gagal', gaem(error), 'error')
                }).finally(() => this.loading = false);
            },
            simpanWaktu() {
                if (this.loading) return;
                let data = {
                    [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value,
                    jadwals: []
                }
                let start = moment(`${this.startDate} ${this.startTime}`).unix();
                let end = moment(`${this.endDate} ${this.endTime}`).unix();
                if (!start || !end) {
                    Swal.fire('Error', 'Waktu Tidak Valid', 'error')
                    return
                } else if (start > end) {
                    Swal.fire('Error', 'Waktu Mulai/Selesai Tidak Valid', 'error')
                    return
                }
                data.jadwals = this.jadwalUjian.filter(v => v.selected).map(v => {
                    return {
                        id: v.id,
                        startDateTime: start,
                        endDateTime: end,
                        status: this.status ? '1' : '0',
                        use_token: this.use_token ? '1' : '0',
                        show_point: this.show_point ? '1' : '0',
                        multi_login: this.multi_login ? '1' : '0'
                    }
                })
                this.errorMsg = '';
                this.loading = true;
                axios({
                    method: 'put',
                    data,
                    url: this.$store.state.config.base_url + "/panel/ujian/jadwal/batch/time",
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    return Swal.fire('Berhasil', 'Data berhasil diubah', 'success');
                }, (error) => {
                    if (typeof error.response == 'undefined') return;
                    Swal.fire('Gagal', gaem(error), 'error')
                }).finally(() => this.loading = false);
            },
            eventListener() {
                this.$refs[this.mdl.ref].addEventListener('hide.bs.modal', (e) => {
                    this.loading = false;
                })
            },
            modal(e = 'show') {
                if (!this.mdl.instance) {
                    this.mdl.instance = new bootstrap.Modal(this.$refs[this.mdl.ref]);
                }
                switch (e) {
                    case "hide":
                        this.mdl.instance.hide();
                        break;
                    case "show":
                        this.mdl.instance.show();
                        break;
                    case "toggle":
                        this.mdl.instance.toggle();
                        break;
                    case "dispose":
                        this.mdl.instance.dispose();
                        break;
                }
            }
        },
        computed: {
            filteredJadwal() {
                if (!this.query) return this.jadwalUjian;
                return this.jadwalUjian.filter(v => {
                    return v.nama_draft.toLowerCase().includes(this.query.toLowerCase()) || v.nama.toLowerCase().includes(this.query.toLowerCase());
                })
            },
            jadwalUjian() {
                return this.jadwal.map(v => {
                    v.selected = false;
                    v.nama = `${v.nama} - ${v.nama_draft} - `;
                    let sdt = mm({ unix: v.startDateTime });
                    let edt = mm({ unix: v.endDateTime });
                    v.startDate = sdt.format('YYYY-MM-DD');
                    v.startTime = sdt.format('HH:mm');
                    v.endDate = edt.format('YYYY-MM-DD');
                    v.endTime = edt.format('HH:mm');
                    if (v.startDate == v.endDate) {
                        v.nama += `${v.startDate} ${v.startTime} s/d ${v.endTime}`;
                    } else {
                        v.nama += `${v.startDate} ${v.startTime} s/d ${v.endDate}  ${v.endTime}`;
                    }
                    return v;
                })
            },
            startDate: {
                get() {
                    return moment(this.mdl.datetime.start.date).format('YYYY-MM-DD');
                },
                set(v) {
                    this.mdl.datetime.start.date = moment(new Date(v)).format('YYYY-MM-DD')
                    this.calendar.startDate = this.mdl.datetime.start.date;
                    this.calendar.refresh();
                    this.calendar.save();
                }
            },
            endDate: {
                get() {
                    return moment(this.mdl.datetime.end.date).format('YYYY-MM-DD');
                },
                set(v) {
                    this.mdl.datetime.end.date = moment(new Date(v)).format('YYYY-MM-DD')
                    this.calendar.endDate = this.mdl.datetime.end.date;
                    this.calendar.refresh();
                    this.calendar.save();
                }
            },
            startTime: {
                get() {
                    return this.mdl.datetime.start.time || "00:00";
                },
                set(v) {
                    this.mdl.datetime.start.time = moment(v, "HH:mm:ss").format('HH:mm')
                    this.calendar.startTime = this.mdl.datetime.start.time;
                    this.calendar.refresh();
                    this.calendar.save();
                    this.mdl.datetime.start.instance.setValue(this.mdl.datetime.start.time);
                }
            },
            endTime: {
                get() {
                    return this.mdl.datetime.end.time || "00:00";
                },
                set(v) {
                    this.mdl.datetime.end.time = moment(v, "HH:mm:ss").format('HH:mm')
                    this.calendar.endTime = this.mdl.datetime.end.time;
                    this.calendar.refresh();
                    this.calendar.save();
                    this.mdl.datetime.end.instance.setValue(this.mdl.datetime.end.time);
                }
            }
        }
    }
})();
