var VPKelas = (function () {
    let vp_template = `
    <div class="card-style">
  <div style="text-align:right">
    <button title="Tambah Kelas" class="main-btn btn-sm primary-btn rounded-md btn-hover" @click="modal('show')">
      <i class="lni lni-plus"></i>
    </button>
    &nbsp;
    <button title="Segarkan" class="main-btn btn-sm success-btn rounded-md btn-hover" @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>Kode</th>
                    <th>Nama</th>
                    <th>Tingkat</th>
                    <th>Jurusan</th>
                    <th>Tahun Pelajaran</th>
                    <th>Aksi</th>
                </tr>
            </thead>
        </table>
      </div>
      </div>
      <div class="modal fade" ref="modal"  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">{{mdl.id?'Ubah':'Tambah'}} Kelas</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="input-style-1">
                      <label>Kode Kelas</label>
                      <input required v-model="mdl.kode" type="text" placeholder="Kode Kelas">
                  </div>
                  <div class="input-style-1">
                      <label>Nama Kelas</label>
                      <input required v-model="mdl.nama" type="text" placeholder="Nama Kelas">
                  </div>
                <div class="my-4">
                    <label>Tingkat</label>
                    <tomselect id="tingkat"  :options="tingkat.options" :value="tingkat.value" @changed="tingkat.value=$event" placeholder="Pilih Tingkat"  eltype="select" style="width: 100%;">
                        </tomselect>
                </div>
                <div class="my-4">
                    <label>Jurusan</label>
                    <tomselect id="jurusan"  :options="jurusan.options" :value="jurusan.value" @changed="jurusan.value=$event" placeholder="Pilih Jurusan"  eltype="select" style="width: 100%;">
                    </tomselect>
                </div>
                <div class="my-4">
                    <label>Tahun Pelajaran</label>
                    <tomselect id="tahun_pelajaran"  :options="tahun_pelajaran.options" :value="tahun_pelajaran.value" @changed="tahun_pelajaran.value=$event" placeholder="Pilih Tahun Pelajaran"  eltype="select" style="width: 100%;">
                    </tomselect>
                </div>
                  <div class="form-check form-switch toggle-switch">
                    <input class="form-check-input" type="checkbox" id="isAlumni" v-model="mdl.is_alumni"/>
                    <label class="form-check-label" for="isAlumni"> Alumni </label>
                  </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>
            </div>
          </div>
        </div>`
    return {
        name: "kelas",
        template: vp_template,

        data() {
            return {

                errorMessage: '',
                mdl: {},
                tingkat: {
                    value: '',
                    options: []
                },
                jurusan: {
                    value: '',
                    options: []
                },
                tahun_pelajaran: {
                    value: '',
                    options: []
                },
            }
        },
        mounted() {

            this.loadTingkat();
            this.loadJurusan();
            this.loadTahunPelajaran();
            this.eventListener();
            this.renderTable();
        },
        methods: {
            renderTable() {
                if (!this.tbl) this.tbl = $('#tbl').DataTable({
                    dom: 'Blfrtip',
                    colReorder: true,
                    buttons: [
                        'copy', 'excel', 'pdf', 'print'
                    ],
                    processing: true,
                    responsive: true,
                    // serverSide: true,
                    ajax: {
                        url: this.$store.state.config.base_url + '/panel/md/kelas/all?alumni=all',
                        dataSrc: 'data',
                        beforeSend: function (request) {
                            request.setRequestHeader("X-Requested-With", 'XMLHttpRequest');
                        }
                    },
                    columnDefs: [
                        {
                            targets: 2, visible: true,
                            render: function (data, type, row) {
                                return `<span class="badge bg-primary">${data.kode_tingkat || 'Tidak Ada'}</span>`;
                            }
                        }, {
                            targets: 3, visible: true,
                            render: function (data, type, row) {
                                let j = data.kode_jurusan ? data.kode_jurusan + " - " + data.nama_jurusan : "Tidak Ada";
                                return `<span class="badge bg-primary">${j}</span>`;
                            },
                        }, {
                            targets: 4, visible: true,
                            render: function (data, type, row) {
                                let j = data.kode_tahun_pelajaran ? data.kode_tahun_pelajaran + " - " + data.nama_tahun_pelajaran : "Tidak Ada";
                                return `<span class="badge bg-primary">${j}</span>`;
                            },
                        }, {

                            targets: 5, visible: true,
                            render: (data, type, row) => {
                                let url = this.$store.state.config.base_url + '/panel/md/kelas/kartu/' + data.id;
                                let btn = `<div class="d-flex justify-content-evenly ">`;
                                btn += `&nbsp;<button title="Ubah Kelas" class="btn btn-primary btn-sm 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 title="Hapus Kelas" class="btn btn-danger btn-sm rounded-md" id="trigger-delete" data-id="${data.id}"><i id="trigger-delete" data-id="${data.id}" class='lni lni-trash-can'></i></button>`;
                                if (data.is_alumni == '0') btn += `&nbsp;<button title="Kartu Ujian" class="btn btn-success rounded-md" onclick="window.open('${url}')"><i onclick="window.open('${url}')" class='fas fa-address-card'></i></button>`;
                                btn += `</div>`;
                                return btn;
                            },
                        }
                    ],
                    columns: [
                        { data: 'kode' },
                        { data: 'nama' },
                        { data: null },
                        { data: null },
                        { data: null },
                        { data: null },
                    ]
                });
            },
            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-delete') {
                        this.delete(e.target.dataset.id)
                    }
                });
                this.$refs.modal.addEventListener('hide.bs.modal', (e) => {
                    let dummymdl = {};
                    for (let key in this.mdl) {
                        if (!this.mdl.hasOwnProperty(key)) continue;
                        dummymdl[key] = null;
                    }
                    this.mdl = dummymdl;
                })
            },
            loadTingkat() {
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + "/panel/md/kelas/tingkat",
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.tingkat.options = response.data.data.map(e => {
                        return { value: parseInt(e.id), text: e.kode }
                    });
                }, (error) => {
                });
            },
            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');
                    console.log(response.data);
                    this.tahun_pelajaran.options = response.data.data.map(e => {
                        return { value: parseInt(e.id), text: `${e.nama} ` + (e.is_active == '1' ? "[ACTIVE]" : '') };
                    });
                }, (error) => {
                });
            },
            loadJurusan() {
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + "/panel/md/kelas/jurusan",
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.jurusan.options = response.data.data.map(e => {
                        return { value: parseInt(e.id), text: e.kode + " - " + e.nama }
                    });
                }, (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/md/kelas/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')
                        });
                    }
                });
            },
            detail(id) {
                showDismisableLoading();
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + "/panel/md/kelas/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.kode = response.data.data.kode;
                    this.mdl.nama = response.data.data.nama;
                    this.mdl.is_alumni = response.data.data.is_alumni == '1';
                    this.tingkat.value = response.data.data.tingkat_id;
                    this.jurusan.value = response.data.data.jurusan_id;
                    this.tahun_pelajaran.value = response.data.data.tahun_pelajaran_id;
                    this.modal("show")
                }, (error) => {
                    Swal.fire('Gagal', gaem(error), 'error')
                });
            },
            add() {
                let data = {
                    [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value,
                    kode: this.mdl.kode,
                    nama: this.mdl.nama,
                    is_alumni: this.mdl.is_alumni ? '1' : '0',
                    tingkat_id: this.tingkat.value,
                    jurusan_id: this.jurusan.value,
                    tahun_pelajaran_id: this.tahun_pelajaran.value,
                };
                this.mdl.loading = true;
                let url = this.$store.state.config.base_url + "/panel/md/kelas/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.tbl.ajax.reload(null, false)
                }, (error) => {
                    if (typeof error.response == 'undefined') return;
                    Swal.fire('Gagal', gaem(error), 'error')
                }).finally(() => this.mdl.loading = false);
            },
            edit() {
                let data = {
                    [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value,
                    kode: this.mdl.kode,
                    nama: this.mdl.nama,
                    is_alumni: this.mdl.is_alumni ? '1' : '0',
                    tingkat_id: this.tingkat.value,
                    jurusan_id: this.jurusan.value,
                    tahun_pelajaran_id: this.tahun_pelajaran.value,
                };
                this.mdl.loading = true;
                let url = this.$store.state.config.base_url + "/panel/md/kelas/edit/" + this.mdl.id
                axios({
                    method: 'PATCH',
                    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.tbl.ajax.reload(null, false)
                }, (error) => {
                    if (typeof error.response == 'undefined') return;
                    Swal.fire('Gagal', gaem(error), 'error')
                }).finally(() => this.mdl.loading = false);
            },
            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;
                }
            }
        },
    }
})();
