var VPRPP = (function () {
    let gridConf = {
        ready: false,
        data: [],
        id: "rpp-table",
        ref: "rpp-table",
        columns: [
            {
                id: 'nama_kompetensi', name: "Kompetensi",
                formatter: (_, row) => {
                    return `${row.cells[5].data} ${row.cells[0].data}`;
                }
            }
            , {
                id: 'kode_tahun', name: "Tahun Pelajaran",
                formatter: (_, row) => gridjs.html(`<div class="badge text-dark">${row.cells[1].data} - ${row.cells[row.cells.length - 1].data} - ${row.cells[row.cells.length - 2].data}</div>`)
            }, { id: 'created_by', name: "Dibuat Oleh" },
            {
                id: 'id',
                name: 'Aksi',
                formatter: (_, row) => {
                    let btn = `<div class="d-flex">`;
                    btn += `&nbsp;<button class="btn btn-primary rounded-md" id="trigger-edit" data-id="${row.cells[3].data}"><i id="trigger-edit" data-id="${row.cells[3].data}" class='lni lni-pencil-alt'></i></button>`;
                    btn += `&nbsp;<button class="btn btn-danger rounded-md" id="trigger-delete" data-id="${row.cells[3].data}"><i id="trigger-delete" data-id="${row.cells[3].data}" class='lni lni-trash-can'></i></button>`;
                    if (row.cells[4].data) {
                        btn += `&nbsp;<a download="${row.cells[5].data.split(' ').join('-')}-${row.cells[0].data.split(' ').join('-')}-${row.cells[1].data.split(' ').join('-')}-${row.cells[row.cells.length - 1].data.split(' ').join('-')}-${row.cells[row.cells.length - 2].data.split(' ').join('-')}.pdf" class="btn btn-success rounded-md" href="${row.cells[4].data}"><i class='fas fa-file-pdf'></i></a>`;
                    }
                    btn += "</div>";
                    return gridjs.html(btn);
                }
            },
            {
                id: "file",
                hidden: true
            },
            {
                id: "nomor_kompetensi",
                hidden: true
            },
            { id: 'semester_tahun', hidden: true },
            { id: 'nama_tahun', hidden: true },
        ]
    };
    let vp_template = `
    <div class="card-style">
        <div style="text-align:right">
            <button class="main-btn btn-sm success-btn rounded-md btn-hover" @click="filterModal('show')">
                <i class="fas fa-filter"></i>
            </button>
            &nbsp;
            <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="urlrpp" :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-xl 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'}} Rencana Pelaksanaan Pembelajaran</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="my-4" >
                  <label>Tahun Pelajaran</label>
                  <tomselect id="tahun" :options="mdl.tahun.options" :value="mdl.tahun.value" @changed="mdl.tahun.value=$event" placeholder="Pilih Tahun Pelajaran"  eltype="select" style="width: 100%;">
                  </tomselect>
                </div>
                <div class="my-4" >
                  <label>Mata Pelajaran</label>
                  <tomselect id="mapel" :options="mdl.mapel.options" :value="mdl.mapel.value" @changed="mdl.mapel.value=$event" placeholder="Pilih Mata Pelajaran"  eltype="select" style="width: 100%;">
                  </tomselect>
                </div>
                <div class="my-4" >
                  <label>Tingkat</label>
                  <tomselect id="tingkat" :options="mdl.tingkat.options" :value="mdl.tingkat.value" @changed="mdl.tingkat.value=$event" placeholder="Pilih Tingkat"  eltype="select" style="width: 100%;">
                  </tomselect>
                </div>
                <div class="my-4" >
                  <label>Kompetensi Dasar</label>
                  <tomselect id="kompetensi" :options="mdl.kompetensi.options" :value="mdl.kompetensi.value" @changed="mdl.kompetensi.value=$event" placeholder="Pilih Kompetensi Dasar"  eltype="select" style="width: 100%;">
                  </tomselect>
                </div>
                <div class="row">
                    <div class="col-6" :class="'col-'+(mdl.file.value&&!mdl.file.raw?'6':'12')">
                        <div class="input-style-1">
                        <label>File</label>
                        <input ref="pdfInput" @change="fileready" type="file" >
                        </div>
                    </div>
                    <div v-if="mdl.file.value&&!mdl.file.raw" class="col-6 my-auto text-center">
                        <a class="btn btn-success mx-1" download :href="mdl.file.value"><i class="fas fa-file-pdf"></i></a>
                        <a class="btn btn-danger mx-1" @click="mdl.file.value=null" href="javascript:void(0)"><i class="lni lni-trash-can"></i></a>
                    </div>
                </div>
                
              <div v-show="mdl.file.canvas" class="accordion" id="accordionPanelsStayOpenExample">
                    <div class="accordion-item">
                        <h2 class="accordion-header" id="panelsStayOpen-heading">
                            <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapse" aria-expanded="false" aria-controls="panelsStayOpen-collapse">
                                Preview
                            </button>
                        </h2>
                        <div id="panelsStayOpen-collapse" class="accordion-collapse collapse show" aria-labelledby="panelsStayOpen-heading">
                            <div class="accordion-body">
                                <canvas class="w-100" ref="pdfViewer"></canvas>
                            </div>
                        </div>
                    </div>
               </div>


                    <div class="my-4" v-if="mdl.guru.show">
                    <label>Guru</label>
                    <tomselect id="guru" :options="mdl.guru.data" :value="mdl.guru.value" @changed="mdl.guru.value=$event" placeholder="Pilih Guru"  eltype="select" style="width: 100%;">
                    </tomselect>
                    </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>
    <!-- Filter 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</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>Tingkat</label>
                    <div class="select-position">
                        <select required v-model="filterMdl.tingkat_id">
                            <option value="">Semua</option>
                            <option v-for="tingkat in mdl.tingkat.options" :value="tingkat.value">{{tingkat.text}}</option>
                        </select>
                    </div>
                </div>
                <div class="select-style-1">
                    <label>Mata Pelajaran</label>
                    <div class="select-position">
                        <select required v-model="filterMdl.mapel_id">
                            <option value="">Semua</option>
                            <option v-for="mapel in mdl.mapel.options" :value="mapel.value">{{mapel.text}}</option>
                        </select>
                    </div>
                </div>
              </div>
            </div>
          </div>
        </div>
    </div>
    `;
    return {
        template: vp_template,
        name: "rpp",
        data() {
            return {
                grid: gridConf,
                csrf: {
                    name: null,
                    value: null,
                },
                filterMdl: {
                    tingkat_id: '',
                    mapel_id: '',
                },
                mdl: {
                    guru: {
                        show: false,
                        value: null,
                        data: []
                    },
                    kompetensi: {
                        value: null,
                        options: [],
                        raw: []
                    },
                    tahun: {
                        value: null,
                        options: [],
                        raw: []
                    },
                    mapel: {
                        value: null,
                        options: [],
                        raw: []
                    },
                    tingkat: {
                        value: null,
                        options: [],
                        raw: []
                    },
                    file: {
                        value: null,
                        raw: null,
                        canvas: false,
                    }
                },
            }
        },
        mounted() {
            this.eventListener();
            this.loadConfig();
            this.loadMapel();
            this.loadTingkat();
            this.loadTahun();
        },
        watch: {
            mata_pelajaran(v) {
                this.mdl.kompetensi.options = [];
                this.mdl.kompetensi.value = null;
                this.loadKompetensi();
            },
            tingkat(v) {
                this.mdl.kompetensi.options = [];
                this.mdl.kompetensi.value = null;
                this.loadKompetensi();
            },
        },
        computed: {
            tahun_pelajaran: {
                get() {
                    return this.mdl.tahun.value;
                },
                set(v) {
                    this.mdl.tahun.value = v;
                }
            },
            mata_pelajaran: {
                get() {
                    return this.mdl.mapel.value;
                },
                set(v) {
                    this.mdl.mapel.value = v;
                }
            },
            tingkat: {
                get() {
                    return this.mdl.tingkat.value;
                },
                set(v) {
                    this.mdl.tingkat.value = v;
                }
            },
            kompetensi_dasar: {
                get() {
                    return this.mdl.kompetensi.value;
                },
                set(v) {
                    this.mdl.kompetensi.value = v;
                }
            },
            urlrpp() {
                let url = window.location.href + "/all?";
                if (this.filterMdl.tingkat_id) url += `&tingkat_id=${this.filterMdl.tingkat_id}`;
                if (this.filterMdl.mapel_id) url += `&mapel_id=${this.filterMdl.mapel_id}`;
                return url;
            },
        },
        methods: {
            eventListener() {
                document.addEventListener('click', (e) => {
                    if (e.target && e.target.id == 'trigger-delete') {
                        this.delete(e.target.dataset.id)
                    }
                    if (e.target && e.target.id == 'trigger-edit') {
                        this.detail(e.target.dataset.id)
                    }
                    this.$refs.modal.addEventListener('hide.bs.modal', (e) => {
                        this.mdl.id = null;
                        this.resetFile();
                    });
                });
            },
            resetFile() {
                this.$refs.pdfInput.value = "";
                this.mdl.file.raw = null;
                this.mdl.file.value = null;
                this.mdl.file.canvas = false;
            },
            fileready(e) {
                let files = e.target.files || e.dataTransfer.files;
                if (!files.length) return this.resetFile();
                if (files[0].type != "application/pdf") return this.resetFile();
                this.mdl.file.raw = files[0];
                let fileReader = new FileReader();
                let canvas = this.$refs.pdfViewer;
                let setCanvasReady = (b) => {
                    this.mdl.file.canvas = b
                }
                fileReader.onload = function () {
                    let pdfData = new Uint8Array(this.result);
                    // Using DocumentInitParameters object to load binary data.
                    let loadingTask = pdfjsLib.getDocument({ data: pdfData });
                    loadingTask.promise.then(function (pdf) {
                        console.log('PDF loaded');

                        // Fetch the first page
                        let pageNumber = 1;
                        pdf.getPage(pageNumber).then(function (page) {
                            console.log('Page loaded');

                            let scale = 1.5;
                            let viewport = page.getViewport({ scale: scale });

                            // Prepare canvas using PDF page dimensions
                            let context = canvas.getContext('2d');
                            canvas.height = viewport.height;
                            canvas.width = viewport.width;

                            // Render PDF page into canvas context
                            let renderContext = {
                                canvasContext: context,
                                viewport: viewport
                            };
                            let renderTask = page.render(renderContext);
                            renderTask.promise.then(function () {
                                console.log('Page rendered');
                            });
                        });
                        setCanvasReady(true)
                    }, function (reason) {
                        setCanvasReady(false)
                        // PDF loading error
                        console.error(reason);
                    });
                };
                fileReader.readAsArrayBuffer(files[0]);
            },
            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.kompetensi.value = response.data.data.kompetensi_id;
                    this.mdl.tahun.value = response.data.data.tahun_id;
                    this.mdl.file.value = response.data.data.file;
                    this.tingkat = response.data.data.tingkat_id;
                    this.mata_pelajaran = response.data.data.mapel_id;
                    this.kompetensi_dasar = response.data.data.kompetensi_id;
                    this.mdl.guru.value = response.data.data.user_id;
                    this.modal("show")
                }, (error) => {
                    Swal.fire('Gagal', gaem(error), 'error')
                });
            },
            add() {
                let formData = new FormData();
                formData.append([this.$store.state.config.csrf.name], this.$store.state.config.csrf.value);
                if (this.mdl.file.raw) formData.append('file', this.mdl.file.raw);
                formData.append('file_value', this.mdl.file.value);
                formData.append('kompetensi_id', this.mdl.kompetensi.value);
                formData.append('tahun_id', this.mdl.tahun.value);
                formData.append('user_id', this.mdl.guru.value);
                this.mdl.loading = true;
                let url = window.location.href + "/add"
                axios({
                    method: 'POST',
                    data: formData,
                    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.mdl.loading = false);
            },
            edit() {
                let formData = new FormData();
                formData.append([this.$store.state.config.csrf.name], this.$store.state.config.csrf.value);
                if (this.mdl.file.raw) formData.append('file', this.mdl.file.raw);
                formData.append('file_value', this.mdl.file.value);
                formData.append('kompetensi_id', this.mdl.kompetensi.value);
                formData.append('tahun_id', this.mdl.tahun.value);
                formData.append('user_id', this.mdl.guru.value);
                this.mdl.loading = true;
                let url = window.location.href + "/edit/" + this.mdl.id;
                axios({
                    method: 'POST',
                    data: formData,
                    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.mdl.loading = false);
            },
            loadMapel() {
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + `/panel/e-learning/kompetensi-dasar/mapel`
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.mdl.mapel.raw = response.data.data;
                    this.mdl.mapel.options = response.data.data.map((v, i) => {
                        if (i == 0) this.mdl.mapel.value = v.id;
                        return { value: v.id, text: `${v.kode} - ${v.nama}` };
                    })
                }, (error) => {
                    Swal.fire('Gagal', 'Terjadi Kesalahan Saat Mengambil Data Mata Pelajaran', 'error')
                });
            },
            loadTingkat() {
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + `/panel/e-learning/kompetensi-dasar/tingkat`
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.mdl.tingkat.options = response.data.data.map((v, i) => {
                        if (i == 0) this.mdl.tingkat.value = v.id;
                        return { value: v.id, text: v.kode }
                    });
                }, (error) => {
                    Swal.fire('Gagal', 'Terjadi Kesalahan Saat Mengambil Data Tingkat', 'error')
                });
            },
            loadKompetensi() {
                let url = this.$store.state.config.base_url + `/panel/e-learning/kompetensi-dasar/all?`;
                url += `&tingkat_id=${this.tingkat}&mapel_id=${this.mata_pelajaran}`;
                axios({
                    method: 'get',
                    url,
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.mdl.kompetensi.options = response.data.data.map((v, i) => {
                        if (i == 0 && !this.kompetensi_dasar) this.kompetensi_dasar = v.id;
                        return { value: v.id, text: `${v.kode} - ${v.nomor} ${v.nama}` };
                    })
                }, (error) => {
                    Swal.fire('Error', gaem(error, 'Terjadi Kesalahan Saat Mengambil Data Kompetensi Dasar'), 'error')
                });
            },
            loadTahun() {
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + `/panel/e-learning/tahun-pelajaran/all`
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.mdl.tahun.options = response.data.data.map((v, i) => {
                        if (i == 0 && !this.tahun_pelajaran) this.tahun_pelajaran = v.id;
                        return { value: v.id, text: `${v.kode} - ${v.nama} - ${v.semester}` }
                    });
                }, (error) => {
                    Swal.fire('Error', gaem(error, 'Terjadi Kesalahan Saat Mengambil Data Tahun Pelajaran'), '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('Error', gaem(error), 'error')
                        });
                    }
                });
            },
            loadConfig() {
                axios({
                    method: 'get',
                    url: window.location.href + "/config",
                }).then((response) => {
                    if (!response.data) return;
                    this.mdl.guru.show = response.data.fieldGuru;
                    if (this.mdl.guru.show) this.loadGuru();
                }, (error) => {
                });
            },
            loadGuru() {
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + `/panel/users/staff/all?role=guru`
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.mdl.guru.data = response.data.data.map((v, i) => {
                        if (i == 0) {
                            this.mdl.guru.value = v.id;
                        }
                        return { value: v.id, text: v.fullname };
                    });
                }, (error) => {
                    Swal.fire('Gagal', gaem(error, 'Gagal Mengambil Data Guru'), 'error')
                });
            },
            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;
                }
            },
            filterModal(e = 'show') {
                if (!this.filterMdl.instance) {
                    this.filterMdl.instance = new bootstrap.Modal(this.$refs.filterModal);
                }
                switch (e) {
                    case "hide":
                        this.filterMdl.instance.hide();
                        break;
                    case "show":
                        this.filterMdl.instance.show();
                        break;
                    case "toggle":
                        this.filterMdl.instance.toggle();
                        break;
                    case "dispose":
                        this.filterMdl.instance.dispose();
                        break;
                }
            },
            ondataload(data) {
                this.grid.data = data.data;
                this.grid.ready = true;
                return data.data;
            },
        },
    }
})();
