var VPBankSoal = (function () {
    return {
        name: "banksoal",

        template: "#main-template",
        props: ['isguru'],
        data() {
            return {
                query: '',
                soals: {
                    data: [],
                    loading: false,
                    errMsg: '',
                },
                guru: {
                    show: false,
                    value: null,
                    data: []
                },
                cancelToken: axios.CancelToken,
            }
        },
        mounted() {
            this.loadSoals();
            this.loadGuru();
        },
        methods: {
            importSoal(e) {
                let [file] = e.target.files || e.dataTransfer.files;
                if (!file) return this.$refs.fileImport.value = null;
                let soal = this.soals.data.find(x => x.id == this.$refs.fileImport.dataset.id);
                // source: null,
                // percent: 0,
                // status: 0,
                soal.importSoal.status = 1;
                soal.importSoal.percent = 0;
                soal.importSoal.source = this.cancelToken.source();
                let onUploadProgress = event => {
                    const percentCompleted = Math.round((event.loaded * 100) / event.total);
                    soal.importSoal.percent = percentCompleted;
                }
                const formData = new FormData();
                formData.append([this.$store.state.config.csrf.name], this.$store.state.config.csrf.value);
                formData.append('file', file);
                formData.append('id', soal.id);
                let url = this.$store.state.config.base_url + '/panel/bank-soal/import';
                this.$refs.fileImport.value = null;
                axios({
                    method: 'POST',
                    data: formData,
                    url,
                    cancelToken: soal.importSoal.source.token,
                    onUploadProgress
                }).then((response) => {
                    if (!isObject(response.data)) {
                        soal.importSoal.status = 3;
                        return toastr.error(gaem({ response }, response.data));
                    }
                    soal.importSoal.status = 2;
                    this.loadSoal(soal.id);
                }, (error) => {
                    soal.importSoal.status = 3;
                    if (!error.response) return toastr.error("Dibatalkan");
                    toastr.error(gaem(error));
                }).finally(() => setTimeout(() => soal.importSoal.status = 0, 1000))
            },
            addSoalTemp() {
                let soals = this.soals.data.reverse();
                soals.push({
                    id: Math.round(Math.random()),
                    editmode: true,
                    isnew: true,
                });
                soals.reverse();
            },
            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.guru.data = response.data.data.map((v, i) => {
                        if (i == 0) {
                            this.guru.value = v.id;
                        }
                        return { value: v.id, text: v.fullname };
                    });
                }, (error) => {
                    Swal.fire('Gagal', gaem(error, 'Gagal Mengambil Data Guru'), 'error')
                });
            },
            loadSoals() {
                this.soals.loading = true;
                this.soals.errMsg = '';
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + '/panel/bank-soal/all',
                }).then((response) => {
                    if (!isObject(response.data)) return this.soals.errMsg = gaem({ response }, response.data);
                    if (!response.data.data) return this.soals.errMsg = "Data tidak ditemukan";
                    this.soals.data = response.data.data.map(v => {
                        v.importSoal = {
                            source: null,
                            percent: 0,
                            status: 0,
                        };
                        v.total_pg = parseInt(v.count_soal_pg) + parseInt(v.count_soal_pgmulti) + parseInt(v.count_soal_pgtf) + parseInt(v.count_soal_pgcouple);
                        v.created_at = mm({ unix: v.created_at }).format("DD MMMM YYYY HH:mm")
                        return v;
                    });
                }, (error) => {
                    this.soals.errMsg = gaem(error);
                }).finally(() => this.soals.loading = false);
            },
            loadSoal(id) {
                let soal = this.soals.data.find(v => v.id == id);
                if (!soal) return;
                soal.loading = true;
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + '/panel/bank-soal/' + id,
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    let s = response.data;
                    soal.total_pg = parseInt(s.count_soal_pg) + parseInt(s.count_soal_pgmulti) + parseInt(s.count_soal_pgtf) + parseInt(s.count_soal_pgcouple);
                    soal.created_at = mm({ unix: s.created_at }).format("DD MMMM YYYY HH:mm")
                    soal.created_by = s.created_by;
                    soal.kode = s.kode;
                    if (!soal.importSoal) {
                        soal.importSoal = {
                            source: null,
                            percent: 0,
                            status: 0,
                        };
                    }
                }, (error) => {
                    Swal.fire('Gagal', gaem(error), 'error');
                }).finally(() => soal.loading = false);
            },
            simpan(id) {
                let soal = this.soals.data.find(v => v.id == id);
                if (!soal) return;
                if (soal.loading) return;
                let data = {
                    [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value,
                    kode: soal.kode,
                    isnew: soal.isnew,
                    deskripsi: soal.deskripsi,
                }
                if (!this.isguru) data.user_id = soal.user_id;
                soal.loading = true;
                axios({
                    method: 'put',
                    data: data,
                    url: this.$store.state.config.base_url + '/panel/bank-soal/' + id,
                }).then((response) => {
                    // if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    if (soal.isnew) {
                        soal.id = response.data.id;
                        delete soal.isnew;
                    }
                    soal.editmode = false;
                    soal.loading = false
                    this.loadSoal(soal.id);
                }, (error) => {
                    soal.loading = false
                    Swal.fire('Gagal', gaem(error), 'error');
                })
            },
            hapusTerpilih() {
                let soals = this.soals.data.filter(v => v.checked && !v.loading && !v.isnew);
                if (soals.length == 0) return;
                SwalDelete({
                    params: { confirmButtonText: 'Ya, hapus ini!' },
                    confirmed: () => {
                        soals.forEach(el => el.loading = true);
                        axios({
                            method: 'DELETE',
                            data: { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value, id: soals.map(v => v.id) },
                            url: this.$store.state.config.base_url + "/panel/bank-soal",
                        }).then((response) => {
                            soals.forEach(el => {
                                let index = this.soals.data.findIndex(v => v.id == el.id);
                                if (index != -1) this.soals.data.splice(index, 1);
                            })
                        }, (error) => {
                            soals.forEach(el => el.loading = false);
                        });
                    }
                });
            },
            hapus(id) {
                let soal = this.soals.data.find(v => v.id == id);
                if (!soal) return;
                if (soal.loading) return;

                SwalDelete({
                    params: { confirmButtonText: 'Ya, hapus ini!' },
                    confirmed: () => {
                        soal.loading = true;
                        axios({
                            method: 'DELETE',
                            data: { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value, },
                            url: this.$store.state.config.base_url + "/panel/bank-soal/" + id,
                        }).then((response) => {
                            let index = this.soals.data.findIndex(v => v.id == id);
                            if (index != -1) this.soals.data.splice(index, 1);
                        }, (error) => {
                        }).finally(() => soal.loading = false);
                    }
                });

            }
        },
        computed: {
            parsedSoals() {
                if (this.query.length == 0) return this.soals.data;
                let soals = this.soals.data.filter(v => {
                    let q = `${v.kode}${v.created_by}${v.deskripsi}`.replaceAll("\n", "").replaceAll("\r", "").replaceAll(" ", "").toLowerCase();
                    if (q.search(this.query.toLowerCase()) != -1) return true;
                    return false;
                });
                return soals;
            }
        }
    }
})();
