var VPView = (function () {
    let vp_template = `
    <div v-show="tugas_id" class="card-style">
        <div style="text-align:right">
            <button class="main-btn btn-sm success-btn rounded-md btn-hover" @click="exportNilai()">
                <i class="fas fa-file-excel"></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="viewdataload"></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():''">
                <div class="input-style-1">
                    <label>Nilai</label>
                    <input v-model="mdl.point" type="number" min="0" placeholder="Nilai">
                </div>
                <div class="input-style-1">
                    <label>Komentar</label>
                    <textarea v-model="mdl.comment" placeholder="Komentar"></textarea>
                </div>
                <div v-if="mdl.file" >
                    <a v-for="(file,i) in mdl.file" class="btn btn-primary btn-sm mx-1" :download="'Lampiran '+(i+1)+' - '+mdl.nama+' - '+mdl.nomor_induk+'.'+file.split('.').pop()" :href="file">Lampiran {{i+1}}</a>
                </div>
                <label>Jawaban</label>
                <div>
                    {{mdl.answer}}
                </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>
                        Simpan
                    </template>
                  </button>
              </div>
                </form>
              </div>
            </div>
          </div>
        </div>
    </div>
    
    
    `;
    return {
        template: vp_template,
        name: "view-tugas",
        data() {
            return {
                grid: {
                    ready: false,
                    data: [],
                    id: "vt-table",
                    ref: "vt-table",
                    columns: [
                        { id: 'nomor_induk', name: "Nomor Induk" },
                        { id: 'nama', name: "Nama" },
                        { id: 'point', name: "Nilai" },
                        { id: 'comment', name: "Komentar" },
                        {
                            id: 'answered', name: "Dijawab",
                            formatter: (_, row) => {
                                return row.cells[4].data == '1' ? "Terjawab" : "Belum Terjawab";
                            }
                        },
                        {
                            id: 'id',
                            name: 'Aksi',
                            formatter: (_, row) => {
                                let btn = `<div class="d-flex">`;
                                btn += `&nbsp;<button class="btn btn-success rounded-md" id="trigger-correction" data-id="${row.cells[5].data}"><i id="trigger-correction" data-id="${row.cells[5].data}" class='fas fa-user-edit'></i></button>`;
                                btn += "</div>";
                                return gridjs.html(btn);
                            }
                        },
                    ]
                },
                tugas_id: 0,
                judul_tugas: '',
                mdl: {
                    id: null,
                    nama: '',
                    point: 0,
                    comment: '',
                    answer: '',
                },
            }
        },
        mounted() {
            this.grid.url = window.location.href + "/answers/" + this.tugas_id;
            this.eventListener();
        },
        watch: {
            tugas_id(v) {
                this.grid.url = window.location.href + "/answers/" + this.tugas_id;
            }
        },
        methods: {
            setId(v) {
                this.tugas_id = v;
            },
            setJudul(v) {
                this.judul_tugas = v;
            },
            eventListener() {
                document.addEventListener('click', (e) => {
                    if (e.target && e.target.id == 'trigger-correction') {
                        this.detail(e.target.dataset.id)
                    }
                    this.$refs.modal.addEventListener('hide.bs.modal', (e) => {
                        this.mdl.id = null;
                    });
                });
            },
            exportNilai() {
                let rows = [["No", "Nomor Induk", "Nama", "Nilai", "File", "Dibuat"]];
                this.grid.data.forEach((v, i) => {
                    rows.push([i + 1, v.nomor_induk, v.nama, v.point || 0, v.file, moment.unix(v.created_at).format('YYYY-MM-DD HH:mm')]);
                })
                let csv = "data:text/csv;charset=utf-8," + rows.map(e => e.join(";")).join("\n");
                let link = document.createElement("a");
                link.setAttribute("href", encodeURI(csv));
                link.setAttribute("download", `Nilai-Tugas-${this.judul_tugas.replace(' ', '-')}.csv`);
                document.body.appendChild(link); // Required for FF

                link.click(); // This will download the data file named "my_data.cs
                link.remove();
            },
            detail(id) {
                showDismisableLoading();
                axios({
                    method: 'get',
                    url: window.location.href + "/answer/" + 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.nomor_induk = response.data.nomor_induk;
                    this.mdl.nama = response.data.nama;
                    this.mdl.point = response.data.point;
                    this.mdl.comment = response.data.comment;
                    this.mdl.file = response.data.file ? response.data.file.split(',') : [];
                    this.mdl.answer = response.data.answer;
                    this.modal("show")
                }, (error) => {
                    Swal.fire('Gagal', gaem(error), 'error')
                });
            },
            edit() {
                showDismisableLoading();
                let url = window.location.href + "/answer/" + this.mdl.id;
                axios({
                    method: 'patch',
                    data: {
                        [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value,
                        point: this.mdl.point,
                        comment: this.mdl.comment,
                    },
                    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);
            },
            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;
                }
            },
            viewdataload(data) {
                this.grid.data = data;
                this.grid.ready = true;
                return this.grid.data;
            },
        },
    }
})();
