

var VPStaff = (function () {
    let vp_template = `
            
  <div class="card-style">
  <div style="text-align:right">
    <a class="main-btn btn-sm primary-btn rounded-md btn-hover" href="/panel/users/staff/import">
      <i class="lni lni-upload"></i>
  </a>
  &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="grid.url" :ref="grid.ref" :columns="grid.columns" :ondataload="ondataload"></grid>
      </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'}} Pegawai</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 v-if="['guru','kepsek'].includes(roles_id)" class="input-style-1">
                      <label>Nomor Induk</label>
                      <input required v-model="mdl.nomor_induk" type="text" placeholder="Nomor Induk">
                  </div>
                  <div v-if="['guru','kepsek','karyawan'].includes(roles_id)" class="input-style-2">
                      <label>RFID</label>
                      <input v-model="mdl.rfid" type="text" placeholder="RFID">
                      <span style="cursor:pointer" @click="listening=true,listen_rf(true)" class="icon"> <i @click="listening=true,listen_rf(true)" title="Klik untuk scan" class="fas fa-id-card-alt"></i> </span>
                  </div>
                  <div v-if="['guru','kepsek','karyawan'].includes(roles_id)" class="input-style-2">
                      <label>Solution ID</label>
                      <input v-model="mdl.attendance_solution_id" type="text" placeholder="Attendance Solution ID">
                  </div>
                  <div class="input-style-1">
                      <label>Nama Lengkap</label>
                      <input required v-model="mdl.fullname" type="text" placeholder="Nama Lengkap">
                  </div>
                  <div class="input-style-1">
                      <label>Username</label>
                      <input required v-model="mdl.username" type="text" placeholder="Username">
                  </div>
                  <div class="input-style-1">
                      <label>Nomor Handphone</label>
                      <input v-model="mdl.phone" type="text" placeholder="Nomor Handphone">
                  </div>
                  <div class="my-4">
                      <label>Peran</label>
                      <tomselect ref="roles" id="roles" :options="roles.options" :value="roles_id" @changed="roles_id=$event" placeholder="Pilih Peran" :multiple="true" eltype="select" style="width: 100%;">
                      </tomselect>
                  </div>
                  <div class="input-style-2">
                      <label>Kata Sandi</label>
                      <input :required="!mdl.id" v-model="mdl.password" :type="mdl.passoff?'text':'password'" placeholder="Kata Sandi">
                      <span style="cursor:pointer" @click="mdl.passoff=!mdl.passoff" class="icon"> <i :class="mdl.passoff?'mdi-eye-outline':'mdi-eye-off-outline'" class="mdi"></i> </span>
                  </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 v-show="roles_id.includes('guru')">
                <label>Kelas</label>
                <tomselect id="kelas"  :options="kelas.options" :value="kelas.value" @changed="kelas.value=$event" placeholder="Pilih Kelas"  eltype="select" style="width: 100%;">
                </tomselect>
              </div>
                  <div class="action mt-4 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>
            `;
    let gridConf = {
        ready: false,
        id: "staff-table",
        ref: "staff-table",
        url: window.location.href + "/all",
        columns: [
            {
                id: 'photo', name: "Photo", formatter: (_, row) => {
                    let photo = `
                    <div style="max-width: 60px;" class="employee-image mx-auto">
                        <img class="w-100" src="${row.cells[0].data}" alt="">
                    </div>`
                    return gridjs.html(photo);
                }
            },
            { id: 'nomor_induk', name: "Nomor Induk" }, { id: 'username', name: "Username" }, { id: "fullname", name: "Nama Lengkap" },
            {
                id: 'status',
                name: 'Status',
                formatter: (_, row) => {
                    return gridjs.html(`<span class="badge bg-${row.cells[4].data == 1 ? 'success' : 'danger'}">${row.cells[4].data == 1 ? 'Aktif' : 'Tidak Aktif'}</span>`);
                }
            },
            {
                id: 'role',
                name: 'Peran',
                formatter: (_, row) => {
                    let role = '<div class="d-flex">';
                    row.cells[5].data.forEach(r => {
                        role += `&nbsp;<span class="badge bg-primary">${r}</span>`
                    });
                    role += "</div>";
                    return gridjs.html(role);
                }
            },
            {
                id: 'nama_kelas',
                name: 'Kelas',
                formatter: (_, row) => {
                    return gridjs.html(`<span class="badge bg-primary">${row.cells[6].data ? (row.cells[8].data + " - " + row.cells[6].data) : 'Tidak Ada'}</span>`);
                }
            },
            {
                id: 'id',
                name: 'Aksi',
                formatter: (_, row) => {
                    let btn = "<div class='d-flex'>";
                    btn += `<button class="btn btn-primary rounded-md" id="user-trigger-edit" data-id="${row.cells[7].data}"><i class='lni lni-pencil-alt'></i></button>`;
                    btn += `&nbsp;<button class="btn btn-danger rounded-md" id="user-trigger-delete" data-id="${row.cells[7].data}"><i class='lni lni-trash-can'></i></button>`;
                    btn += `&nbsp;<button title="Masuk" class="btn btn-success rounded-md" id="user-trigger-login" data-id="${row.cells[7].data}"><i class='fas fa-user-ninja'></i></button>`;
                    btn += "</div>";
                    return gridjs.html(btn);
                }
            },
            {
                id: "kode_kelas",
                name: "Kode Kelas",
                hidden: true
            }
        ]
    };
    return {
        name: "staff",
        template: vp_template,

        data() {
            return {
                listening: false,
                errorMessage: '',
                mdl: {
                    status: 1,
                },
                kelas: {
                    value: '',
                    options: []
                },
                roles: {
                    value: [],
                    options: []
                },


                grid: gridConf,
            }
        },
        mounted() {
            this.loadRoles();
            this.loadKelas();
            this.eventListener();
        },
        computed: {
            roles_id: {
                get() {
                    return this.roles.value.join(',');
                },
                set(v) {
                    if (typeof v == 'string') {
                        v = v.split(',');
                    }
                    if (!v.includes('guru')) {
                        this.kelas.value = null;
                        this.mdl.nomor_induk = null;
                    }
                    this.roles.value = v.map(v => v);
                }
            }
        },
        methods: {
            eventListener() {
                document.addEventListener('click', (e) => {
                    if (e.target && e.target.id == 'user-trigger-edit') {
                        this.detail(e.target.dataset.id)
                    }
                    if (e.target && e.target.id == 'user-trigger-delete') {
                        this.delete(e.target.dataset.id)
                    }
                    if (e.target && e.target.id == 'user-trigger-login') {
                        window.open(`/panel/auth/switch/${btoa(1)}/${btoa(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;
                })
            },
            ondataload(data) {
                this.grid.ready = true;
                return data.data;
            },
            loadRoles() {
                axios({
                    method: 'get',
                    url: window.location.href + "/roles",
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');

                    this.roles.options = response.data.data.map(e => {
                        return { value: e.name, text: e.name + " | " + e.description }
                    });
                }, (error) => {
                });
            },
            loadKelas() {
                axios({
                    method: 'get',
                    url: window.location.href + "/kelas",
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');

                    this.kelas.options = response.data.data.map(e => {
                        return { value: 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: 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('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');
                    this.mdl.id = response.data.data.id;
                    this.$refs.roles.setValue(response.data.data.role);
                    this.mdl.nomor_induk = response.data.data.nomor_induk;
                    this.mdl.status = response.data.data.status;
                    this.mdl.rfid = response.data.data.rfid;
                    this.mdl.phone = response.data.data.phone;
                    this.mdl.attendance_solution_id = response.data.data.attendance_solution_id;
                    this.mdl.username = response.data.data.username;
                    this.mdl.fullname = response.data.data.fullname;
                    this.kelas.value = response.data.data.kelas_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,
                    fullname: this.mdl.fullname,
                    rfid: this.mdl.rfid,
                    nomor_induk: this.mdl.nomor_induk,
                    password: this.mdl.password,
                    phone: this.mdl.phone,
                    role: this.roles_id,
                    attendance_solution_id: this.mdl.attendance_solution_id,
                    kelas: this.kelas.value,
                    status: this.mdl.status,
                    username: this.mdl.username,
                };
                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('Gagal', gaem(error), 'error')
                }).finally(() => this.mdl.loading = false);
            },
            edit() {
                let data = {
                    [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value,
                    fullname: this.mdl.fullname,
                    password: this.mdl.password,
                    phone: this.mdl.phone,
                    rfid: this.mdl.rfid,
                    role: this.roles_id,
                    attendance_solution_id: this.mdl.attendance_solution_id,
                    nomor_induk: this.mdl.nomor_induk,
                    kelas: this.kelas.value,
                    status: this.mdl.status,
                    username: this.mdl.username,
                };
                this.mdl.loading = true;
                let url = window.location.href + "/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.$refs[this.grid.ref].reload()
                }, (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;
                }
            },
            listen_rf(first = false) {
                if (!this.listening) return
                if (first) {

                    Swal.fire({
                        title: "Silahkan Tempelkan Kartu",
                        scrollbarPadding: false,
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        allowEnterKey: false,
                        confirmButtonColor: '#d33',
                        confirmButtonText: 'Hentikan',
                        html: `
                    <div class="spinner-grow text-primary" role="status"><span class="visually-hidden">Loading...</span></div>
                    `,
                    }).then(async (result) => {
                        if (result.isConfirmed) {
                            this.listening = false;
                            Swal.close();
                        }
                    });
                }
                axios.get(window.location.href + '/rfid')
                    .then(response => {
                        if (response.data.rfid !== '') {
                            this.mdl.rfid = response.data.rfid
                            this.listening = false
                            Swal.close();
                        } else {
                            setTimeout(this.listen_rf, 500)
                        }
                    })
                    .catch(error => {
                        Swal.fire('Gagal', gaem(error), 'error')
                        this.listening = false
                    })
            }
        },
    }
})();
