var VPLogs = (function () {
    let vp_template = `
    
  <div class="card-style">
  <div style="text-align:right">
    <button class="main-btn btn-sm danger-btn rounded-md btn-hover" @click="flushlog" >
        <i class="lni lni-trash-can"></i>
    </button>
    &nbsp;
    <button  class="main-btn btn-sm primary-btn rounded-md btn-hover" @click="modal('show')">
        <i class="fas fa-filter"></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="parsedURL" :ref="grid.ref" :columns="grid.columns" :ondataload="ondataload"></grid>
  </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">Filter</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">
            <div class="select-style-1">
                <label>User</label>
                <div class="select-position">
                    <tomselect ref="users" id="users" :options="filter.users.options" :value="filter.users.value" @changed="filter.users.value=$event" placeholder="Pilih Pengguna" eltype="select" style="width: 100%;">
                    </tomselect>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="input-style-1">
                        <label>Mulai Dari</label>
                        <input class="form-control" type="date" v-model="filter.date.start" placeholder="Masukkan Tanggal Awal">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="input-style-1">
                        <label>Sampai </label>
                        <input class="form-control" type="date" v-model="filter.date.end" placeholder="Masukkan Tanggal Akhir">
                    </div>
                </div>
            </div>
        </div>
      </div>
    </div>
  </div>
</div>
    `;
    let gridConf = {
        ready: false,
        data: [],
        id: "logs-table",
        ref: "logs-table",
        columns: [
            { id: "user_id", name: "ID Pengguna", },
            {
                id: "user_type", name: "Tipe Pengguna",
                formatter: (_, row) => {
                    let k = "";
                    if (row.cells[1].data == '1') k = 'Panel';
                    else k = "Mobile";
                    return gridjs.html(k);
                }
            },
            { id: "fullname", name: "Nama Lengkap", },
            { id: "detail", name: "Rincian" },
            { id: "ip", name: "Alamat IP" },
            {
                id: "created_at", name: "Waktu Kejadian",
                formatter: (_, row) => {
                    let time = `<div class='badge text-dark'>${mm({ unix: row.cells[5].data }).format("YYYY-MM-DD HH:mm:ss")}</div>`;
                    return gridjs.html(time);
                }
            },
            {
                id: "deleted",
                hidden: true
            },
        ]
    };
    return {
        name: "logs",
        template: vp_template,
        data() {
            return {
                grid: gridConf,
                filter: {
                    date: {
                        start: mm().subtract(7, 'days').format("YYYY-MM-DD"),
                        end: mm().format("YYYY-MM-DD"),
                    },
                    users: {
                        value: 'all',
                        options: [{ value: 'all', text: 'Semua' }]
                    }
                },
                mdl: {
                    ref: "modal",
                },
            }
        },
        mounted() {
            // this.eventListener();
            this.loadUser();
        },
        methods: {
            eventListener() {
                document.addEventListener('click', (e) => {
                    if (e.target && e.target.id == 'trigger-delete') {
                        this.delete(e.target.dataset.id)
                    }
                });
            },
            flushlog() {
                SwalDelete({
                    params: {
                        title: 'Hapus Riwayat',
                        text: 'Ini akan menghapus riwayat, apakah anda yakin?',
                        type: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#3085d6',
                        cancelButtonColor: '#d33',
                        confirmButtonText: 'Ya, Hapus!'
                    },
                    confirmed: () => {
                        axios({
                            method: 'DELETE',
                            data: {
                                [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value,
                            },
                            url: this.$store.state.config.base_url + "/panel/logs",
                        }).then((response) => {
                            if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                            Swal.fire("Success", 'Berhasil menghapus riwayat', 'success');
                            this.$refs[this.grid.ref].reload()
                        }, (error) => {
                            if (typeof error.response == 'undefined') return;
                            let errMsg = gaem(error);
                            return Swal.fire('Gagal', errMsg, 'error')
                        });
                    }
                });
            },
            loadUser() {
                axios({
                    method: 'GET',
                    url: this.$store.state.config.base_url + "/panel/logs/users",
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    let uids = [];
                    let opt = response.data.filter(v => {
                        if (uids.includes(v.user_id)) return false;
                        uids.push(v.user_id);
                        return true;
                    }).map(v => {
                        return {
                            value: `${v.user_id}-${v.user_type}`,
                            text: v.fullname,
                        }
                    });
                    this.filter.users.options = [{ value: 'all', text: 'Semua' }].concat(opt);
                }, (error) => {
                    if (typeof error.response == 'undefined') return;
                    let errMsg = gaem(error);
                    return Swal.fire('Gagal', errMsg, 'error')
                });
            },
            ondataload(data) {
                this.grid.data = data.map(v => {
                    let sdt = mm({ unix: v.startDateTime });
                    let edt = mm({ unix: v.endDateTime });
                    v.startDate = sdt.format('YYYY-MM-DD');
                    v.startTime = sdt.format('HH:mm');
                    v.endDate = edt.format('YYYY-MM-DD');
                    v.endTime = edt.format('HH:mm');
                    return v;
                });
                this.grid.ready = true;
                return data;
            },
            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;
                }
            },
        },
        computed: {
            jadwal() {
                let jadwal = this.mdl.jadwal.raw.find(v => v.id == this.mdl.jadwal.value);
                if (!jadwal) return null;
                let sdt = mm({ unix: jadwal.startDateTime });
                let edt = mm({ unix: jadwal.endDateTime });
                jadwal.startDate = sdt.format('YYYY-MM-DD');
                jadwal.startTime = sdt.format('HH:mm');
                jadwal.endDate = edt.format('YYYY-MM-DD');
                jadwal.endTime = edt.format('HH:mm');
                return jadwal;
            },
            parsedURL() {
                let url = window.location.href + "/all?";
                if (this.filter.users.value != 'all') {
                    url += `&ui=${this.filter.users.value.split('-')[0]}`;
                    url += `&ut=${this.filter.users.value.split('-')[1]}`;
                }
                if (this.filter.date.start) url += `&sd=` + moment(this.filter.date.start + " 00:00:00").unix();
                if (this.filter.date.end) url += `&ed=` + moment(this.filter.date.end + " 23:59:59").unix();
                return url;
            }
        }
    }
})();
