var VPJadwalPelajaran = (function () {
    let gridConf = {
        ready: false,
        data: [],
        id: "jp-table",
        ref: "jp-table",
        url: window.location.href + "/all",
        columns: [{ id: 'nama_mapel', name: "Mata Pelajaran" }, { id: 'nama_guru', name: "Guru" },
        {
            id: 'sdtm', name: "Hari", formatter: (_, row) => row.cells[2].data.format("dddd")
        },
        { id: 'sdtm', name: "Jam Mulai", formatter: (_, row) => row.cells[3].data.format("HH:mm") },
        {
            id: 'edtm', name: "Jam Selesai", formatter: (_, row) => {
                console.log()
                if (row.cells[3].data.day() != row.cells[4].data.day()) return row.cells[4].data.format("dddd HH:mm");
                return row.cells[4].data.format("HH:mm");
            }
        },
        {
            id: 'nama_kelas', name: "Kelas", formatter: (_, row) => {
                let kelas = `<div class="badge text-dark">${row.cells[row.cells.length - 1].data} - ${row.cells[5].data}`;
                if (row.cells[row.cells.length - 2].data) {
                    kelas += ` | ${row.cells[row.cells.length - 2].data}`;
                }
                if (row.cells[row.cells.length - 3].data) {
                    kelas += ` | ${row.cells[row.cells.length - 3].data}`;
                }
                kelas += "</div>";
                return gridjs.html(kelas);
            }
        },
        {
            id: 'kode_tahun', name: "Tahun Pelajaran", formatter: (_, row) => gridjs.html(`<div class="badge text-dark">${row.cells[6].data} - ${row.cells[row.cells.length - 4].data} - ${row.cells[row.cells.length - 5].data}</div>`)
        },
        {
            id: 'id',
            name: 'Aksi',
            formatter: (_, row) => {
                let btn = `<div class="d-flex">`;
                btn += `&nbsp;<button class="btn btn-primary rounded-md" id="trigger-edit" data-id="${row.cells[7].data}"><i id="trigger-edit" data-id="${row.cells[7].data}" class='lni lni-pencil-alt'></i></button>`;
                btn += `&nbsp;<button class="btn btn-danger rounded-md" id="trigger-delete" data-id="${row.cells[7].data}"><i id="trigger-delete" data-id="${row.cells[7].data}" class='lni lni-trash-can'></i></button>`;
                btn += "</div>";
                return gridjs.html(btn);
            }
        },
        { id: 'semester_tahun', hidden: true },
        { id: 'nama_tahun', hidden: true },
        { id: 'kode_jurusan', hidden: true },
        { id: 'kode_tingkat', hidden: true },
        { id: 'kode_kelas', hidden: true },
        ]
    };
    let vp_template = `
    <div class="container" ref="example" id="example">    </div>
    <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" @click="modal('show')">
                <i class="lni lni-plus"></i>
            </button>
            &nbsp;
            <button class="main-btn btn-sm success-btn rounded-md btn-hover" @click="$refs[grid.ref].reload()">
                <i class="lni lni-reload"></i>
            </button>
        </div>
        <div class="table-responsive">
            <grid :id="grid.id" :limits="true" :url="urlJadwal" :ref="grid.ref" :columns="grid.columns"
                :ondataload="ondataload"></grid>
        </div>
    </div>
    <!-- Modal -->

    <div class="modal fade" ref="modal"  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">
              <h5 class="text-bold">{{mdl.id?'Ubah':'Tambah'}} Jadwal Pelajaran</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 class="my-4" >
                  <label>Kelas</label>
                  <tomselect id="kelas" :options="mdl.kelas.options" :value="mdl.kelas.value" @changed="mdl.kelas.value=$event" placeholder="Pilih Kelas"  eltype="select" style="width: 100%;">
                  </tomselect>
                </div>
                <div class="my-4" v-if="mdl.guru.show">
                  <label>Guru</label>
                  <tomselect id="guru" :options="mdl.guru.data" :value="mdl.guru.value" @changed="mdl.guru.value=$event" placeholder="Pilih Guru"  eltype="select" style="width: 100%;">
                  </tomselect>
                </div>
                <div class="my-4" >
                <label>Mata Pelajaran</label>
                  <tomselect id="mapel" :options="mdl.mapel.options" :value="mdl.mapel.value" @changed="mdl.mapel.value=$event" placeholder="Pilih Mata Pelajaran"  eltype="select" style="width: 100%;">
                  </tomselect>
                </div>
                <div class="my-4" >
                <label>Tahun Pelajaran</label>
                  <tomselect id="tahun" :options="mdl.tahun.options" :value="mdl.tahun.value" @changed="mdl.tahun.value=$event" placeholder="Pilih Tahun Pelajaran"  eltype="select" style="width: 100%;">
                  </tomselect>
                </div>
                <div class="row">
                    <div class="col-3">
                        <div class="select-style-1">
                            <label>Hari</label>
                            <div class="select-position">
                                <select required v-model="mdl.hari">
                                    <option value="1">Senin</option>
                                    <option value="2">Selasa</option>
                                    <option value="3">Rabu</option>
                                    <option value="4">Kamis</option>
                                    <option value="5">Jumat</option>
                                    <option value="6">Sabtu</option>
                                    <option value="0">Minggu</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-3">
                        <div class="input-style-2">
                            <label>Jumlah Jam</label>
                            <input required type="number" min="1" v-model="mdl.countJam" placeholder="Jumlah Jam Pelajaran">
                            <span class="icon">
                                <i class="far fa-clock">
                                </i>
                            </span>
                        </div>
                    </div>
                    <div class="col-3">
                        <div class="input-style-2">
                            <label>Jam Mulai</label>
                            <input required @change="mdl.startTime.instance.setValue(stv)" v-model="stv" placeholder="--:--">
                            <span style="cursor:pointer" class="icon">
                            <i class="far fa-clock" id="startTime" ref="startTime">
                            </i>
                            </span>
                        </div>
                    </div>
                    <div class="col-3">
                        <div class="input-style-2">
                            <label>Jam Selesai</label>
                            <input required @change="mdl.endTime.instance.setValue(etv)" v-model="etv" placeholder="--:--">
                            <span style="cursor:pointer" class="icon">
                            <i class="far fa-clock" id="endTime" ref="endTime">
                            </i>
                            </span>
                        </div>
                    </div>
                </div>
                <div class="action d-flex flex-wrap justify-content-end my-1">
                  <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>
          </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="my-4" >
                                <label>Tahun Pelajaran</label>
                                <tomselect id="tahun-pelajaran" :options="filter.tahun.options" :value="filter.tahun.value" @changed="filter.tahun.value=$event" placeholder="Pilih Tahun Pelajaran"  eltype="select" style="width: 100%;">
                                </tomselect>
                            </div>
                            <div class="my-4" >
                                <label>Kelas</label>
                                <tomselect id="filter-kelas" :options="filter.kelas.options" :value="filter.kelas.value" @changed="filter.kelas.value=$event" placeholder="Pilih Kelas"  eltype="select" style="width: 100%;">
                                </tomselect>
                            </div>
                            <div class="select-style-1">
                                <label>Hari</label>
                                <div class="select-position">
                                    <select required v-model="filter.hari">
                                    <option value="all">Semua</option>
                                        <template v-for="(h,i) in hari">
                                            <option :value="i+1">{{h}}</option>
                                        </template>
                                    </select>
                                </div>
                            </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    `;
    return {
        template: vp_template,
        name: "jadwal-pelajaran",

        data() {
            return {
                grid: gridConf,

                filter: {
                    hari: 'all',
                    kelas: {
                        value: null,
                        options: [],
                    },
                    tahun: {
                        value: null,
                        options: [],
                    },
                },
                mdl: {
                    countJam: 1,
                    startTime: {
                        value: `${(new Date()).getHours()}:${(new Date()).getMinutes()}`,
                        instance: null
                    },
                    endTime: {
                        value: `${(new Date()).getHours()}:${(new Date()).getMinutes()}`,
                        instance: null
                    },
                    guru: {
                        show: false,
                        value: null,
                        data: []
                    },
                    mapel: {
                        value: null,
                        options: [],
                        raw: [],
                    },
                    tahun: {
                        value: null,
                        options: [],
                        raw: []
                    },
                    kelas: {
                        value: null,
                        options: [],
                        raw: []
                    },
                    tahun: {
                        value: null,
                        options: [],
                        raw: []
                    },
                    hari: 1,
                },
            }
        },
        mounted() {

            this.loadConfig();
            this.timePicker();
            this.eventListener();
            this.loadMapel();
            this.loadKelas();
            this.loadTahun();
        },
        methods: {
            eventListener() {
                document.addEventListener('click', (e) => {
                    if (e.target && e.target.id == 'trigger-delete') {
                        this.delete(e.target.dataset.id)
                    }
                    if (e.target && e.target.id == 'trigger-edit') {
                        this.detail(e.target.dataset.id)
                    }
                    this.$refs.modal.addEventListener('hide.bs.modal', (e) => {
                        this.mdl.id = null;
                    });
                });
            },
            timePicker() {
                this.mdl.startTime.instance = new NJTimePicker({
                    targetID: 'startTime',
                    format: '24',
                    autoSave: true
                });
                this.mdl.endTime.instance = new NJTimePicker({
                    targetID: 'endTime',
                    format: '24',
                    autoSave: true
                });

                this.mdl.startTime.instance.on('save', (data) => {
                    if (data.fullResult.length < 6) {
                        data.fullResult += ":00";
                    }
                    this.stv = data.fullResult
                });
                this.mdl.endTime.instance.on('save', (data) => {
                    if (data.fullResult.length < 6) {
                        data.fullResult += ":00";
                    }
                    this.etv = data.fullResult
                });
                this.mdl.startTime.instance.setValue(this.stv);
                this.mdl.endTime.instance.setValue(this.etv);
            },
            detail(id) {
                showDismisableLoading();
                axios({
                    method: 'get',
                    url: window.location.href + "/detail/" + id,
                }).then((response) => {
                    Swal.close();
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    let sdtm = mm({ unix: response.data.data.startDateTime });
                    let edtm = mm({ unix: response.data.data.endDateTime });
                    this.mdl.id = response.data.data.id;
                    this.mdl.nomor = response.data.data.nomor;
                    this.mdl.countJam = response.data.data.countJam;
                    this.mdl.hari = sdtm.days();
                    this.stv = sdtm.format('HH:mm');
                    this.etv = edtm.format('HH:mm');
                    this.mdl.kelas.value = response.data.data.kelas_id;
                    this.mdl.mapel.value = response.data.data.mapel_id;
                    this.mdl.tahun.value = response.data.data.tahun_id;
                    this.mdl.guru.value = response.data.data.user_id;
                    this.modal("show")
                }, (error) => {
                    Swal.fire('Error', gaem(error), 'error')
                });
            },
            add() {
                if (this.stv.length < 5) return Swal.fire('Error', 'Waktu mulai tidak boleh kosong', 'error');
                if (this.etv.length < 5) return Swal.fire('Error', 'Waktu selesai tidak boleh kosong', 'error');
                let sdtm = mm().days(this.mdl.hari).minutes(this.stv.split(':')[1]).hours(this.stv.split(':')[0]);
                let edtm = mm().days(this.mdl.hari).minutes(this.etv.split(':')[1]).hours(this.etv.split(':')[0]);
                if (edtm.unix() < sdtm.unix()) return Swal.fire('Error', 'Waktu selesai tidak boleh lebih kecil dari waktu mulai', 'error');
                let data = {
                    [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value,
                    countJam: this.mdl.countJam,
                    startTime: sdtm.unix(),
                    endTime: edtm.unix(),
                    mapel_id: this.mdl.mapel.value,
                    kelas_id: this.mdl.kelas.value,
                    tahun_id: this.mdl.tahun.value,
                    user_id: this.mdl.guru.value
                };
                this.mdl.loading = true;
                let url = window.location.href + "/add"
                axios({
                    method: 'POST',
                    data: data,
                    url: url,
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    Swal.fire('Success', response.data.message, 'success')
                    this.modal("hide");
                    this.$refs[this.grid.ref].reload()
                }, (error) => {
                    if (typeof error.response == 'undefined') return;
                    Swal.fire('Error', gaem(error), 'error')
                }).finally(() => this.mdl.loading = false);
            },
            edit() {
                if (this.stv.length < 5) return Swal.fire('Error', 'Waktu mulai tidak boleh kosong', 'error');
                if (this.etv.length < 5) return Swal.fire('Error', 'Waktu selesai tidak boleh kosong', 'error');
                let sdtm = mm().days(this.mdl.hari).minutes(this.stv.split(':')[1]).hours(this.stv.split(':')[0]);
                let edtm = mm().days(this.mdl.hari).minutes(this.etv.split(':')[1]).hours(this.etv.split(':')[0]);
                if (edtm.unix() < sdtm.unix()) return Swal.fire('Error', 'Waktu selesai tidak boleh lebih kecil dari waktu mulai', 'error');
                let data = {
                    [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value,
                    countJam: this.mdl.countJam,
                    startTime: sdtm.unix(),
                    endTime: edtm.unix(),
                    mapel_id: this.mdl.mapel.value,
                    kelas_id: this.mdl.kelas.value,
                    tahun_id: this.mdl.tahun.value,
                    user_id: this.mdl.guru.value
                };
                console.log(sdtm.format('YYYY-MM-DD HH:mm:ss'));
                console.log(edtm.format('YYYY-MM-DD HH:mm:ss'));
                this.mdl.loading = true;
                let url = window.location.href + "/edit/" + this.mdl.id;
                axios({
                    method: 'PATCH',
                    data,
                    url,
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    Swal.fire('Success', response.data.message, 'success')
                    this.modal("hide");
                    this.$refs[this.grid.ref].reload()
                }, (error) => {
                    if (typeof error.response == 'undefined') return;
                    Swal.fire('Error', gaem(error), 'error')
                }).finally(() => this.mdl.loading = false);
            },
            loadMapel() {
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + `/panel/md/pelajaran/all`
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.mdl.mapel.raw = response.data.data;
                    this.mdl.mapel.options = response.data.data.map((v, i) => {
                        if (i == 0) this.mdl.mapel.value = v.id;
                        return { value: v.id, text: `${v.kode} - ${v.nama}` };
                    })
                }, (error) => {
                    Swal.fire('Error', gaem(error, 'Terjadi Kesalahan Saat Mengambil Data Mata Pelajaran'), 'error')
                });
            },
            loadKelas() {
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + "/panel/md/kelas/all",
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.mdl.kelas.options = response.data.data.map((e, i) => {
                        if (i == 0) this.mdl.kelas.value = e.id;
                        let k = e.kode + " - " + e.nama;
                        if (e.kode_tingkat) {
                            k += " | " + e.kode_tingkat
                        }
                        if (e.kode_jurusan) {
                            k += " | " + e.kode_jurusan
                        }
                        return { value: e.id, text: k }
                    });
                    this.filter.kelas.options = this.mdl.kelas.options;
                }, (error) => {
                });
            },
            loadTahun() {
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + `/panel/e-learning/tahun-pelajaran/all`
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.mdl.tahun.options = response.data.data.map((v, i) => {
                        if (i == 0) this.mdl.tahun.value = v.id;
                        return { value: v.id, text: `${v.kode} - ${v.nama} - ${v.semester}` }
                    });
                    this.filter.tahun.options = response.data.data.map((v, i) => {
                        if (i == 0) this.filter.tahun.value = v.id;
                        return { value: v.id, text: `${v.kode} - ${v.nama} - ${v.semester}` }
                    });
                }, (error) => {
                    Swal.fire('Error', gaem(error, 'Terjadi Kesalahan Saat Mengambil Data Tahun Pelajaran'), 'error')
                });
            },
            delete(id) {
                SwalDelete({
                    confirmed: () => {
                        showDismisableLoading();
                        axios({
                            method: 'delete',
                            data: { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value, },
                            url: window.location.href + "/delete/" + id,
                        }).then((response) => {
                            Swal.close();
                            if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                            this.$refs[this.grid.ref].reload();
                            Swal.fire(response.data.deleted ? 'Berhasil' : 'Gagal', response.data.message, response.data.deleted ? 'success' : 'error')
                        }, (error) => {
                            Swal.fire('Error', gaem(error), 'error')
                        });
                    }
                });
            },
            loadConfig() {
                axios({
                    method: 'get',
                    url: window.location.href + "/config",
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.mdl.guru.show = response.data.fieldGuru;
                    if (this.mdl.guru.show) this.loadGuru();
                }, (error) => {
                });
            },
            loadGuru() {
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + `/panel/users/staff/all?role=guru`
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.mdl.guru.data = response.data.data.map((v, i) => {
                        if (i == 0) {
                            this.mdl.guru.value = v.id;
                        }
                        return { value: v.id, text: v.fullname };
                    });
                }, (error) => {
                    Swal.fire('Error', gaem(error, 'Gagal Mengambil Data Guru'), 'error')
                });
            },
            modal(e = 'show') {
                if (!this.mdl.instance) {
                    this.mdl.instance = new bootstrap.Modal(this.$refs.modal);
                }
                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;
                }
            },
            ondataload(data) {
                this.grid.data = data.data.map(v => {
                    v.sdtm = mm({ unix: v.startDateTime });
                    v.edtm = mm({ unix: v.endDateTime });
                    return v;
                });
                this.grid.ready = true;
                return data.data;
            },
        },
        computed: {
            stv: {
                get() {
                    return this.mdl.startTime.value;
                },
                set(v) {
                    this.mdl.startTime.value = v.replace(/[^\d:]/g, '');
                }
            },
            etv: {
                get() {
                    return this.mdl.endTime.value;
                },
                set(v) {
                    this.mdl.endTime.value = v.replace(/[^\d:]/g, '');
                }
            },
            urlJadwal() {
                let url = window.location.href + "/all?";
                if (this.filter.kelas.value) url += `&kelas_id=${this.filter.kelas.value}`;
                if (this.filter.tahun.value) url += `&tahun_id=${this.filter.tahun.value}`;
                if (this.filter.hari >= 0) {
                    let date = mm().days(this.filter.hari);
                    if (date.days() < mm().days()) date.add(7, 'd');
                    url += `&startTime=${date.hours("00").minutes("00").seconds("00").unix()}`;
                    url += `&endTime=${date.hours("23").minutes("59").seconds("59").unix()}`;
                };
                return url;
            },
            hari() {
                return ["Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu", "Minggu"];
            },
        }
    }
})();
