var VPPresence = (function () {
    let gridConf = {
        ready: false,
        data: [],
        id: "p-table",
        ref: "p-table",
        columns: [
            { id: 'id', name: 'ID', },
            {
                id: 'presence_status', name: 'Kehadiran',
                formatter: (_, row) => {
                    let status = "";
                    switch (row.cells[1].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[2].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[3].data}</div>`;
                    return gridjs.html(btn);
                }
            },
            { id: 'cam', name: 'Dibuat Pada', formatter: (_, row) => row.cells[4].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[2].data == '1') {
                        btn += `&nbsp;<button class="btn btn-danger rounded-md" id="trigger-cancel" data-id="${row.cells[0].data}"><i id="trigger-cancel" data-id="${row.cells[0].data}" class='fas fa-user-times'></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="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="$store.state.config.base_url + '/panel/approval/presence/all'" :ref="grid.ref" :columns="grid.columns"
                :ondataload="ondataload"></grid>
        </div>
    </div>
    <!-- Modal -->

    <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">Tambah 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">
                <form @submit.prevent="add">
                <div class="input-style-1">
                    <label>Tanggal</label>
                    <input required v-model="tanggal" type="date" min="1988-01-01" placeholder="Tanggal Kehadiran">
                </div>
                <div class="input-style-1">
                    <label>Deskripsi</label>
                    <editor :tinymceScriptSrc="$store.state.config.base_url+'/vendors/tinymce/js/tinymce/tinymce.min.js'" v-model="approval_description"  :api-key="tinymcekey" :init="tinymceinit" />
                </div>
                <div class="select-style-1">
                    <label>Kehadiran</label>
                    <div class="select-position">
                        <select required v-model="presence_status">
                            <option value="1">Hadir</option>
                            <option value="2">Alpa</option>
                            <option value="3">Sakit</option>
                            <option value="4">Izin</option>
                        </select>
                    </div>
                </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>
                </form>
              </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">
                    <label>Tanggal Kehadiran</label>
                    <div>{{details.tanggal}}</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 class="my-2" v-if="details.approver_description&&details.status!='1'">
                    <label>Keterangan Pengubah</label>
                    <editor :disabled="true" :tinymceScriptSrc="$store.state.config.base_url+'/vendors/tinymce/js/tinymce/tinymce.min.js'" v-model="details.approver_description"  :api-key="tinymcekey" :init="{plugins:[],toolbar:false,menubar:false}" />
                </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>
            </div>
          </div>
        </div>
    </div>
    `;
    return {
        template: vp_template,
        name: "presence",
        props: ['tinymcekey',],
        data() {
            return {
                grid: gridConf,

                loading: false,
                approval_description: '',
                tanggal: '',
                details: {
                    id: (new URL(window.location.href)).searchParams.get('approval')
                },
                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();
        },
        computed: {
            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-cancel') {
                        this.cancel(e.target.dataset.id)
                    }
                    if (e.target && e.target.id == 'trigger-detail') {
                        this.detail(e.target.dataset.id)
                    }
                });
            },
            add() {
                let data = {
                    [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value,
                    approval_description: this.approval_description,
                    tanggal: this.tanggal,
                    presence_status: this.presence_status,
                };
                this.loading = true;
                let url = this.$store.state.config.base_url + "/panel/approval/presence/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('Error', gaem(error), 'error')
                }).finally(() => this.loading = false);
            },
            detail(id) {
                showDismisableLoading();
                let url = this.$store.state.config.base_url + "/panel/approval/presence/detail/" + id
                axios({
                    method: 'GET',
                    url: url,
                }).then((response) => {
                    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;
                    if (this.details.approver_description) this.details.approver_description = this.details.approver_description.replace("../../../assets/img", this.$store.state.config.base_url + "/assets/img");
                    Swal.close()
                    this.modalDetail("show");
                }, (error) => {
                    Swal.fire('Error', gaem(error), 'error')
                });
            },
            cancel(id) {
                SwalDelete({
                    params: { confirmButtonText: 'Ya, batalkan ini!' },
                    confirmed: () => {
                        showDismisableLoading();
                        axios({
                            method: 'PATCH',
                            data: { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value, },
                            url: this.$store.state.config.base_url + "/panel/approval/presence/cancel/" + id,
                        }).then((response) => {
                            if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                            Swal.close();
                            this.$refs[this.grid.ref].reload();
                            Swal.fire('Berhasil', response.data.message, 'success')
                        }, (error) => {
                            Swal.fire('Error', gaem(error), '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/approval/presence/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);
            },
            modal(e = 'show') {
                if (!this.ModalInstance) {
                    this.ModalInstance = new bootstrap.Modal(this.$refs.modal);
                }
                switch (e) {
                    case "hide":
                        this.ModalInstance.hide();
                        break;
                    case "show":
                        this.ModalInstance.show();
                        break;
                    case "toggle":
                        this.ModalInstance.toggle();
                        break;
                    case "dispose":
                        this.ModalInstance.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;
            },
        },
    }
})();
