var VPJadwalTugas = (function () {
    let gridConf = {
        ready: false,
        data: [],
        id: "jt-table",
        ref: "jt-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 `${row.cells[8].data} ${row.cells[3].data}`;
                }
            },
            {
                id: 'ddm', name: "Batas Tugas",
                formatter: (_, row) => {
                    let btn = `<div class="badge text-dark">${row.cells[4].data.format("YYYY-MM-DD HH:mm")}</div>`;
                    return gridjs.html(btn);
                }
            },
            {
                id: 'file', name: "File", formatter: (_, row) => {
                    if (row.cells[5].data) {
                        btn = `&nbsp;<a download="${row.cells[2].data.split(' ').join('-')}-${row.cells[1].data.split(' ').join('-')}-${row.cells[0].data.split(' ').join('-')}-${row.cells[8].data.split(' ').join('-')}-${row.cells[3].data.split(' ').join('-')}.pdf" class="btn btn-success rounded-md" href="${row.cells[5].data}"><i class='fas fa-file-pdf'></i></a>`;
                        return gridjs.html(btn);
                    }
                }
            },
            {
                id: 'is_active',
                name: 'Status',
                formatter: (_, row) => {
                    let btn = `<div class="badge bg-${row.cells[6].data == 1 ? 'primary' : 'danger'}">${row.cells[6].data == 1 ? "Aktif" : "Tidak Aktif"}</div>`;
                    return gridjs.html(btn);
                }
            },
            {
                id: 'id',
                name: 'Aksi',
                formatter: (_, row) => {
                    let btn = `<div class="d-flex">`;
                    btn += `&nbsp;<button class="btn btn-success rounded-md" id="trigger-view" data-id="${row.cells[7].data}" data-judul="${row.cells[2].data}"><i id="trigger-view" data-id="${row.cells[7].data}" class='fas fa-user-edit'></i></button>`;
                    btn += `&nbsp;<button class="btn btn-primary rounded-md" id="trigger-edit" data-id="${row.cells[7].data}"><i id="trigger-edit" data-id="${row.cells[7].data}" class='lni lni-pencil-alt'></i></button>`;
                    btn += `&nbsp;<button class="btn btn-danger rounded-md" id="trigger-delete" data-id="${row.cells[7].data}"><i id="trigger-delete" data-id="${row.cells[7].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="modal('show')">
                <i class="lni lni-plus"></i>
            </button>
            &nbsp;
            <button class="main-btn btn-sm secondary-btn rounded-md btn-hover" @click="$refs.cti.start()">
                <i class="fas fa-clone"></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="grid.url" :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">{{mdl.id?'Ubah':'Tambah'}} Tugas</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-2">
                    <label>Deskripsi</label>
                    <editor :tinymceScriptSrc="$store.state.config.base_url+'/vendors/tinymce/js/tinymce/tinymce.min.js'" v-model="mdl.deskripsi"  :api-key="tinymcekey" :init="tinymce" />
               </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="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 mb-2" 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="row m-0">
                    <div class="col-6">
                        <div class="input-style-1">
                            <label>Batas Tanggal</label>
                            <input type="date" required v-model="mdl.dueDate.date" :min="mdl.dueDate.min" :max="mdl.dueDate.max" placeholder="Tanggal Batas">
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="input-style-2">
                            <label>Batas Jam</label>
                            <input required @change="mdl.dueDate.instance.setValue(mdl.dueDate.time)" v-model="mdl.dueDate.time" placeholder="--:--">
                            <span style="cursor:pointer" class="icon">
                                <i class="far fa-clock" id="dueDate" ref="dueDate">
                                </i>
                            </span>
                        </div>
                    </div>
                </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>
    
    <view-tugas ref="vt"></view-tugas>
    <salin-tugas @updated="$event?$refs[grid.ref].reload():''" :jadwal-id="jadwalId" ref="cti"></salin-tugas>
    `;
    return {
        template: vp_template,
        props: ['tinymcekey',],
        name: "jadwal-tugas",
        data() {
            return {
                grid: gridConf,

                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 formula ",
                },
                kode_mapel: '',
                mdl: {
                    file: {
                        value: null,
                        raw: null,
                        canvas: false,
                    },
                    judul: '',
                    deskripsi: '',
                    is_active: '1',
                    dueDate: {
                        min: "1997-01-01",
                        max: `${(new Date(((new Date()).getFullYear() + 10).toString())).getFullYear()}-12-31`,
                        date: `${(new Date()).getFullYear()}-${((new Date()).getMonth() + 1).toString().length == 1 ? "0" + ((new Date()).getMonth() + 1).toString() : (new Date()).getMonth() + 1}-${((new Date()).getDate()).toString().length == 1 ? "0" + ((new Date()).getDate()).toString() : (new Date()).getDate()}`,
                        time: `${(new Date()).getHours()}:${(new Date()).getMinutes()}`,
                        instance: null
                    },
                    kompetensi: {
                        value: null,
                        options: [],
                        raw: []
                    },
                },
            }
        },
        mounted() {

            this.eventListener();
            this.loadKompetensi();
            this.timePicker()
        },
        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)
                    }
                    if (e.target && e.target.id == 'trigger-view') {
                        this.$refs.vt.setId(e.target.dataset.id);
                        this.$refs.vt.setJudul(e.target.dataset.judul);
                    }
                    this.$refs.modal.addEventListener('hide.bs.modal', (e) => {
                        this.mdl.id = null;
                        this.resetFile();
                    });
                    document.addEventListener('focusin', (e) => {
                        if (e.target.closest(".tox-tinymce-aux, .moxman-window, .tam-assetmanager-root") !== null) {
                            e.stopImmediatePropagation();
                        }
                    });
                });
            },
            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);
            },
            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]);
            },
            timePicker() {
                this.mdl.dueDate.instance = new NJTimePicker({
                    targetID: 'dueDate',
                    format: '24',
                    autoSave: true
                });

                this.mdl.dueDate.instance.on('save', (data) => {
                    if (data.fullResult.length < 6) {
                        data.fullResult += ":00";
                    }
                    this.mdl.dueDate.time = data.fullResult
                });
                this.mdl.dueDate.instance.setValue(this.mdl.dueDate.time);
            },
            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, 'Terjadi Kesalahan Saat Mengambil Data Kompetensi Dasar'), 'error')
                });
            },
            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.id;
                    this.mdl.judul = response.data.judul;
                    this.mdl.deskripsi = response.data.deskripsi;
                    this.mdl.is_active = response.data.is_active;
                    this.mdl.kompetensi.value = response.data.kompetensi_id;
                    let dd = mm({ unix: response.data.dueDate });
                    this.mdl.dueDate.date = dd.format("YYYY-MM-DD");
                    this.mdl.dueDate.time = dd.format("HH:mm");
                    this.mdl.file.value = response.data.file;
                    this.mdl.dueDate.instance.setValue(dd.format("HH:mm"));
                    this.modal("show")
                }, (error) => {
                    Swal.fire('Gagal', gaem(error), 'error')
                });
            },
            add() {
                let m = moment(this.mdl.dueDate.date + " " + this.mdl.dueDate.time);
                if (!m.isValid()) return;
                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('deskripsi', this.mdl.deskripsi);
                formData.append('kompetensi_id', this.mdl.kompetensi.value);
                formData.append('is_active', this.mdl.is_active);
                formData.append('dueDate', m.unix());
                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 m = moment(this.mdl.dueDate.date + " " + this.mdl.dueDate.time);
                if (!m.isValid()) return;
                let data = new FormData();
                data.append([this.$store.state.config.csrf.name], this.$store.state.config.csrf.value);
                if (this.mdl.file.raw) data.append('file', this.mdl.file.raw);
                data.append('file_value', this.mdl.file.value);
                data.append('judul', this.mdl.judul);
                data.append('deskripsi', this.mdl.deskripsi);
                data.append('kompetensi_id', this.mdl.kompetensi.value);
                data.append('is_active', this.mdl.is_active);
                data.append('dueDate', m.unix());
                this.mdl.loading = true;
                let url = window.location.href + "/edit/" + this.mdl.id;
                axios({
                    method: 'post',
                    data,
                    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('Gagal', 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.tugas.map(v => {
                    v.kode_mapel = data.kode_mapel;
                    v.nama_kelas = data.nama_kelas;
                    v.ddm = mm({ unix: v.dueDate })
                    v.cam = mm({ unix: v.created_at })
                    v.uam = mm({ unix: v.updated_at })
                    return v;
                });
                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)
            }
        }
    }
})();
