var VPAdministrator = (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="$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'}} User</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>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="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 class="select-style-1">
                      <label>Peran</label>
                      <div class="select-position">
                        <select required v-model="mdl.role">
                          <option selected disabled value="" >Pilih Peran</option>
                          <option v-for="role in roles" :value="role.value">{{role.text}}</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>`;
    let gridConf = {
        ready: false,
        id: "administrator-table",
        ref: "administrator-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: 'username', name: "Username" }, { id: "fullname", name: "Nama Lengkap" },
            {
                id: 'status',
                name: 'Status',
                formatter: (_, row) => {
                    return gridjs.html(`<span class="badge bg-${row.cells[3].data == 1 ? 'success' : 'danger'}">${row.cells[3].data == 1 ? 'Aktif' : 'Tidak Aktif'}</span>`);
                }
            },
            {
                id: 'role',
                name: 'Peran',
                formatter: (_, row) => {
                    return gridjs.html(`<span class="badge bg-primary">${row.cells[4].data}</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[5].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[5].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[5].data}"><i class='fas fa-user-ninja'></i></button>`;
                    btn += "</div>";
                    return gridjs.html(btn);
                }
            },
        ]
    };
    return {
        name: "administrator",
        template: vp_template,

        data() {
            return {
                errorMessage: '',
                mdl: {
                    status: '1',
                },

                roles: [],

                grid: gridConf,
            }
        },
        mounted() {

            this.loadRoles();
            this.eventListener();
        },
        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 = response.data.data.map(e => {
                        return { value: e.name, text: e.name + " | " + e.description }
                    });
                }, (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.mdl.role = response.data.data.role[0];
                    this.mdl.phone = response.data.data.phone;
                    this.mdl.status = response.data.data.status;
                    this.mdl.username = response.data.data.username;
                    this.mdl.fullname = response.data.data.fullname;
                    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,
                    password: this.mdl.password,
                    phone: this.mdl.phone,
                    role: this.mdl.role,
                    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,
                    role: this.mdl.role,
                    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;
                }
            }
        },
    }
})();
