var VPPresence = (function () {
    let vp_template = `
    <div class="container">
        <div class="card">
            <div style="text-align:right" class="m-2">
                <button class="btn btn-sm btn-primary rounded-md btn-hover" @click="modal('show')">
                    <i class="fas fa-plus"></i>
                </button>
                &nbsp;
                <button v-if="table.instance" class="btn btn-sm btn-success rounded-md btn-hover" @click="loadData()">
                    <i class="fas fa-sync"></i>
                </button>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table  id="approval-table"></table>
                </div>
            </div>
        </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 p-4">
            <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="fas fa-times-circle"></i>
              </button>
            </div>
            <div class="modal-body px-0">
              <div class="content">
                <form @submit.prevent="add">
                <div class="form-group">
                    <label class="form-label" >Tanggal</label>
                    <input class="form-control" required v-model="tanggal" type="date" min="1988-01-01" placeholder="Tanggal Kehadiran">
                </div>
                <div class="form-group">
                    <label class="form-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="form-group">
                    <label class="form-label">Large select</label>
                    <select required v-model="presence_status" class="form-select form-select-lg" aria-label="Kehadiran">
                        <option value="1">Hadir</option>
                        <option value="2">Alpa</option>
                        <option value="3">Sakit</option>
                        <option value="4">Izin</option>
                    </select>
                </div>
                <div class="action d-flex flex-wrap justify-content-end">
                    <button type="submit" :disabled="loading" class="btn btn-sm btn-primary 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 p-4">
            <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="fas fa-times-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 {
        name: "presence",
        props: ['tinymcekey'],
        template: vp_template,
        data() {
            return {
                table: {
                    instance: null,
                },

                errMsg: '',
                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();
            this.loadData();
        },
        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 + "/approvals/presence/add"
                axios({
                    method: 'POST',
                    data: data,
                    url: url,
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire("Gagal", gaem({
                        response
                    }, response.data), 'error');
                    Swal.fire('Success', response.data.message, 'success')
                    this.modal("hide");
                    this.loadData();
                }, (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 + "/approvals/presence/detail/" + id
                axios({
                    method: 'GET',
                    url: url,
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire("Gagal", 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 + "/approvals/presence/cancel/" + id,
                        }).then((response) => {
                            if (!isObject(response.data)) return Swal.fire("Gagal", gaem({
                                response
                            }, response.data), 'error');
                            Swal.close();
                            this.loadData();
                            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 + '/approvals/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);
            },
            kehadiranText(state) {
                let status = "";
                switch (state) {
                    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>`;
            },
            statusText(state) {
                let status = "";
                let cl = "";
                switch (state) {
                    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>`;
            },
            loadData() {
                if (this.table.instance) this.table.instance.destroy(), this.table.instance = null;
                this.table.instance = new DataTable("#approval-table", {
                    ajax: {
                        url: this.$store.state.config.base_url + "/approvals/presence/all",
                        load: (xhr) => {
                            let data = null;
                            try {
                                data = JSON.parse(xhr.responseText);
                            } catch (error) {
                                return console.log(error)
                            }
                            return JSON.stringify(data.data.map(v => {
                                let btn = `<div class="d-flex">`;
                                btn += `&nbsp;<button class="btn btn-primary btn-sm" id="trigger-detail" data-id="${v.id}"><i id="trigger-detail" data-id="${v.id}" class='fas fa-eye'></i></button>`;
                                if (v.status == '1') {
                                    btn += `&nbsp;<button class="btn btn-danger btn-sm" id="trigger-cancel" data-id="${v.id}"><i id="trigger-cancel" data-id="${v.id}" class='fas fa-user-times'></i></button>`;
                                }
                                btn += "</div>";
                                return {
                                    "ID": v.id,
                                    "Kehadiran": this.kehadiranText(v.presence_status),
                                    "Status": this.statusText(v.status),
                                    "Tanggal": v.tanggal,
                                    "Dibuat Pada": mm({ unix: v.created_at }).format("YYYY-MM-DD HH:mm"),
                                    "Aksi": btn,
                                }
                            }));
                        }
                    }
                });
            },
            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;
                }
            },
        },
        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>`;

            },
        },
    }
})();
