var VPMateriPelajaran = (function () {
    let gridConf = {
        ready: false,
        data: [],
        id: "mp-table",
        ref: "mp-table",
        url: window.location.href + "/all",
        columns: [
            { id: 'kode_mapel', name: "Kode Mata Pelajaran" },
            { id: 'nama_kelas', name: "Kelas" },
            { id: 'judul', name: "Judul" },
            {
                id: 'nama_kompetensi', name: "Kompetensi",
                formatter: (_, row) => {
                    return gridjs.html(`<div class="badge text-dark">${row.cells[7].data} ${row.cells[3].data}</div>`);
                }
            },
            {
                id: 'file', name: "File", formatter: (_, row) => {
                    if (row.cells[4].data) {
                        btn = `&nbsp;<a class="btn btn-success rounded-md" href="${row.cells[4].data}"><i class='${archiveIcon(row.cells[4].data)}'></i></a>`;
                        return gridjs.html(btn);
                    }
                }
            }, {
                id: 'is_active',
                name: 'Status',
                formatter: (_, row) => {
                    let btn = `<div class="badge bg-${row.cells[5].data == 1 ? 'primary' : 'danger'}">${row.cells[5].data == 1 ? "Aktif" : "Tidak Aktif"}</div>`;
                    return gridjs.html(btn);
                }
            },
            {
                id: 'id',
                name: 'Aksi',
                formatter: (_, row) => {
                    let btn = `<div class="d-flex">&nbsp;<button class="btn btn-primary rounded-md" id="trigger-edit" data-id="${row.cells[6].data}"><i id="trigger-edit" data-id="${row.cells[6].data}" class='lni lni-pencil-alt'></i></button>`;
                    btn += `&nbsp;<button class="btn btn-danger rounded-md" id="trigger-delete" data-id="${row.cells[6].data}"><i id="trigger-delete" data-id="${row.cells[6].data}" class='lni lni-trash-can'></i></button>`;
                    btn += "</div>";
                    return gridjs.html(btn);
                }
            },
            {
                id: "nomor_kompetensi",
                hidden: true
            },
        ]
    };
    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="viewed_log=!viewed_log">
                <i class="fas fa-history"></i>
            </button>
            &nbsp;
            <button class="main-btn btn-sm success-btn rounded-md btn-hover" @click="preview_mode=!preview_mode">
                <i v-if="!preview_mode" class="fas fa-book-open"></i>
                <i v-if="preview_mode" class="fas fa-book"></i>
            </button>
            &nbsp;
            <button class="main-btn btn-sm secondary-btn rounded-md btn-hover" @click="$refs.cmi.start()">
                <i class="fas fa-clone"></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 v-show="!preview_mode" :id="grid.id" :limits="true" :url="grid.url" :ref="grid.ref" :columns="grid.columns"
                :ondataload="ondataload">
            </grid>
            <div v-show="preview_mode" style="margin-top:15px">
                <div class="accordion accordion-flush" id="accordionFlushExample">
                    <div class="accoridon-item" v-for="(materi, index) in grid.data" :key="index">
                        <h2 class="accordion-header" :id="'flush-heading'+index">
                            <button
                            class="accordion-button collapsed"
                                type="button"
                                data-bs-toggle="collapse"
                                :data-bs-target="'#flush-collapse'+index"
                                aria-expanded="false"
                                :aria-controls="'flush-collapse-'+index">
                                {{materi.nomor_kompetensi}} {{materi.nama_kompetensi}} - {{materi.judul}} 
                            </button>
                        </h2>
                        <div :id="'flush-collapse'+index" class="accordion-collapse collapse" :aria-labelledby="'flush-heading'+index" data-bs-parent="#accordionFlushExample">
                            <div class="accordion-body"> 
                                <div v-html="materi.isi"></div> 
                            </div>
                        </div>
                    </div>
                </div>      
            </div>
            
            <div v-show="viewed_log">
                <viewed-materi></viewed-materi>
            </div>
        </div>
    </div>
    <!-- Modal -->

    <div class="modal fade" ref="modal"  tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-fullscreen 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'}} Materi Pelajaran</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="input-style-1">
                    <label>Judul</label>
                    <input required v-model="mdl.judul" type="text" placeholder="Judul">
                </div>
                <div class="my-4" >
                  <label>Kompetensi Dasar</label>
                  <tomselect id="kompetensi" :options="filteredKompetensi" :value="mdl.kompetensi.value" @changed="mdl.kompetensi.value=$event" placeholder="Pilih Kompetensi Dasar"  eltype="select" style="width: 100%;">
                  </tomselect>
                </div>
                <div class="select-style-1">
                    <label>Status</label>
                    <div class="select-position">
                        <select required v-model="mdl.is_active">
                            <option value="1">Aktif</option>
                            <option value="0">Tidak Aktif</option>
                        </select>
                    </div>
                </div>
                <div class="row m-0">
                    <div class="col-6" :class="'col-'+(mdl.file.value&&!mdl.file.raw?'6':'12')">
                        <div class="input-style-1">
                        <label>File</label>
                        <input ref="fileInput" @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="archiveIcon(mdl.file.value)"></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-for="(media,id) in medias" class="file-progress">
                    <div class="row m-0">
                        <div class="col-10 p-0">
                            <span>{{media.name}}</span> <span v-if="media.msg" class="text-danger">{{media.msg}}</span>
                            <div class="progress bg-success-100">
                                <div :class="media.status==0?'primary-bg blink_me':(media.status==1?'success-bg':'danger-bg')" class="progress-bar" role="progressbar" :style="'width: '+media.percent+'%;'" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                            </div>
                        </div>
                        <div class="col-2 p-0 d-flex justify-content-center">
                            <button v-if="media.status==2||media.status==1" @click="delete medias[id]" class="btn btn-danger"><i class="lni lni-trash-can"></i></button>
                            <button v-if="media.status==0" @click="media.source.cancel()"  class="btn btn-danger"><i class="fas fa-times"></i></button>
                        </div>
                    </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-2">
                <input type="file" class="d-none" ref="mediaInput" @change="addMedia">
                <editor :tinymceScriptSrc="$store.state.config.base_url+'/vendors/tinymce/js/tinymce/tinymce.min.js'" v-model="mdl.isi"  :api-key="tinymcekey" :init="tinymce" />
                </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>
    <salin-materi @updated="$event?$refs[grid.ref].reload():''" :jadwal-id="jadwalId" ref="cmi"></salin-materi>
    `;
    return {
        template: vp_template,
        props: ['tinymcekey',],
        name: "materi-pelajaran",
        data() {
            return {
                grid: gridConf,
                viewed_log: false,
                preview_mode: false,
                tinymce: {
                    external_plugins: {
                        'formula': `${this.$store.state.config.base_url}/vendors/tinymce-formula/plugin.min.js`,
                    },
                    formula: {
                        mlang: 'mml'
                    },
                    // Necessary
                    htmlAllowedTags: ['.*'],
                    htmlAllowedAttrs: ['.*'],

                    // We recommend to set 'draggable_modal' to true to avoid overlapping issues
                    // with the different UI modal dialog windows implementations between core and third-party plugins on TinyMCE.
                    draggable_modal: true,

                    // You could set a different language for MathType editor:
                    // language: 'fr_FR',
                    // mathTypeParameters: {
                    //   editorParameters: { language: 'fr' },
                    // },
                    images_upload_handler: this.images_upload_handler,
                    plugins: [
                        'advlist autolink lists link image charmap print preview anchor',
                        'searchreplace visualblocks code fullscreen formula',
                        'insertdatetime media table powerpaste hr help wordcount'
                    ],
                    powerpaste_allow_local_images: true,
                    powerpaste_word_import: 'prompt',
                    powerpaste_html_import: 'prompt',
                    paste_data_images: true,
                    toolbar:
                        "bold italic strikethrough link numlist bullist blockquote | image addMedia formula ",
                    setup: (editor) => {
                        editor.ui.registry.addButton('addMedia', {
                            icon: 'embed',
                            onAction: (_) => {
                                this.$refs.mediaInput.click();
                            }
                        });
                    },
                },
                kode_mapel: '',
                mdl: {
                    is_active: '1',
                    isi: "",
                    relatedMateri: {
                        value: null,
                        options: [],
                        raw: []
                    },
                    kompetensi: {
                        value: null,
                        options: [],
                        raw: []
                    },
                    file: {
                        value: null,
                        raw: null,
                        canvas: false,
                    }
                },
                medias: {},
                cancelToken: axios.CancelToken,
            }
        },
        mounted() {
            this.eventListener();
            this.loadKompetensi();
        },
        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.mdl.isi = '';
                        this.medias = {};
                        this.resetFile();
                    });

                    document.addEventListener('focusin', (e) => {
                        if (e.target.closest(".tox-tinymce-aux, .moxman-window, .tam-assetmanager-root") !== null) {
                            e.stopImmediatePropagation();
                        }
                    });
                });
            },
            resetFile() {
                this.$refs.fileInput.value = "";
                this.mdl.file.raw = null;
                this.mdl.file.value = null;
                this.mdl.file.canvas = false;
            },
            archiveIcon(name) {
                return archiveIcon(name);
            },
            fileready(e) {
                let [file] = e.target.files || e.dataTransfer.files;
                if (!file) return this.resetFile();
                this.mdl.file.raw = file;
                if (file.type != "application/pdf") return this.mdl.file.canvas = null;
                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(file);
            },
            images_upload_handler(blobInfo, success, failure, progress) {
                var xhr, formData;

                xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                xhr.open('POST', window.location.href + '/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);
            },
            addMedia(e) {
                let mediaMime = [
                    'video/x-flv', 'video/mp4', 'application/x-mpegURL',
                    'video/MP2T', 'video/3gpp', 'video/quicktime',
                    'video/x-msvideo', 'video/x-ms-wmv', 'audio/mpeg'];
                let [file] = e.target.files || e.dataTransfer.files;
                if (!file) return;
                if (!mediaMime.includes(file.type)) return Swal.fire('Error', 'Format Tidak Diizinkan', 'error');
                let taskId = Math.random().toString(36).substring(2, 10);
                this.medias[taskId] = {};
                this.medias[taskId].status = 0;
                this.medias[taskId].msg = '';
                this.medias[taskId].name = file.name;
                this.medias[taskId].type = file.type;
                this.medias[taskId].source = this.cancelToken.source();
                let onUploadProgress = event => {
                    const percentCompleted = Math.round((event.loaded * 100) / event.total);
                    this.medias[taskId].percent = percentCompleted;
                }
                const formData = new FormData();
                formData.append([this.$store.state.config.csrf.name], this.$store.state.config.csrf.value);
                let url = '';
                if (this.medias[taskId].type == 'audio/mpeg') {
                    formData.append('audio', file);
                    url = window.location.href + '/audioUploader';
                } else {
                    url = window.location.href + '/videoUploader';
                    formData.append('video', file);
                }
                this.$refs.mediaInput.value = null;
                axios({
                    method: 'POST',
                    data: formData,
                    url,
                    cancelToken: this.medias[taskId].source.token,
                    onUploadProgress
                }).then((response) => {
                    if (!isObject(response.data)) {
                        this.medias[taskId].status = 2;
                        return this.medias[taskId].msg = gaem({ response }, response.data);
                    }
                    this.medias[taskId].status = 1;
                    if (this.medias[taskId].type == 'audio/mpeg') {
                        this.mdl.isi += `<audio controls controlsList="nodownload"><source src="${response.data.location}" type="audio/mpeg">Your browser does not support the audio element.</audio>`;
                    } else {
                        this.mdl.isi += `<div><div class="ratio ratio-16x9"><video controls="controls"><source src="${response.data.location}" type="${this.medias[taskId].type}" /></video></div></div>`;
                    }
                }, (error) => {
                    this.medias[taskId].status = 2;
                    if (!error.response) return this.medias[taskId].msg = "Dibatalkan";
                    return this.medias[taskId].msg = gaem(error);
                })
            },
            detail(id, onsuccess = null, onerror = null) {
                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.id;
                    this.mdl.judul = response.data.judul;
                    this.mdl.isi = response.data.isi;
                    this.mdl.is_active = response.data.is_active;
                    this.mdl.kompetensi.value = response.data.kompetensi_id;
                    this.mdl.file.value = response.data.file;
                    this.modal("show")
                    if (onsuccess) {
                        onsuccess(response)
                    }
                }, (error) => {
                    Swal.fire('Gagal', gaem(error), 'error')
                    if (onerror) {
                        onerror(error)
                    }
                });
            },
            loadKompetensi() {
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + `/panel/e-learning/kompetensi-dasar/all`
                }).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) => {
                        this.mdl.kompetensi.value = v.id;
                        return { value: v.id, text: `${v.kode} - ${v.nomor} ${v.nama}`, kode_mapel: v.kode_mapel };
                    })
                }, (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('judul', this.mdl.judul);
                formData.append('isi', this.mdl.isi);
                formData.append('is_active', this.mdl.is_active);
                formData.append('kompetensi_id', this.mdl.kompetensi.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('judul', this.mdl.judul);
                formData.append('kompetensi_id', this.mdl.kompetensi.value);
                formData.append('isi', this.mdl.isi);
                formData.append('is_active', this.mdl.is_active);
                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);
            },
            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')
                        });
                    }
                });
            },
            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;
                }
            },
            ondataload(data) {
                this.grid.data = data.materi;
                this.kode_mapel = data.kode_mapel;
                this.grid.ready = true;
                return this.grid.data;
            },
        },
        computed: {
            jadwalId() {
                let id = window.location.href.split('/');
                return id[id.length - 1];
            },
            filteredKompetensi() {
                return this.mdl.kompetensi.options.filter(v => v.kode_mapel == this.kode_mapel)
            }
        }
    }
})();
