var VPServers = (function () {
    let vp_template = `
    <div class="card-style">
        <div style="text-align:right">
            <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="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>Alamat</th>
                        <th>Pengecekan Terakhir</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">Server</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 mb-1">
                                <label>Nama Server</label>
                                <input type="text" v-model="mdl.name" placeholder="Nama Server" required>
                            </div>
                            <div class="input-style-1 mb-1">
                                <label>Alamat</label>
                                <input type="text" v-model="mdl.address" placeholder="Alamat" required>
                            </div>
                            <div class="input-style-1 mb-1">
                                <label>Secret Key</label>
                                <input type="password" v-model="mdl.secret_key" placeholder="Secret Key" required>
                            </div>
                            <div class="select-style-1">
                                <label>Status</label>
                                <div class="select-position">
                                    <select required v-model="mdl.status">
                                        <option value="1">Aktif</option>
                                        <option value="0">Tidak Aktif</option>
                                    </select>
                                </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>
            </div>
          </div>
        </div>

        `

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

        data() {
            return {
                data: [],
                mdl: {
                    ref: "modal",
                    nama: '',
                },
                tbl: null,
            }
        },
        mounted() {

            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/app/settings/servers/all',
                        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: 2, visible: true, render: function (data, type, row) {
                                let time = moment.unix(data.last_check).format("Y-m-d HH:mm:ss");
                                let err = data.error_count > 0 ? `Dengan error : ${data.error_count}` : '';
                                let el = `<div class="d-flex justify-content-evenly">${time} ${err}</div>`;
                                return el;
                            }
                        },
                        {
                            target: 3, 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: 4, visible: true,
                            render: function (data, type, row) {
                                let btn = `<div class="d-flex justify-content-evenly">`;
                                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 += '</div>';
                                return btn;
                            }
                        }
                    ],
                    columns: [
                        { data: 'name' },
                        { data: 'address' },
                        { 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) => {
                    this.mdl.id = null
                })
            },
            detail(id) {
                showDismisableLoading();
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + "/panel/app/settings/servers/" + 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.name = response.data.data.name;
                    this.mdl.address = response.data.data.address;
                    this.mdl.secret_key = response.data.data.secret_key;
                    this.mdl.status = response.data.data.status;
                    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/app/settings/servers/" + 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('Berhasil', response.data.message, 'success')
                        }, (error) => {
                            Swal.fire('Gagal', gaem(error), 'error')
                        });
                    }
                });
            },
            edit() {
                let data = {
                    [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value,
                    name: this.mdl.name,
                    address: this.mdl.address,
                    secret_key: this.mdl.secret_key,
                    status: this.mdl.status,
                };
                showDismisableLoading();
                this.mdl.loading = true;
                axios({
                    method: 'patch',
                    data: data,
                    url: this.$store.state.config.base_url + "/panel/app/settings/servers/" + 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,
                    name: this.mdl.name,
                    address: this.mdl.address,
                    secret_key: this.mdl.secret_key,
                    status: this.mdl.status,
                };
                showDismisableLoading();
                this.mdl.loading = true;
                axios({
                    method: 'POST',
                    data: data,
                    url: this.$store.state.config.base_url + "/panel/app/settings/servers",
                }).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);
            },
            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;
                }
            }
        },
    }
})();
