var VPASDevice = (function () {
    let vp_template = `
    
  <div class="card-style">
    <div style="text-align:right">
        <button title="Tambah Perangkat" 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" id="refresh-btn" @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>IP</th>
                    <th>Port</th>
                    <th>Status</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'}} Perangkat</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()">
                  <input type="text" hidden="true">
                  <div class="input-style-1">
                      <label>Nama</label>
                      <input required v-model="mdl.nama" type="text" placeholder="Nama">
                  </div>
                  <div class="input-style-1">
                      <label>IP</label>
                      <input required v-model="mdl.ip" type="text" placeholder="IP">
                    </div>
                    <div class="input-style-1">
                        <label>Port</label>
                        <input required v-model="mdl.port" type="number" min="80" placeholder="Port">
                    </div>
                    <div class="input-style-1">
                        <label>Comm Key</label>
                        <input required v-model="mdl.commKey" type="number" min="0" placeholder="Comm Key">
                    </div>
                  <div class="my-4">
                    <label>Status</label>
                    <select class="form-select" v-model="mdl.is_active">
                        <option value="1">Aktif</option>
                        <option value="0">Tidak Aktif</option>
                    </select>
                  </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: "asdevice",

        template: vp_template,
        data() {
            return {
                mdl: {
                    is_active: '1'
                },
            }
        },
        mounted() {
            this.renderTable();
            this.eventListener();
        },
        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/attendance-solution/device/all',
                        dataSrc: 'data',
                        beforeSend: function (request) {
                            request.setRequestHeader("X-Requested-With", 'XMLHttpRequest');
                        }
                    },
                    columnDefs: [
                        {
                            target: 3, visible: true, render: function (data, type, row) {
                                let t = `<div class="text-center">`;
                                if (data.is_active == '1') t += `<span title="Aktif" class="badge bg-success m-1">Aktif</span>`;
                                else t += `<span title="Tidak Aktif" class="badge bg-danger m-1">Tidak Aktif</span>`;
                                if (data.is_connected == '1') t += `<span title="Terhubung" class="badge bg-success m-1">Terhubung</span>`;
                                else t += `<span id="check-connection" style="cursor:pointer" data-id="${data.id}" title="Cek Koneksi" class="badge bg-danger m-1">Tidak Terhubung</span>`;
                                t += "</div>";
                                return t;
                            }
                        },
                        {
                            targets: 4, visible: true,
                            render: (data, type, row) => {
                                let btn = `<div class="d-flex justify-content-evenly">`;
                                btn += `&nbsp;<button title="Ubah" 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 title="Hapus" 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: 'nama' },
                        { data: 'ip' },
                        { data: 'port' },
                        { 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)
                    }
                    if (e.target && e.target.id == 'check-connection') {
                        this.checkConnection(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;
                })
            },
            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.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')
                        });
                    }
                });
            },
            checkConnection(id) {
                showDismisableLoading();
                axios({
                    method: 'get',
                    url: window.location.href + "/check-connection/" + id,
                }).then((response) => {
                    Swal.close();
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    if (!response.data) return Swal.fire('Error', 'Data tidak ditemukan', 'error');
                    this.tbl.ajax.reload(null, false)
                    Swal.fire("Success", response.data.message, 'success');
                }, (error) => {
                    Swal.fire('Gagal', gaem(error), 'error')
                });
            },
            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');
                    if (!response.data) return Swal.fire('Error', 'Data tidak ditemukan', 'error');
                    this.mdl.id = response.data.id;
                    this.mdl.nama = response.data.nama;
                    this.mdl.ip = response.data.ip;
                    this.mdl.port = response.data.port;
                    this.mdl.commKey = response.data.commKey;
                    this.mdl.is_active = response.data.is_active;
                    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,
                    nama: this.mdl.nama,
                    ip: this.mdl.ip,
                    port: this.mdl.port,
                    commKey: this.mdl.commKey,
                    is_active: this.mdl.is_active,
                };
                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.tbl.ajax.reload(null, false)
                }, (error) => {
                    if (typeof error.response == 'undefined') return;
                    Swal.fire('Error', gaem(error), 'error')
                }).finally(() => this.mdl.loading = false);
            },
            edit() {
                let data = {
                    [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value,
                    nama: this.mdl.nama,
                    ip: this.mdl.ip,
                    port: this.mdl.port,
                    commKey: this.mdl.commKey,
                    is_active: this.mdl.is_active,
                };
                this.mdl.loading = true;
                let url = window.location.href + "/edit/" + this.mdl.id
                axios({
                    method: 'PUT',
                    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('Error', 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;
                }
            }
        },
    }
})();
