var VPPesertaUjian = (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">Peserta 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">
                <template v-if="mdl.loading">
                <div class="text-center">
                    <span class="spinner-grow spinner-border-sm" role="status" aria-hidden="true"></span>
                </div>
                </template>
                <template v-else>
                    <div :class="mdl.addmode?'col-md-6':'col-md-12'">
                <div class="select-style-1">
                 <label>Filter Kelas</label>
                 <div class="select-position">
                  <select required v-model="kelas.value">
                    <option value="0">Semua Kelas</option>
                    <option v-for="k in kelasOption" :value="k.value">{{k.text}}</option>
                  </select>
                 </div>
                </div>

                <h6 v-if="kelas.value==0">
                  Semua Kelas
                </h6>
                <h6 v-else>
                    Kelas {{filteredKelasNama}}
                </h6>
                <small v-if="filteredPeserta.length>0">
                  Jumlah Siswa : {{filteredPeserta.length}}
                </small>
                <small v-else>
                    Tidak ada data peserta
                </small>
                <div class="input-style-1 mb-1">
                    <input type="text" v-model="peserta.query" placeholder="Cari Peserta">
                </div>
                <div title="Hapus Semua" @click="deletePeserta" style="cursor:pointer" class="border border-light shadow-sm rounded-top p-2 text-center">
                  <i class="mdi mdi-trash-can"></i>
                </div>
                <div class="siswa-list overflow-auto">
                  <template v-if="filteredPeserta.length">
                    <div v-for="siswa in filteredPeserta" :title="'Hapus Peserta '+siswa.nama" @click="peserta.raw = peserta.raw.filter(v => v.id != siswa.id)" class="border border-light shadow-sm rounded px-1 siswa-item" style="cursor:pointer;">{{siswa.nomor_induk + "/" + siswa.nama+" - "+siswa.agama+" - "+siswa.kode_tingkat+" - "+siswa.kode_kelas+" - "+siswa.kode_ruang}}</div>
                  </template>
                    <template v-else>
                    <div class="text-center my-2">
                      <span class="text-bold">Tidak Ada Siswa</span>
                    </div>
                  </template>
                </div>
                </div>
                <template v-if="mdl.addmode">
                <div class="col-md-6">
                <h6>
                Tambah Peserta
                </h6>
                <div class="row">
                    <div class="col-md-6">
                        <div class="select-style-1">
                            <label>Filter</label>
                            <div class="select-position">
                                <select required v-model="kelas.addFilterExists">
                                <option value="0">Semua</option>
                                <option value="1">Sudah Ditambahkan</option>
                                <option value="2">Belum Ditambahkan</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="select-style-1">
                            <label>Tingkat</label>
                            <div class="select-position">
                                <select @change="loadSiswa" required v-model="tingkatAdd">
                                    <option value="">Semua</option>
                                    <option v-for="k in addTingkatOption" :value="k.value">{{k.text}}</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="select-style-1">
                            <label>Jurusan</label>
                            <div class="select-position">
                                <select @change="loadSiswa" required v-model="jurusanAdd">
                                    <option value="">Semua</option>
                                    <option v-for="k in addJurusanOption" :value="k.value">{{k.text}}</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="select-style-1">
                            <label>Kelas</label>
                            <div class="select-position">
                                <select required v-model="kelasAddValue">
                                <option v-for="k in addKelasOption" :value="k.value">{{k.text}}</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="select-style-1">
                            <label>Agama</label>
                            <div class="select-position">
                                <select required v-model="agamaAdd">
                                <option v-for="k in agamaOptions" :value="k.value">{{k.text}}</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                    
                <label>Jumlah Siswa: {{filteredSiswa.length}}</label>
                <div class="input-style-1 mb-1">
                    <input type="text" v-model="kelas.addSiswaQuery" placeholder="Cari Siswa">
                </div>
                <div title="Tambah Semua" @click="addAllSiswa" style="cursor:pointer" class="border border-light shadow-sm rounded-top p-2 text-center">
                    <i class="mdi mdi-arrow-up-bold"></i>
                    <i class="mdi mdi-arrow-up-bold"></i>
                </div>
                <div class="siswa-list overflow-auto">
                  <template v-if="filteredSiswa.length">
                    <div v-for="siswa in filteredSiswa" :title="siswa.exists?'Siswa Sudah Ada':'Tambah Siswa '+siswa.nama" @click="siswa.exists?peserta.raw = peserta.raw.filter(v => v.id != siswa.id):addPeserta(siswa.id)" :class="siswa.exists?'text-white bg-primary':''" class="border border-light shadow-sm rounded px-1 siswa-item" style="cursor:pointer;">{{siswa.nomor_induk + "/" + siswa.nama+" - "+siswa.agama+" - "+siswa.kode_tingkat+" - "+siswa.kode_kelas+" - "+siswa.kode_ruang}}</div>
                  </template>
                  <template v-else>
                    <div class="text-center my-2">
                      <span class="text-bold">Tidak Ada Siswa</span>
                    </div>
                  </template>
                </div>
                </div>
                </template>


                </template>
              </div>
            </div>
            </div>
            
            <div class="modal-footer px-0">
                <button type="button" @click="mdl.addmode=!mdl.addmode" v-if="!mdl.addmode" class="main-btn btn-sm primary-btn btn-hover">
                        Tambah Peserta
                </button>
                <button type="button" @click="simpanPeserta()" :disabled="mdl.loading" class="main-btn btn-sm success-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>
                        Simpan
                    </template>
                </button>
            </div>

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

                errorMsg: '',
                mdl: {
                    addmode: false,
                    ref: 'modal',
                },
                peserta: {
                    query: '',
                    raw: [],
                },
                tingkatAdd: '',
                jurusanAdd: '',
                agamaAdd: 'all',
                agamaOptions: [
                    { value: 'all', text: 'Semua' },
                    { value: 'islam', text: 'Islam' },
                    { value: 'katolik', text: 'Katolik' },
                    { value: 'protestan', text: 'Protestan' },
                    { value: 'hindu', text: 'Hindu' },
                    { value: 'buddha', text: 'Buddha' },
                    { value: 'konghucu', text: 'Konghucu' },
                ],
                kelas: {
                    value: 0,
                    addSiswaQuery: '',
                    addvalue: null,
                    addFilterExists: 0,
                    siswa: [],
                    raw: [],
                },
            }
        },
        mounted() {
            this.eventListener();
            this.loadKelas();
        },
        methods: {
            init(jadwalId) {
                this.jadwalId = jadwalId;
                this.loading = true;
                if (!this.kelasAddValue && this.kelas.raw.length > 1) this.kelasAddValue = this.kelas.raw[0].id;
                this.loadPeserta();
                this.modal('show');
            },
            loadKelas() {
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + "/panel/md/kelas/all",
                }).then((response) => {
                    this.kelas.raw = response.data.data;
                }, (error) => {
                });
            },
            loadPeserta() {
                this.mdl.loading = true;
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + "/panel/ujian/jadwal/" + btoa(this.jadwalId) + "/peserta",
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.peserta.raw = response.data.data;
                }, (error) => {
                    if (typeof error.response == 'undefined') return;
                    Swal.fire('Gagal', gaem(error), 'error')
                }).finally(() => this.mdl.loading = false);
            },
            loadSiswa() {
                this.errorMsg = '';
                if (this.kelasAddValue == '') {
                    let url = this.$store.state.config.base_url + "/panel/md/siswa/all?";
                    if (this.jurusanAdd) url += "&jurusan=" + this.jurusanAdd;
                    if (this.tingkatAdd) url += "&tingkat=" + this.tingkatAdd;
                    axios({
                        method: 'get',
                        url,
                    }).then((response) => {
                        if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                        this.kelas.siswa = response.data.data;
                    }, (error) => {
                        if (typeof error.response == 'undefined') return;
                        Swal.fire('Gagal', gaem(error), 'error')
                    });
                } else {

                    axios({
                        method: 'get',
                        url: this.$store.state.config.base_url + "/panel/md/siswa/kelas/" + this.kelasAddValue + "/siswa",
                    }).then((response) => {
                        if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                        this.kelas.siswa = response.data.data.siswa;
                    }, (error) => {
                        if (typeof error.response == 'undefined') return;
                        Swal.fire('Gagal', gaem(error), 'error')
                    });
                }
            },
            deletePeserta() {
                if (this.kelas.value == 0) this.peserta.raw = [];
                if (this.kelas.value != 0) this.peserta.raw = this.peserta.raw.filter(v => v.kelas_id != this.kelas.value);
            },
            addAllSiswa() {
                this.filteredSiswa.forEach(elem => {
                    this.addPeserta(elem.id);
                })
            },
            addPeserta(id) {
                let siswa = this.peserta.raw.findIndex(p => p.id == id);
                if (siswa != -1) return;
                this.peserta.raw.push(this.kelas.siswa[this.kelas.siswa.findIndex(v => v.id == id)]);
            },
            simpanPeserta(force = false) {
                if (this.mdl.loading) return;
                let data = { peserta: [], [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value }
                data.peserta = this.peserta.raw.map(v => {
                    return v.id
                })
                if (force) data['force-save'] = true
                this.errorMsg = '';
                this.mdl.loading = true;
                showDismisableLoading();
                axios({
                    method: 'put',
                    data: data,
                    url: this.$store.state.config.base_url + "/panel/ujian/jadwal/" + btoa(this.jadwalId) + "/peserta",
                }).then((response) => {
                    Swal.close()
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    return Swal.fire('Berhasil', "Berhasil menambah", 'success')
                }, (error) => {
                    Swal.close()
                    if (typeof error.response == 'undefined') return;
                    let errMsg = gaem(error);
                    try {
                        if (!error.response.data.messages.confirmation) return Swal.fire('Gagal', errMsg, 'error')
                    } catch (error) {
                        return Swal.fire('Gagal', errMsg, 'error')
                    }
                    SwalDelete({
                        params: { confirmButtonText: 'Ya, Simpan!', text: errMsg },
                        confirmed: () => this.simpanPeserta(true)
                    });
                }).finally(() => this.mdl.loading = false);
            },
            eventListener() {
                this.$refs[this.mdl.ref].addEventListener('hide.bs.modal', (e) => {
                    this.mdl.loading = false;
                    this.mdl.addmode = 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;
                }
            }
        },
        watch: {
            kelasAddValue() {
                this.loadSiswa();
            }
        },
        computed: {
            kelasOption() {
                let data = this.kelas.raw;
                data = data.filter(v => this.peserta.raw.findIndex(p => p.kelas_id == v.id) != -1);
                return data.map(v => {
                    let k = v.kode + " - " + v.nama;
                    if (v.kode_tingkat) {
                        k += " | " + v.kode_tingkat
                    }
                    if (v.kode_jurusan) {
                        k += " | " + v.kode_jurusan
                    }
                    return { value: v.id, text: k }
                });
            },
            addTingkatOption() {
                let data = [];
                this.kelas.raw.forEach(elem => {
                    if (!elem.tingkat_id) return;
                    if (data.findIndex(v => v.value == elem.tingkat_id) == -1) {
                        data.push({ value: elem.tingkat_id, text: elem.kode_tingkat })
                    }
                })
                return data;
            },
            addJurusanOption() {
                let data = [];
                this.kelas.raw.forEach(elem => {
                    if (!elem.jurusan_id) return;
                    if (data.findIndex(v => v.value == elem.jurusan_id) == -1) {
                        data.push({ value: elem.jurusan_id, text: elem.kode_jurusan + " - " + elem.nama_jurusan })
                    }
                })
                return data;
            },
            addKelasOption() {
                let k = this.kelas.raw.filter(v => {
                    if (!this.jurusanAdd && !this.tingkatAdd) return true;
                    if (!this.jurusanAdd && this.tingkatAdd && v.tingkat_id == this.tingkatAdd) {
                        return true;
                    }
                    if (!this.tingkatAdd && this.jurusanAdd && v.jurusan_id == this.jurusanAdd) {
                        return true;
                    }
                    if (this.jurusanAdd && v.jurusan_id == this.jurusanAdd && this.tingkatAdd && v.tingkat_id == this.tingkatAdd) return true;
                    return false;
                }).map(v => {
                    let k = v.kode + " - " + v.nama;
                    if (v.kode_tingkat) {
                        k += " | " + v.kode_tingkat
                    }
                    if (v.kode_jurusan) {
                        k += " | " + v.kode_jurusan
                    }
                    return { value: v.id, text: k }
                });
                let data = [{ value: '', text: 'Semua' }, ...k];
                if (data.length) {
                    let exists = data.findIndex(v => v.value == this.kelasAddValue);
                    if (exists == -1) {
                        this.kelasAddValue = data[0].value;
                    }
                }
                return data;
            },
            kelasAddValue: {
                get() {
                    return this.kelas.addvalue;
                },
                set(id) {
                    this.kelas.addvalue = id;
                }
            },
            filteredKelasNama() {
                this.kelasOption.forEach(v => {
                    if (v.value == this.kelas.value) return v.text;
                });
                return '';
            },
            filteredSiswa() {
                let data = this.kelas.siswa;
                data.map(v => {
                    v.exists = this.peserta.raw.findIndex(p => p.id == v.id) != -1;
                    return v;
                });
                if (this.kelas.addSiswaQuery) data = data.filter(v => {
                    return (v.nomor_induk + "/" + v.nama + " - " + v.agama + " - " + v.kode_ruang).toLocaleLowerCase().includes(this.kelas.addSiswaQuery.toLocaleLowerCase());
                });
                if (this.kelas.addFilterExists == 1) data = data.filter(v => {
                    return v.exists;
                });
                if (this.kelas.addFilterExists == 2) data = data.filter(v => {
                    return !v.exists;
                });
                if (this.agamaAdd != 'all') data = data.filter(v => {
                    if (v.agama != this.agamaAdd) return false;
                    return !v.exists;
                });
                return data;
            },
            filteredPeserta() {
                let data = this.peserta.raw;
                if (this.kelas.value == 0 && !this.peserta.query) return data;
                return data.filter(v => {
                    if (!this.peserta.query) return v.kelas_id == this.kelas.value
                    return (v.nomor_induk + "/" + v.nama + " - " + v.agama).toLocaleLowerCase().includes(this.peserta.query.toLocaleLowerCase());
                });
            }
        }
    }
})();
