var VPJadwal = (function () {
    let vp_template = `
    <div class="card-style">
          <div style="text-align:right">
            <button title="Filter" class="main-btn btn-sm primary-btn rounded-md btn-hover" data-bs-toggle="modal" data-bs-target="#modal-filter">
                <i class="fas fa-filter"></i>
            </button>
            &nbsp;
            <button class="main-btn btn-sm primary-btn rounded-md btn-hover" title="Bersihkan Jawaban Ujian" @click="$refs['respond'].init()">
                <i class="lni lni-write"></i>
            </button>
            &nbsp;
            <button class="main-btn btn-sm success-btn rounded-md btn-hover" title="Ubah Jadwal Ujian" @click="$refs['time'].init()">
                <i class="lni lni-calendar"></i>
            </button>
            &nbsp;
            <button  class="main-btn btn-sm primary-btn rounded-md btn-hover" title="Tambah Jadwal" @click="modal('show')">
                <i class="lni lni-plus"></i>
            </button>
            &nbsp;
            <button class="main-btn btn-sm success-btn rounded-md btn-hover" title="Segarkan" @click="tbl.ajax.reload(null,false)" >
                <i class="lni lni-reload"></i>
            </button>
          </div>
  
          <div class="table-responsive">
            <table class="table table-striped table-hover w-100" id="tbl">
                <thead>
                    <tr>
                        <th>Nama</th>
                        <th>Draft</th>
                        <th>Pengawas</th>
                        <th>Detail Ujian</th>
                        <th>Kelas</th>
                        <th>Waktu Ujian</th>
                        <th>Status</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
            </table>
          </div>
      </div>
  
      <div class="modal fade" :ref="mdl.ref"  tabindex="-1" aria-hidden="true">
          <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content card-style">
              <div class="modal-header px-0 border-0">
                <h5 class="text-bold">Jadwal Ujian</h5>
                <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">
                  <form @submit.prevent="mdl.id?edit():add()">
                  <div>

                    <div class="input-style-1 mb-1">
                        <label>Nama Jadwal</label>
                        <input type="text" v-model="mdl.nama" placeholder="Nama Jadwal" required>
                    </div>
                    <div class="">
                        <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="startTime" 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="endTime" ref="endTime">
                                    </i>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                  </div>
                  <div class="my-3">
                    <label for="tahun_pelajaran">Tahun Pelajaran</label>
                    <tomselect id="tahun_pelajaran" :options="mdl.tahun_pelajaran.options" :value="mdl.tahun_pelajaran.value" @changed="mdl.tahun_pelajaran.value=$event" placeholder="Pilih Tahun Pelajaran"  eltype="select" style="width: 100%;" required>
                    </tomselect>
                  </div>
                  <div class="my-3">
                    <label for="draft">Draft</label>
                    <tomselect id="draft" :options="mdl.draft.options" :value="mdl.draft.value" @changed="mdl.draft.value=$event" placeholder="Pilih Draft"  eltype="select" style="width: 100%;">
                    </tomselect>
                  </div>
                  <div v-if="mdl.draft.value">
                    <span v-if="draftData.kode_mapel" class="badge bg-primary mx-1">{{draftData.kode_mapel}} - {{draftData.nama_mapel}}</span>
                    <span v-if="draftData.timeout" class="badge bg-primary mx-1">{{draftData.timeout}} Menit</span>
                    <span v-if="draftData.kode_bank_soal" class="badge bg-primary mx-1">Bank Soal {{draftData.kode_bank_soal}}</span>
                    <span class="badge bg-primary mx-1">{{parseInt(draftData.count_soal_pg)+parseInt(draftData.count_soal_esai)+parseInt(draftData.count_soal_pgmulti)+parseInt(draftData.visible_pgtf)+parseInt(draftData.visible_shortentry)+parseInt(draftData.visible_pgcouple)}} Soal</span>
                    <span class="badge bg-primary mx-1">{{parseInt(draftData.visible_pg)+parseInt(draftData.visible_esai)+parseInt(draftData.visible_pgmulti)+parseInt(draftData.visible_pgtf)+parseInt(draftData.visible_shortentry)+parseInt(draftData.visible_pgcouple)}} Soal Tampil</span>
                  </div>
                  <div class="my-3">
                    <label for="pengawas">Pengawas</label>
                    <tomselect required id="pengawas" :options="mdl.pengawas.options" :value="mdl.pengawas.value" @changed="mdl.pengawas.value=$event" placeholder="Pilih Pengawas"  eltype="select" style="width: 100%;">
                    </tomselect>
                  </div>
                  <div class="my-3">
                    <label for="ruang">Ruang Ujian</label>
                    <tomselect id="ruang" :options="mdl.ruang.options" :value="mdl.ruang.value" @changed="mdl.ruang.value=$event" placeholder="Pilih Ruang"  eltype="select" style="width: 100%;">
                    </tomselect>
                  </div>
                  <div class="my-3" v-if="mdl.ruang.value&&false">
                    <span class="badge bg-primary mx-1">{{ruangData.total_siswa}} Siswa</span>
                    <template v-if="ruangData.kelas" v-for="kelas in ruangData.kelas.split(',')">
                      <span class="badge bg-primary mx-1">{{kelas}} </span>
                    </template>
                  </div>
                  <div class="my-3">
                    <label for="jenis">Jenis Ujian</label>
                    <tomselect id="jenis" :options="mdl.jenis_ujian.options" :value="mdl.jenis_ujian.value" @changed="mdl.jenis_ujian.value=$event" placeholder="Pilih Jenis"  eltype="select" style="width: 100%;" required>
                    </tomselect>
                  </div>
                    <div class="row my-3">
                        <div class="col-md-3 col-sm-6">
                            <label>Strict</label>
                            <div class="form-check form-switch my-3">
                                <input class="form-check-input" v-model="mdl.strict" type="checkbox" >
                                <label @click="mdl.strict=!mdl.strict" class="form-check-label">{{mdl.strict?'Aktif':'Tidak Aktif'}}</label>
                            </div>
                        </div>
                        <div v-if="false" class="col-md-3 col-sm-6">
                            <label>Cache Soal</label>
                            <div class="form-check form-switch my-3">
                                <input class="form-check-input" v-model="mdl.cache_soal" type="checkbox" >
                                <label @click="mdl.cache_soal=!mdl.cache_soal" class="form-check-label">{{mdl.cache_soal?'Aktif':'Tidak Aktif'}}</label>
                            </div>
                        </div>
                        <div class="col-md-3 col-sm-6">
                            <div class="input-style-1">
                                <label>AFK Timeout *Detik</label>
                                <input required v-model="mdl.afktimeout" type="number" class="remove-arrow-num" placeholder="Waktu Keluar Ujian">
                            </div>
                        </div>
                        <div class="col-md-3 col-sm-6">
                            <div class="input-style-1">
                                <label>Maksimal Pelanggaran</label>
                                <input required v-model="mdl.maxCheatCount" type="number" class="remove-arrow-num" placeholder="Maksimal Jumlah Pelanggaran">
                            </div>
                        </div>
                    </div>
                  <div class="row">
                    <div class="col-lg-3 col-md-4 col-sm-6">
                      <span>Status</span>
                      <div class="form-check form-switch">
                        <input class="form-check-input" v-model="mdl.status" type="checkbox" >
                        <label @click="mdl.status=!mdl.status" class="form-check-label">{{mdl.status?'Aktif':'Tidak Aktif'}}</label>
                      </div>
                    </div>
                    <div class="col-lg-3 col-md-4 col-sm-6">
                      <span>Token</span>
                      <div class="form-check form-switch">
                        <input class="form-check-input" v-model="mdl.use_token" type="checkbox" >
                        <label @click="mdl.use_token=!mdl.use_token" class="form-check-label">{{mdl.use_token?'Aktif':'Tidak Aktif'}}</label>
                      </div>
                    </div>
                    <div class="col-lg-3 col-md-4 col-sm-6">
                      <span>Show Point</span>
                      <div class="form-check form-switch">
                        <input class="form-check-input" v-model="mdl.show_point" type="checkbox" >
                        <label @click="mdl.show_point=!mdl.show_point" class="form-check-label">{{mdl.show_point?'Aktif':'Tidak Aktif'}}</label>
                      </div>
                    </div>
                    <div class="col-lg-3 col-md-4 col-sm-6">
                      <span>Multi Login</span>
                      <div class="form-check form-switch">
                        <input class="form-check-input" v-model="mdl.multi_login" type="checkbox" >
                        <label @click="mdl.multi_login=!mdl.multi_login" class="form-check-label">{{mdl.multi_login?'Aktif':'Tidak Aktif'}}</label>
                      </div>
                    </div>
                  </div>
                      <div class="action d-flex flex-wrap justify-content-end">
                        <button type="submit" :disabled="mdl.loading" class="main-btn btn-sm primary-btn btn-hover">
  
                          <template v-if="mdl.loading"> <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                          </template>
                          <template v-else>
                            {{mdl.id?'Simpan':'Tambah'}}
                          </template>
                        </button>
                      </div>
                  </form>
                  
                </div>
                    <div class="alert-box info-alert pl-100">
                        <div class="left">
                            <h5 class="text-bold">Info</h5>
                        </div>
                        <div class="alert">
                            <p class="text-medium">
                                Strict : Aktifkan jika ingin ujian tampilan Fullscreen.
                            </p>
                            <p v-if="false" class="text-medium ">
                                Cache Soal : Nonaktifkan jika ingin merubah soal ketika Ujian berlangsung.
                            </p>
                            <p class="text-medium">
                                Afk : Ujian akan dikeluarkan jika keluar dari browser selama ... detik
                            </p>
                            <p class="text-medium">
                                Multilogin : Aktifkan jika tidak ingin ada fitur reset sesi atau ujian dikunci.
                            </p>
                        </div>
                    </div>
              </div>
            </div>
          </div>
        </div>


        <div class="modal fade" id="modal-filter" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-lg modal-dialog-centered">
                <div class="modal-content card-style">
                    <div class="modal-header px-0 border-0">
                        <h5 class="text-bold">Filter</h5>
                        <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 class="select-style-1">
                                <label>Status</label>
                                <div class="select-position">
                                <select required v-model="filter.status">
                                    <option value="all">Semua</option>
                                    <option value="1">Aktif</option>
                                    <option value="0">Tidak Aktif</option>
                                </select>
                                </div>
                            </div>
                            <div class="select-style-1">
                                <label>Draft</label>
                                <tomselect id="filter-draft" required :options="[{ 'text': 'Semua', 'value': 'all' }, ...mdl.draft.options]" :value="filter.draft" @changed="filter.draft=$event" placeholder="Pilih Draft"  eltype="select" style="width: 100%;">
                                </tomselect>
                            </div>
                            <div class="select-style-1">
                                <label>Tahun Pelajaran</label>
                                <tomselect id="filter-tahun-pelajaran" ref="filter-tahun-pelajaran" required :options="[{ 'text': 'Semua', 'value': 'all' }, ...mdl.tahun_pelajaran.options]" :value="filter.tahun_pelajaran" @changed="filter.tahun_pelajaran=$event" placeholder="Pilih Tahun Pelajaran"  eltype="select" style="width: 100%;">
                                </tomselect>
                            </div>
                            <div class="select-style-1">
                                <label>Jenis UJian</label>
                                <div class="select-position">
                                <select required v-model="filter.jenis_ujian">
                                    <option value="all">Semua</option>
                                    <option v-for="opsi in mdl.jenis_ujian.options" :value="opsi.value">{{opsi.text}}</option>
                                </select>
                            </div>
                        </div>
                            <div class="row">
                                <div class="col-12 text-center mb-2">
                                    <label>Tanggal</label>
                                </div>
                                <div class="col-md-6">
                                    <div class="input-style-1 text-center">
                                        <label>Mulai</label>
                                        <input v-model="filter.dates.start" type="date">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="input-style-1 text-center">
                                        <label>Selesai</label>
                                        <input v-model="filter.dates.end" type="date">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <peserta-ujian ref="pu"></peserta-ujian>
        <edit-waktu :jadwal="data" ref="time"></edit-waktu>
        <clear-respond :jadwal="data" ref="respond"></clear-respond>
        `

    return {
        name: "jadwal",
        template: vp_template,

        data() {
            return {
                data: [],
                filter: {
                    status: 1,
                    draft: 'all',
                    tahun_pelajaran: 'all',
                    jenis_ujian: 'all',
                    dates: {
                        start: '',
                        end: '',
                    }
                },
                mdl: {
                    calendar: null,
                    afktimeout: 0,
                    ref: "modal",
                    nama: '',
                    maxCheatCount: 0,
                    datetime: {
                        start: {
                            instance: null,
                            date: null,
                            time: null,
                        },
                        end: {
                            instance: null,
                            date: null,
                            time: null,
                        }
                    },
                    draft: {
                        value: null,
                        options: [],
                        raw: [],
                    },
                    tahun_pelajaran: {
                        value: null,
                        options: [],
                        raw: [],
                    },
                    pengawas: {
                        value: null,
                        options: [],
                        raw: []
                    },
                    jenis_ujian: {
                        value: null,
                        options: [],
                        raw: []
                    },
                    ruang: {
                        value: null,
                        options: [],
                        raw: []
                    }
                },
            }
        },
        mounted() {

            this.loadDraft();
            this.loadTahunPelajaran();
            this.loadPengawas();
            this.loadJenisUjian();
            this.loadRuang();
            this.setWaktuPelaksanaan();
            setInterval(this.updateTimeCount, 500);
            this.eventListener();
            this.renderTable();
        },
        methods: {
            renderTable() {
                if (!this.tbl) this.tbl = $('#tbl').DataTable({
                    select: true,
                    dom: 'Blfrtip',
                    colReorder: true,
                    buttons: [
                        'copy', 'excel', 'pdf', 'print',
                        {
                            text: 'Belum Ujian',
                            action: () => {
                                let id = [];
                                let tbl = this.tbl.rows({ selected: true });
                                if (tbl.count() > 0) {
                                    tbl[0].forEach(i => {
                                        id.push($(this.tbl.row(i).node()).find('#trigger-edit')[0].dataset.id);
                                    });
                                } else {
                                    this.tbl.rows()[0].forEach(i => {
                                        id.push($(this.tbl.row(i).node()).find('#trigger-edit')[0].dataset.id);
                                    });
                                }
                                window.open(this.$store.state.config.base_url + '/panel/ujian/jadwal/export/belum-ujian?id=' + id.join(','));
                            }
                        }
                    ],
                    processing: true,
                    responsive: true,
                    // serverSide: true,
                    ajax: {
                        url: this.jadwalURL,
                        dataSrc: (data) => {
                            this.data = data.data;
                            return data.data
                        },
                        beforeSend: function (request) {
                            request.setRequestHeader("X-Requested-With", 'XMLHttpRequest');
                        }
                    },
                    columnDefs: [
                        {
                            target: 3, visible: true, render: function (data, type, row) {
                                let k = '';
                                k += `<span class="badge text-dark"><i class="lni lni-tag"></i> ${data.kode_jenis} - <i class="lni lni-book">${data.nama_mapel}</i></span><br>`;
                                k += `<span class="badge text-dark"><i class="lni lni-ruler-pencil"></i> ${data.jumlah_soal} Soal - <i class="lni lni-school-bench-alt"> ${data.nama_ruang}</i> - <i class="lni lni-users"> ${data.total_siswa}</i></span><br>`;
                                if (data.hasGenerated != '1' && data.total_siswa != '0') k += `<span style="cursor:pointer" id="trigger-generate" data-id="${data.id}" class="badge bg-danger mx-1">Belum Membuat Soal</span>`;
                                return k;
                            }
                        },
                        {
                            target: 4, visible: true, render: function (data, type, row) {
                                let k = `<div class="hide-kelas" onclick="this.classList.toggle('hide-kelas')">`;
                                let kelas = data.kelas || '';
                                kelas.split(',').forEach(v => {
                                    k += `<span class="badge bg-primary mx-1">${v}</span>`;
                                })
                                k += "</div>";
                                if (kelas.length <= 0) k = `<div class="text-center"><span style="cursor:pointer" id="trigger-peserta" data-id="${data.id}" class="badge bg-danger mx-1">Belum Ada Peserta</span></div>`;
                                return k;
                            }
                        },
                        {
                            target: 5, visible: true, render: function (data, type, row) {
                                let sdt = mm({ unix: data.startDateTime });
                                let edt = mm({ unix: data.endDateTime });

                                let time = secondsToTime(data.timeout * 60);
                                let timeout = parseTimeToString(time)
                                let k = "<div >";
                                k += `<span class="badge text-dark">Mulai : ${sdt.format('YYYY-MM-DD')} ${sdt.format('HH:mm')}</span><br>`;
                                k += `<span class="badge text-dark">Selesai : ${edt.format('YYYY-MM-DD')} ${edt.format('HH:mm')}</span><br>`;
                                k += `<span class="badge text-dark">Durasi : ${timeout.replace(/\s+/g, '') === "" ? 'Tidak Terbatas' : timeout}</span><br>`;
                                k += `<span class="badge text-dark">Token : ${data.token || "Tidak Ada"}</span><br>`;
                                k += `<span class="badge text-dark">Sudah Ujian : ${data.siswa_hadir}</span><br>`;
                                k += "</div>";
                                k += `<span class="badge text-dark" id="detail-time-${data.id}"></span>`;
                                return k;
                            }
                        },
                        {
                            target: 6, visible: true, render: function (data, type, row) {

                                let state = data.status == '1';
                                let k = `<span class="badge bg-${state ? 'success' : 'danger'}">${state ? 'Aktif' : 'Tidak Aktif'}</span>`;
                                return k;
                            }
                        },
                        {
                            target: 7, visible: true,
                            render: function (data, type, row) {
                                let btn = `<div class="d-flex justify-content-evenly">`;
                                btn += `&nbsp;<button class="btn btn-warning rounded-md" id="trigger-generate" data-id="${data.id}"><i id="trigger-generate" data-id="${data.id}" class='fas fa-cog fa-spin'></i></button>`;
                                btn += `&nbsp;<button class="btn btn-primary rounded-md" id="trigger-edit" data-id="${data.id}"><i id="trigger-edit" data-id="${data.id}" class='lni lni-pencil-alt'></i></button>`;
                                btn += `&nbsp;<button class="btn btn-danger rounded-md" id="trigger-delete" data-id="${data.id}"><i id="trigger-delete" data-id="${data.id}" class='lni lni-trash-can'></i></button>`;
                                btn += `&nbsp;<button title="Overview" class="btn btn-success rounded-md" id="trigger-overview" data-id="${data.id}"><i id="trigger-overview" data-id="${data.id}" class='lni lni-zoom-in'></i></button>`;
                                btn += `&nbsp;<button title="Peserta" class="btn btn-primary rounded-md" id="trigger-peserta" data-id="${data.id}"><i id="trigger-peserta" data-id="${data.id}" class='lni lni-users'></i></button>`;
                                btn += '</div>';
                                return btn;
                            }
                        }
                    ],
                    columns: [
                        { data: 'nama' },
                        { data: 'nama_draft' },
                        { data: 'nama_pengawas' },
                        { data: null },
                        { data: null },
                        { data: null },
                        { data: null },
                        { data: null },
                    ]
                });
            },
            setWaktuPelaksanaan() {
                // this.calendar = new bulmaCalendar(this.$refs.dtime, {
                //     dateFormat: 'yyyy-MM-dd',
                //     cancelLabel: 'Batal',
                //     clearLabel: 'Hapus',
                //     showTodayButton: false,
                //     todayLabel: 'Hari Ini',
                //     minuteSteps: 1,
                //     nowLabel: 'Sekarang',
                //     validateLabel: 'Simpan',
                //     isRange: true,
                // })
                // this.calendar.on('hide', (v) => {
                //     this.startDate = this.calendar.startDate;
                //     this.endDate = this.calendar.endDate;
                //     this.startTime = this.calendar.startTime;
                //     this.endTime = this.calendar.endTime;
                // })
                this.mdl.datetime.start.instance = new NJTimePicker({
                    targetID: 'startTime',
                    format: '24',
                    autoSave: true
                });
                this.mdl.datetime.end.instance = new NJTimePicker({
                    targetID: 'endTime',
                    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);
            },
            eventListener() {
                document.addEventListener('click', (e) => {
                    if (e.target && e.target.id == 'trigger-edit') {
                        this.detail(e.target.dataset.id)
                    }
                    if (e.target && e.target.id == 'trigger-generate') {
                        this.generate(e.target.dataset.id)
                    }
                    if (e.target && e.target.id == 'trigger-delete') {
                        this.delete(e.target.dataset.id)
                    }
                    if (e.target && e.target.id == 'trigger-peserta') {
                        this.$refs.pu.init(e.target.dataset.id)
                    }
                    if (e.target && e.target.id == 'trigger-overview') {
                        window.open("/panel/ujian/jadwal/" + btoa(e.target.dataset.id));
                    }
                });
                this.$refs.modal.addEventListener('hide.bs.modal', (e) => {
                    this.mdl.id = null
                })
            },
            generate(id) {
                SwalDelete({
                    params: {
                        title: "Generator Soal",
                        text: "Tindakan ini akan mengatur ulang semua data soal dan nilai yang sudah ada, apakah anda yakin?",
                        confirmButtonText: "Buat Soal"
                    },
                    confirmed: () => {
                        showDismisableLoading();
                        axios({
                            method: 'post',
                            url: this.$store.state.config.base_url + "/panel/ujian/jadwal/" + btoa(id) + "/generate-soal",
                            data: { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value },
                        }).then((response) => {
                            if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                            Swal.close();
                            Swal.fire('Berhasil', response.data.message, 'success')
                            this.tbl.ajax.reload(null, false)
                        }, (error) => {
                            Swal.fire('Gagal', gaem(error), 'error')
                        });
                    }
                });
            },
            detail(id) {
                showDismisableLoading();
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + "/panel/ujian/jadwal/detail/" + id,
                }).then((response) => {
                    Swal.close();
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.mdl.id = response.data.data.id;
                    this.mdl.nama = response.data.data.nama;
                    this.mdl.tahun_pelajaran.value = parseInt(response.data.data.tahun_id) || null;
                    this.mdl.draft.value = parseInt(response.data.data.draft_id) || null;
                    this.mdl.ruang.value = parseInt(response.data.data.ruang_id) || null;
                    this.mdl.jenis_ujian.value = parseInt(response.data.data.jenis_id) || null;
                    this.mdl.pengawas.value = parseInt(response.data.data.pengawas_id);
                    this.mdl.status = response.data.data.status == 1;
                    this.mdl.use_token = response.data.data.use_token == 1;
                    this.mdl.show_point = response.data.data.show_point == 1;
                    this.mdl.multi_login = response.data.data.multi_login == 1;
                    this.mdl.strict = response.data.data.strict == 1;
                    // this.mdl.cache_soal = response.data.data.cache_soal == 1;
                    this.mdl.afktimeout = response.data.data.afktimeout;
                    this.mdl.maxCheatCount = response.data.data.maxCheatCount;
                    this.startDate = mm({ unix: response.data.data.startDateTime }).format("YYYY-MM-DD")
                    this.startTime = mm({ unix: response.data.data.startDateTime }).format("HH:mm")
                    this.endDate = mm({ unix: response.data.data.endDateTime }).format("YYYY-MM-DD")
                    this.endTime = mm({ unix: response.data.data.endDateTime }).format("HH:mm")
                    this.modal("show")
                }, (error) => {
                    Swal.fire('Gagal', gaem(error), 'error')
                });
            },
            delete(id) {
                SwalDelete({
                    confirmed: () => {
                        showDismisableLoading();
                        axios({
                            method: 'delete',
                            data: { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value, },
                            url: this.$store.state.config.base_url + "/panel/ujian/jadwal/delete/" + id,
                        }).then((response) => {
                            Swal.close();
                            if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                            this.tbl.ajax.reload(null, false);
                            Swal.fire(response.data.deleted ? 'Berhasil' : 'Gagal', response.data.message, response.data.deleted ? 'success' : 'error')
                        }, (error) => {
                            Swal.fire('Gagal', gaem(error), 'error')
                        });
                    }
                });
            },
            edit() {
                let data = { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value }
                data.data = {
                    nama: this.mdl.nama,
                    tahun_id: this.mdl.tahun_pelajaran.value,
                    draft_id: this.mdl.draft.value,
                    ruang_id: this.mdl.ruang.value,
                    jenis_id: this.mdl.jenis_ujian.value,
                    pengawas_id: this.mdl.pengawas.value,
                    status: this.mdl.status == true ? '1' : '0',
                    use_token: this.mdl.use_token == true ? '1' : '0',
                    show_point: this.mdl.show_point == true ? '1' : '0',
                    multi_login: this.mdl.multi_login == true ? '1' : '0',
                    strict: this.mdl.strict,
                    // cache_soal: this.mdl.cache_soal,
                    afktimeout: this.mdl.afktimeout,
                    maxCheatCount: this.mdl.maxCheatCount,
                    startDateTime: moment(`${this.startDate} ${this.startTime}`).unix(),
                    endDateTime: moment(`${this.endDate} ${this.endTime}`).unix(),
                };

                if (!data.data.startDateTime || !data.data.endDateTime) {
                    Swal.fire('Error', 'Waktu Tidak Valid', 'error')
                    return
                } else if (data.data.startDateTime > data.data.endDateTime) {
                    Swal.fire('Error', 'Waktu Mulai/Selesai Tidak Valid', 'error')
                    return
                }
                showDismisableLoading();
                this.mdl.loading = true;
                axios({
                    method: 'put',
                    data: data,
                    url: this.$store.state.config.base_url + "/panel/ujian/jadwal/edit/" + this.mdl.id,
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    Swal.fire('Berhasil', response.data.message, 'success')
                    this.modal("hide");
                    this.tbl.ajax.reload(null, false);
                }, (error) => {
                    if (typeof error.response == 'undefined') return;
                    Swal.fire('Gagal', gaem(error), 'error')
                }).finally(() => this.mdl.loading = false);
            },
            add() {
                let data = { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value, }
                data.data = {
                    nama: this.mdl.nama,
                    tahun_id: this.mdl.tahun_pelajaran.value,
                    draft_id: this.mdl.draft.value,
                    ruang_id: this.mdl.ruang.value,
                    jenis_id: this.mdl.jenis_ujian.value,
                    pengawas_id: this.mdl.pengawas.value,
                    status: this.mdl.status == true ? '1' : '0',
                    use_token: this.mdl.use_token == true ? '1' : '0',
                    multi_login: this.mdl.multi_login == true ? '1' : '0',
                    show_point: this.mdl.show_point == true ? '1' : '0',
                    strict: this.mdl.strict,
                    // cache_soal: this.mdl.cache_soal,
                    afktimeout: this.mdl.afktimeout,
                    maxCheatCount: this.mdl.maxCheatCount,
                    startDateTime: moment(`${this.startDate} ${this.startTime}`).unix(),
                    endDateTime: moment(`${this.endDate} ${this.endTime}`).unix(),
                }

                if (!data.data.startDateTime || !data.data.endDateTime) return Swal.fire('Error', 'Waktu Tidak Valid', 'error');
                else if (data.data.startDateTime > data.data.endDateTime) return Swal.fire('Error', 'Waktu Mulai/Selesai Tidak Valid', 'error')
                showDismisableLoading();
                this.mdl.loading = true;
                axios({
                    method: 'POST',
                    data: data,
                    url: this.$store.state.config.base_url + "/panel/ujian/jadwal/add",
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    Swal.fire('Berhasil', response.data.message, 'success')
                    this.modal("hide");
                    this.tbl.ajax.reload(null, false);
                }, (error) => {
                    if (typeof error.response == 'undefined') return;
                    Swal.fire('Gagal', gaem(error), 'error')
                }).finally(() => this.mdl.loading = false);
            },
            loadTahunPelajaran() {
                axios({
                    url: this.$store.state.config.base_url + `/panel/e-learning/tahun-pelajaran/all`,
                    method: 'get',
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.mdl.tahun_pelajaran.raw = response.data.data;
                    let ftp = 'all';
                    this.mdl.tahun_pelajaran.options = response.data.data.map((v, i) => {
                        if (v.is_active == '1') {
                            this.mdl.tahun_pelajaran.value = v.id;
                            ftp = parseInt(v.id);
                        }
                        return { value: parseInt(v.id), text: `${v.nama} ` + (v.is_active == '1' ? "[ACTIVE]" : '') };
                    })
                    this.filter.tahun_pelajaran = ftp;
                }, (error) => {
                    Swal.fire('Gagal', gaem(error), 'error')
                });
            },
            loadDraft() {
                axios({
                    url: this.$store.state.config.base_url + `/panel/ujian/draft/all`,
                    method: 'get',
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.mdl.draft.raw = response.data.data;
                    this.mdl.draft.options = response.data.data.map((v, i) => {
                        if (i == 0) this.mdl.draft.value = v.id;
                        return { value: v.id, text: v.nama };
                    })
                }, (error) => {
                    Swal.fire('Gagal', gaem(error), 'error')
                });
            },
            loadPengawas() {
                let pengawas = new Promise((r, e) => {
                    axios({
                        method: 'get',
                        url: this.$store.state.config.base_url + `/panel/users/staff/all?role=pengawas`
                    }).then((response) => {
                        if (!isObject(response.data)) return e({ response });
                        r(response.data);
                    }, (error) => {
                        e(error);
                    });
                });
                let guru = new Promise((r, e) => {
                    axios({
                        method: 'get',
                        url: this.$store.state.config.base_url + `/panel/users/staff/all?role=guru`
                    }).then((response) => {
                        if (!isObject(response.data)) return e({ response });
                        r(response.data);
                    }, (error) => {
                        e(error);
                    });
                })
                Promise.all([pengawas, guru]).then(v => {
                    this.mdl.pengawas.raw = [...v[0].data, ...v[1].data];
                    this.mdl.pengawas.options = this.mdl.pengawas.raw.map((v, i) => {
                        if (i == 0) this.mdl.pengawas.value = v.id;
                        return { value: v.id, text: v.username + " - " + v.fullname };
                    })
                }).catch(error => {
                    Swal.fire('Gagal', gaem(error), 'error')
                })
            },
            loadJenisUjian() {
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + `/panel/md/jenis-ujian/all`
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.mdl.jenis_ujian.raw = response.data.data;
                    this.mdl.jenis_ujian.options = response.data.data.map((v, i) => {
                        if (i == 0) this.mdl.jenis_ujian.value = v.id;
                        return { value: v.id, text: v.kode + " - " + v.nama };
                    })
                }, (error) => {
                    Swal.fire('Gagal', gaem(error), 'error')
                });
            },
            loadRuang() {
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + `/panel/md/ruang-ujian/all`
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.mdl.ruang.raw = response.data.data;
                    this.mdl.ruang.options = response.data.data.map((v, i) => {
                        if (i == 0) this.mdl.ruang.value = v.id;
                        return { value: v.id, text: v.kode + " - " + v.nama };
                    })
                }, (error) => {
                    Swal.fire('Gagal', gaem(error), 'error')
                });
            },
            updateTimeCount() {
                if (!this.data) return;
                this.data.forEach(v => {
                    let e = document.getElementById('detail-time-' + v.id);
                    if (!e) return
                    let time = moment().unix() - v.startDateTime;
                    if (v.status != 1) return;
                    let text = ``;
                    let future = false;
                    let timeend = moment().unix() - v.endDateTime;
                    if (time < 0) {
                        //belum mulai
                        future = true;
                        time = -time;
                    }
                    time = secondsToTime(time);
                    time = `${parseTimeToString(time)} `;
                    text += time;
                    if (timeend > 0) {
                        e.innerText = "Selesai";
                        e.classList.add('bg-success');
                        e.classList.remove('text-dark');
                        e.classList.add('text-white');
                        return;
                    } else if (future) {
                        text += " Lagi";
                    } else {
                        text += " Lalu";
                    }
                    e.classList.add('text-dark');
                    e.classList.remove('text-white');
                    e.classList.remove('bg-primary');
                    e.innerText = text;
                })
            },
            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;
                }
            }
        },
        watch: {
            jadwalURL(v) {
                if (this.tbl) this.tbl.ajax.url(v).load();
            },
        },
        computed: {
            jadwalURL() {
                let url = this.$store.state.config.base_url + '/panel/ujian/jadwal/all?';
                url += `&status=${this.filter.status}`;
                url += `&draft=${this.filter.draft}`;
                url += `&jenis_ujian=${this.filter.jenis_ujian}`;
                url += `&tahun_pelajaran=${this.filter.tahun_pelajaran}`;
                if (this.filter.dates.start) {
                    let sm = moment(this.filter.dates.start + " 00:00:00");
                    if (sm.isValid()) url += `&startDate=${sm.unix()}`;
                }
                if (this.filter.dates.end) {
                    let em = moment(this.filter.dates.end + " 23:59:59");
                    if (em.isValid()) url += `&endDate=${em.unix()}`;
                }
                return url;
            },
            draftData() {
                return this.mdl.draft.raw[this.mdl.draft.raw.findIndex(v => v.id == this.mdl.draft.value)] || {};
            },
            ruangData() {
                return this.mdl.ruang.raw[this.mdl.ruang.raw.findIndex(v => v.id == this.mdl.ruang.value)] || {};
            },
            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);
                }
            }
        }
    }
})();
