var VPAdd = (function () {
    let vp_template = `
    <div class="card-style">
        <div class="input-style-1">
            <label>Judul</label>
            <input required type="text" v-model="judul" placeholder="Judul Pengumuman">
        </div>
        <div class="form-group">
            <label>Tujuan</label>
            <div class="row">
                <div class="col-6">
                    <label><input type="radio" :checked="tujuan==1" @click="tujuan=1" name="tujuan"> Guru</label>
                </div>
                <div class="col-6">
                    <label><input type="radio" :checked="tujuan==2" @click="tujuan=2" name="tujuan"> Siswa</label>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label>Informasi Pengumuman</label>
            <input type="file" class="d-none" ref="audioInput" @change="addAudio">
            <editor v-model="body" :tinymceScriptSrc="$store.state.config.base_url+'/vendors/tinymce/js/tinymce/tinymce.min.js'" :api-key="tinymcekey" :init="tinymceinit" />
        </div>
        <button v-if="id" class="btn btn-primary m-2" @click="edit">{{loading?'Menyimpan...':'Simpan'}}</button>
        <button class="btn btn-primary m-2" @click="id?id=null:add()">{{loading&&!id?'Menambahkan...':'Tambah'}}</button>
    </div>`
    return {
        template: vp_template,
        props: ['tinymcekey'],
        name: "add",
        data() {
            return {
                id: null,
                judul: '',
                tujuan: 1,
                loading: false,
                body: '',

                tinymceinit: {
                    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 addAudio formula ",
                    setup: (editor) => {
                        editor.ui.registry.addButton('addAudio', {
                            icon: 'arrow-right',
                            onAction: (_) => {
                                this.$refs.audioInput.click();
                            }
                        });
                    },
                }
            }
        },
        mounted() {

            this.eventListener();
        },
        methods: {
            eventListener() {
                document.addEventListener('click', (e) => {
                    if (e.target && e.target.id == 'trigger-edit') {
                        this.detail(e.target.dataset.id)
                    }
                });
            },
            detail(id) {
                axios({
                    method: 'GET',
                    url: window.location.href + "/detail/" + id,
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.id = response.data.id;
                    this.judul = response.data.judul;
                    this.tujuan = response.data.tujuan;
                    this.body = response.data.body;
                }, (error) => {
                    Swal.fire('Error', gaem(error), 'error')
                }).finally(() => this.loading = false);
            },
            edit() {
                if (this.loading || !this.id || this.judul.length <= 0 || this.body.length <= 0) return;
                this.loading = true;
                axios({
                    method: 'PUT',
                    data: { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value, judul: this.judul, tujuan: this.tujuan, body: this.body },
                    url: window.location.href + '/edit/' + this.id,
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    document.getElementById('reload-btn').click();
                    this.id = null;
                    this.judul = '';
                    this.body = '';
                }, (error) => {
                    Swal.fire('Error', gaem(error), 'error')
                }).finally(() => this.loading = false);
            },
            images_upload_handler(blobInfo, success, failure, progress) {
                var xhr, formData;

                xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                xhr.open('POST', this.$store.state.config.base_url + '/panel/pengumuman/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);
            },
            addAudio(e) {
                var files = e.target.files || e.dataTransfer.files;
                if (!files.length) return;
                const formData = new FormData();
                formData.append('audio', files[0]);
                formData.append([this.$store.state.config.csrf.name], this.$store.state.config.csrf.value);
                axios({
                    method: 'POST',
                    data: formData,
                    url: this.$store.state.config.base_url + '/panel/pengumuman/audioUploader',
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    let e = `
                    <audio controls controlsList="nodownload">
                      <source src="${response.data.location}" type="audio/mpeg">
                    Your browser does not support the audio element.
                    </audio>`;
                    this.body += e;
                }, (error) => {
                    Swal.fire('Error', gaem(error), 'error')
                })
            },
            add() {
                if (this.loading || this.judul.length <= 0 || this.body.length <= 0) return;
                this.loading = true;
                axios({
                    method: 'POST',
                    data: { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value, judul: this.judul, tujuan: this.tujuan, body: this.body },
                    url: window.location.href,
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    document.getElementById('reload-btn').click();
                    this.id = null;
                    this.judul = '';
                    this.body = '';
                }, (error) => {
                    Swal.fire('Error', gaem(error), 'error')
                }).finally(() => this.loading = false);
            },
            ondataload(data) {
                this.grid.data = data.data;
                this.grid.ready = true;
                return data.data;
            },
        },
    }
})();
