var VPPresence = (function () {
    let gridConf = {
        ready: false,
        data: [],
        id: "p-table",
        ref: "p-table",
        columns: [
            { id: 'id', name: 'ID', },
            { id: 'nomor_induk', name: 'Nomor Induk', },
            {
                id: 'presence_status', name: 'Kehadiran',
                formatter: (_, row) => {
                    let status = "";
                    switch (row.cells[2].data) {
                        case '1':
                            status = "Hadir"
                            break;
                        case '2':
                            status = "Alpa"
                            break;
                        case '3':
                            status = "Sakit"
                            break;
                        case '4':
                            status = "Izin"
                            break;
                    }
                    let btn = `<div class="badge bg-primary">${status}</div>`;
                    return gridjs.html(btn);
                }
            },
            {
                id: 'status', name: 'Status',
                formatter: (_, row) => {
                    let status = "";
                    let cl = "";
                    switch (row.cells[3].data) {
                        case '1':
                            status = "Menunggu";
                            cl = "warning";
                            break;
                        case '2':
                            status = "Disetujui"
                            cl = "success";
                            break;
                        case '3':
                            status = "Ditolak"
                            cl = "danger";
                            break;
                        case '4':
                            status = "Dibatalkan"
                            cl = "danger";
                            break;
                    }
                    let btn = `<div class="badge bg-${cl}">${status}</div>`;
                    return gridjs.html(btn);
                }
            }, {
                id: 'tanggal', name: 'Tanggal', formatter: (_, row) => {
                    let btn = `<div class="badge text-dark">${row.cells[4].data}</div>`;
                    return gridjs.html(btn);
                }
            }, { id: 'user_name', name: 'Pembuat', }, { id: 'editor_name', name: 'Pengubah', }, { id: 'cam', name: 'Dibuat Pada', formatter: (_, row) => row.cells[7].data.format("YYYY-MM-DD HH:mm") }, { id: 'uam', name: 'Diubah Pada', formatter: (_, row) => row.cells[8].data.format("YYYY-MM-DD HH:mm") },
            {
                name: 'Aksi',
                formatter: (_, row) => {
                    let btn = `<div class="d-flex">`;
                    btn += `&nbsp;<button class="btn btn-primary rounded-md" id="trigger-detail" data-id="${row.cells[0].data}"><i id="trigger-detail" data-id="${row.cells[0].data}" class='fas fa-eye'></i></button>`;
                    if (row.cells[3].data == '1') {
                        btn += `&nbsp;<button class="btn btn-danger rounded-md" id="trigger-decline" data-id="${row.cells[0].data}"><i id="trigger-decline" data-id="${row.cells[0].data}" class='fas fa-user-times'></i></button>`;
                        btn += `&nbsp;<button class="btn btn-success rounded-md" id="trigger-approve" data-id="${row.cells[0].data}"><i id="trigger-approve" data-id="${row.cells[0].data}" class='fas fa-user-check'></i></button>`;
                    }
                    btn += "</div>";
                    return gridjs.html(btn);
                }
            },
        ]
    };
    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="filterModal('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="curl" :ref="grid.ref" :columns="grid.columns"
                :ondataload="ondataload"></grid>
        </div>
    </div>
    <!-- Modal -->

    <div class="modal fade" ref="filterModal"  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 Persetujuan Kehadiran</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="row">
                <div class="col-md-6">
                    <div class="input-style-1">
                        <label>Mulai</label>
                        <input v-model="filter.startDate" type="date" min="1988-01-01" placeholder="Tanggal Diajukan">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="input-style-1">
                        <label>Akhir</label>
                        <input v-model="filter.endDate" type="date" min="1988-01-01" placeholder="Tanggal Diajukan">
                    </div>
                </div>
            </div>
            <div class="row">
              <div class="col-md-6">
                    <div class="select-style-1">
                        <label>Kehadiran</label>
                        <div class="select-position">
                            <select required v-model="filter.presence_status">
                                <option value="">Semua</option>
                                <option value="1">Hadir</option>
                                <option value="2">Alpa</option>
                                <option value="3">Sakit</option>
                                <option value="4">Izin</option>
                            </select>
                        </div>
                    </div>
                </div>
              <div class="col-md-6">
                    <div class="select-style-1">
                        <label>Status Persetujuan</label>
                        <div class="select-position">
                            <select required v-model="filter.status">
                                <option value="">Semua</option>
                                <option value="1">Menunggu</option>
                                <option value="2">Disetujui</option>
                                <option value="3">Ditolak</option>
                                <option value="4">Dibatalkan</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <div class="my-4" >
                <label>Kelas</label>
                <tomselect ref="kelas" id="kelas" :options="kelas.options" :value="kelas_id" @changed="kelas_id=$event" placeholder="Pilih Kelas"  eltype="select" style="width: 100%;">
                </tomselect>
            </div>

                <div class="action d-flex flex-wrap justify-content-end">
                    <button type="submit" :disabled="loading" class="main-btn btn-sm primary-btn btn-hover">
                            <span v-if="loading" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                            <span v-else >Kirim</span>
                    </button>
                </div>
              </div>
            </div>
          </div>
        </div>
    </div>

    <div class="modal fade" ref="modalDetail"  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">Detail Persetujuan Kehadiran #{{details.id}}</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="my-2 row">
                    <div class="col-md-6" >
                        <label>Kehadiran</label>
                        <div v-html="kehadiran"></div>
                    </div>
                    <div class="col-md-6" >
                        <label>Status</label>
                        <div v-html="status"></div>
                    </div>
                </div>
                <div class="my-2 row">
                    <div class="col-md-6" >
                        <label>Tanggal Kehadiran</label>
                        <div>{{details.tanggal}}</div>
                    </div>
                    <div class="col-md-6" >
                        <label>Pembuat</label>
                        <div><strong>{{details.user_name}}</strong></div>
                    </div>
                </div>
                <div class="my-2" v-if="details.approval_description">
                    <label>Keterangan Pembuat</label>
                    <editor :disabled="true" :tinymceScriptSrc="$store.state.config.base_url+'/vendors/tinymce/js/tinymce/tinymce.min.js'" v-model="details.approval_description"  :api-key="tinymcekey" :init="{plugins:[],toolbar:false,menubar:false}" />
                </div>
                <div v-if="details.approver_description||details.status=='1'" class="my-2">
                    <label>Keterangan Pengubah</label>
                    <editor :disabled="details.status!='1'" :tinymceScriptSrc="$store.state.config.base_url+'/vendors/tinymce/js/tinymce/tinymce.min.js'" v-model="details.approver_description"  :api-key="tinymcekey" :init="tinymceinit" />
                </div>
                <div v-if="details.editor_name">
                    <label>Pengubah</label>
                    <div>{{details.editor_name}}</div>
                </div>
                <div class="my-2 row">
                    <div class="col-md-6" >
                        <label>Diubah Pada</label>
                        <div v-if="details.uam">{{details.uam.format("YYYY-MM-DD HH:mm")}}</div>
                    </div>
                    <div class="col-md-6" >
                        <label>Dibuat Pada</label>
                        <div v-if="details.cam">{{details.cam.format("YYYY-MM-DD HH:mm")}}</div>
                    </div>
                </div>
                <div class="action d-flex flex-wrap justify-content-end">
                    <button type="submit" @click="decline(details.id)" v-if="details.status=='1'" :disabled="details.loading" class="main-btn btn-sm danger-btn btn-hover">
                            <span v-if="loading" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                            <span v-else >Tolak</span>
                    </button>
                    &nbsp;
                    <button type="submit" @click="approve(details.id)" v-if="details.status=='1'" :disabled="details.loading" class="main-btn btn-sm success-btn btn-hover">
                            <span v-if="loading" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                            <span v-else >Setujui</span>
                    </button>
                </div>


              </div>
            </div>
          </div>
        </div>
    </div>
    `;
    return {
        template: vp_template,
        name: "presence",
        props: ['tinymcekey',],
        data() {
            return {
                grid: gridConf,

                filter: {
                    presence_status: '',
                    status: '',
                },
                loading: false,
                approval_description: '',
                tanggal: '',
                details: {
                    id: (new URL(window.location.href)).searchParams.get('approval')
                },
                kelas: {
                    options: [],
                    value: '',
                },
                presence_status: '1',
                tinymceinit: {
                    images_upload_handler: this.images_upload_handler,
                    plugins: [
                        'advlist autolink lists link image charmap print preview anchor',
                        'searchreplace visualblocks code fullscreen',
                        'insertdatetime media table powerpaste help wordcount'
                    ],
                    toolbar:
                        "bold italic strikethrough link numlist bullist blockquote emoticons image",
                }
            }
        },
        mounted() {

            try {
                if (this.details.id) this.detail(atob(this.details.id));
            } catch (error) {
                console.log("Failed decode approval")
            }
            this.eventListener();
            this.loadKelas()
        },
        computed: {
            kelas_id: {
                get() {
                    return this.kelas.value;
                }, set(v) {
                    this.kelas.value = v;
                }
            },
            curl() {
                let url = this.$store.state.config.base_url + "/panel/approvals/presence/siswa/all?";
                if (this.filter.presence_status) url += "&presence_status=" + this.filter.presence_status;
                if (this.filter.status) url += "&status=" + this.filter.status;
                if (this.filter.startDate) {
                    url += "&startDate=" + moment(`${this.filter.startDate} 00:00:00`).unix();
                };
                if (this.filter.endDate) {
                    url += "&endDate=" + moment(`${this.filter.endDate} 23:59:59`).unix();
                };
                if (this.kelas_id) url += "&kelas_id=" + this.kelas_id;
                return url;
            },
            kehadiran() {
                let status = "";
                switch (this.details.presence_status) {
                    case '1':
                        status = "Hadir"
                        break;
                    case '2':
                        status = "Alpa"
                        break;
                    case '3':
                        status = "Sakit"
                        break;
                    case '4':
                        status = "Izin"
                        break;
                }
                return `<div class="badge bg-primary">${status}</div>`;
            },
            status() {
                let status = "";
                let cl = "";
                switch (this.details.status) {
                    case '1':
                        status = "Menunggu";
                        cl = "warning";
                        break;
                    case '2':
                        status = "Disetujui"
                        cl = "success";
                        break;
                    case '3':
                        status = "Ditolak"
                        cl = "danger";
                        break;
                    case '4':
                        status = "Dibatalkan"
                        cl = "danger";
                        break;
                }
                return `<div class="badge bg-${cl}">${status}</div>`;

            },
        },
        methods: {
            eventListener() {
                document.addEventListener('click', (e) => {
                    if (e.target && e.target.id == 'trigger-decline') {
                        this.decline(e.target.dataset.id)
                    }
                    if (e.target && e.target.id == 'trigger-approve') {
                        this.approve(e.target.dataset.id)
                    }
                    if (e.target && e.target.id == 'trigger-detail') {
                        this.detail(e.target.dataset.id)
                    }
                });
            },
            detail(id) {
                showDismisableLoading();
                let url = this.$store.state.config.base_url + "/panel/approvals/presence/siswa/detail/" + id
                axios({
                    method: 'GET',
                    url: url,
                }).then((response) => {
                    Swal.close()
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    response.data.data.cam = mm({ unix: response.data.data.created_at });
                    response.data.data.uam = mm({ unix: response.data.data.updated_at });
                    this.details = response.data.data;
                    this.details.approver_description = this.details.approver_description || '';
                    if (this.details.approval_description) this.details.approval_description = this.details.approval_description.replace("../assets/img", this.$store.state.config.base_url + "/assets/img");
                    this.modalDetail("show");
                }, (error) => {
                    Swal.fire('Error', gaem(error), 'error')
                });
            },
            decline(id) {
                SwalDelete({
                    params: { confirmButtonText: 'Ya, tolak ini!', cancelButtonText: "Kembali" },
                    confirmed: () => {
                        showDismisableLoading();
                        this.details.loading = true;
                        axios({
                            method: 'PATCH',
                            data: { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value, approver_description: this.details.approver_description },
                            url: this.$store.state.config.base_url + "/panel/approvals/presence/siswa/decline/" + id,
                        }).then((response) => {
                            Swal.close();
                            if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                            this.modalDetail('hide');
                            this.details = {};
                            this.$refs[this.grid.ref].reload();
                            Swal.fire('Berhasil', response.data.message, 'success')
                        }, (error) => {
                            Swal.fire('Error', gaem(error), 'error')
                        }).finally(() => this.details.loading = false);
                    }
                });
            },
            approve(id) {
                SwalDelete({
                    params: { confirmButtonText: 'Ya, setujui ini!', cancelButtonText: "Kembali" },
                    confirmed: () => {
                        showDismisableLoading();
                        this.details.loading = true;
                        axios({
                            method: 'PATCH',
                            data: { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value, approver_description: this.details.approver_description },
                            url: this.$store.state.config.base_url + "/panel/approvals/presence/siswa/approve/" + id,
                        }).then((response) => {
                            Swal.close();
                            if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                            this.modalDetail('hide');
                            this.details = {};
                            this.$refs[this.grid.ref].reload();
                            Swal.fire('Berhasil', response.data.message, 'success')
                        }, (error) => {
                            Swal.fire('Error', gaem(error), 'error')
                        }).finally(() => this.details.loading = false);
                    }
                });
            },
            loadKelas() {
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + `/panel/md/kelas/all`
                }).then((response) => {
                    if (!isObject(response.data)) return setTimeout(this.loadKelas, 1000);
                    this.kelas.options = response.data.data.map((e, i) => {
                        let k = e.kode + " - " + e.nama;
                        if (e.kode_tingkat) {
                            k += " | " + e.kode_tingkat
                        }
                        if (e.kode_jurusan) {
                            k += " | " + e.kode_jurusan
                        }
                        return { value: e.id, text: k }
                    });
                }, (error) => {
                });
            },
            images_upload_handler(blobInfo, success, failure, progress) {
                var xhr, formData;

                xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                xhr.open('POST', this.$store.state.config.base_url + '/panel/approvals/presence/siswa/imageUploader');

                xhr.upload.onprogress = function (e) {
                    progress(e.loaded / e.total * 100);
                };

                xhr.onload = function () {
                    var json;

                    if (xhr.status === 403) {
                        failure('HTTP Error: ' + xhr.status, { remove: true });
                        return;
                    }

                    if (xhr.status < 200 || xhr.status >= 300) {
                        failure('HTTP Error: ' + xhr.status);
                        return;
                    }

                    json = JSON.parse(xhr.responseText);

                    if (!json || typeof json.location != 'string') {
                        failure('Invalid JSON: ' + xhr.responseText);
                        return;
                    }

                    success(json.location);
                };

                xhr.onerror = function () {
                    failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
                };

                formData = new FormData();
                formData.append('file', blobInfo.blob(), blobInfo.filename());
                formData.append([this.$store.state.config.csrf.name], this.$store.state.config.csrf.value);

                xhr.send(formData);
            },
            filterModal(e = 'show') {
                if (!this.filterModalInstance) {
                    this.filterModalInstance = new bootstrap.Modal(this.$refs.filterModal);
                }
                switch (e) {
                    case "hide":
                        this.filterModalInstance.hide();
                        break;
                    case "show":
                        this.filterModalInstance.show();
                        break;
                    case "toggle":
                        this.filterModalInstance.toggle();
                        break;
                    case "dispose":
                        this.filterModalInstance.dispose();
                        break;
                }
            },
            modalDetail(e) {
                if (!this.ModalDetailInstance) {
                    this.ModalDetailInstance = new bootstrap.Modal(this.$refs.modalDetail);
                }
                switch (e) {
                    case "hide":
                        this.ModalDetailInstance.hide();
                        break;
                    case "show":
                        this.ModalDetailInstance.show();
                        break;
                    case "toggle":
                        this.ModalDetailInstance.toggle();
                        break;
                    case "dispose":
                        this.ModalDetailInstance.dispose();
                        break;
                }
            },
            ondataload(data) {
                this.grid.data = data.data.map(v => {
                    v.cam = mm({ unix: v.created_at });
                    v.uam = mm({ unix: v.updated_at });
                    return v;
                });
                this.grid.ready = true;
                return data.data;
            },
        },
    }
})();
