var VPDiskusi = (function () {
    let vp_template = `
    
    <div class="message-box-wrapper card-style h-100">
        <div>
            <div class="message-header mb-20">
                <div class="chat-list-item">
                    <div v-if="false" class="image">
                        <img src="assets/images/lead/lead-6.png" alt="">
                        <span class="status"></span>
                    </div>
                    <div class="content">
                        <div class="title">
                            <h6 v-if="nama_mapel&&nama_mapel" class="text-sm text-medium">{{nama_mapel}} - {{nama_kelas}}</h6>
                            <div v-if="false"  class="more-btn-wrapper">
                                <button class="more-btn dropdown-toggle" id="moreAction" data-bs-toggle="dropdown" aria-expanded="false">
                                    <i class="lni lni-more-alt"></i>
                                </button>
                                <ul v-if="false" class="dropdown-menu dropdown-menu-end" aria-labelledby="moreAction">
                                    <li class="dropdown-item">
                                        <a href="javascript:void(0)" class="text-gray">Mark as Read</a>
                                    </li>
                                    <li class="dropdown-item">
                                        <a href="javascript:void(0)" class="text-gray">Reply</a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <p v-if="conversations.length" class="text-sm">
                            <span class="mr-10">Percakapan Terakhir 
                            <template v-if="conversations[conversations.length-1].cam.format('YYYY-MM-DD')==mm().format('YYYY-MM-DD')">
                                {{conversations[conversations.length-1].cam.format('HH:mm')}}
                            </template>
                            <template v-else-if="conversations[conversations.length-1].cam.format('YYYY-MM-DD')==mm().subtract(1, 'd').format('YYYY-MM-DD')">
                                Kemarin {{conversations[conversations.length-1].cam.format('HH:mm')}}
                            </template>
                            <template v-else-if="conversations[conversations.length-1].cam.format('YYYY-MM-DD')==mm().subtract(1, 'w').format('YYYY-MM-DD')">
                                Minggu Lalu {{conversations[conversations.length-1].cam.format('HH:mm')}}
                            </template>
                            <template v-else-if="conversations[conversations.length-1].cam.format('YYYY-MM')==mm().format('YYYY-MM')">
                                {{conversations[conversations.length-1].cam.format('DD HH:mm')}}
                            </template>
                            <template v-else-if="conversations[conversations.length-1].cam.format('YYYY')==mm().format('YYYY')">
                                {{conversations[conversations.length-1].cam.format('DD MMMM HH:mm')}}
                            </template>
                            <template v-else>
                                {{conversations[conversations.length-1].cam.format('YYYY-MM-DD HH:mm')}}
                            </template>
                            </span>
                        </p>
                    </div>
                </div>
            </div>
            <!-- end message header -->
            <div style="max-height:500px;overflow:auto" ref="messagesBox" class="message-body" @scroll="msgScrl">
                <template v-for="(conversation,index) in conversations">
                    <template v-if="index!=0">
                        <div v-if="conversation.cam.format('YYYY-MM-DD')==mm().subtract(1,'d').format('YYYY-MM-DD')&&conversation.cam.format('YYYY-MM-DD')!=conversations[index-1].cam.format('YYYY-MM-DD')" class="my-4" style="width: 100%;height: 12px;border-bottom: 1px solid black;text-align: center">
                            <span style="background-color: rgb(255 255 255);padding: 0px 10px;">Kemarin</span>
                        </div>
                        <div v-else-if="conversation.cam.format('YYYY-MM-DD')==mm().format('YYYY-MM-DD')&&conversation.cam.format('YYYY-MM-DD')!=conversations[index-1].cam.format('YYYY-MM-DD')" class="my-4" style="width: 100%;height: 12px;border-bottom: 1px solid black;text-align: center">
                            <span style="background-color: rgb(255 255 255);padding: 0px 10px;">Hari Ini</span>
                        </div>
                        <div v-else-if="conversation.cam.format('YYYY-MM')!=conversations[index-1].cam.format('YYYY-MM')" class="my-4" style="width: 100%;height: 12px;border-bottom: 1px solid black;text-align: center">
                            <span v-if="conversation.cam.format('YYYY')==mm().format('YYYY')" style="background-color: rgb(255 255 255);padding: 0px 10px;">{{conversation.cam.format('DD MMMM')}}</span>
                            <span v-else style="background-color: rgb(255 255 255);padding: 0px 10px;">{{conversation.cam.format('DD MMMM YYYY')}}</span>
                        </div>
                    </template>
                    <template v-else>
                        <div v-if="conversation.cam.format('YYYY-MM-DD')==mm().subtract(1,'d').format('YYYY-MM-DD')" class="my-4" style="width: 100%;height: 12px;border-bottom: 1px solid black;text-align: center">
                            <span style="background-color: rgb(255, 255, 255);padding: 0px 10px;">Kemarin</span>
                        </div>
                        <div v-else-if="conversation.cam.format('YYYY-MM')!=mm().format('YYYY-MM')" class="my-4" style="width: 100%;height: 12px;border-bottom: 1px solid black;text-align: center">
                            <span v-if="conversation.cam.format('YYYY')==mm().format('YYYY')" style="background-color: rgb(255 255 255);padding: 0px 10px;">{{conversation.cam.format('DD MMMM')}}</span>
                            <span v-else style="background-color: rgb(255 255 255);padding: 0px 10px;">{{conversation.cam.format('DD MMMM YYYY')}}</span>
                        </div>
                    </template>
                <div v-if="conversation.is_me!=1" :ref="conversation.id" class="message-box">
                    <div v-if="false" class="image">
                    <img src="assets/images/lead/lead-6.png" alt="">
                    </div>
                    <div class="content-box">
                    <div class="title d-sm-flex mb-2 justify-content-between align-items-center">
                        <div class="row">
                            <h6 class="text-sm text-medium">{{conversation.nama}}</h6>
                            <small class="text-sm text-medium">{{conversation.nomor_induk}}</small>
                        </div>
                        <span class="text-sm">{{conversation.cam.format('HH:mm')}}</span>
                    </div>                        
                    <div class="content" v-html="conversation.conversation">
                    </div>
                    </div>
                </div>

                <div v-else-if="!conversation.deleting" :ref="conversation.id" class="message-box right">
                    <div v-if="false" class="image">
                        <img src="assets/images/lead/lead-2.png" alt="">
                    </div>
                    <div :style="!conversation.sending?'cursor:pointer':''" @mousedown="!conversation.sending?chatpress(conversation.id):''" @mouseleave="!conversation.sending?schatpress():''" @mouseup="!conversation.sending?schatpress():''" @touchstart="!conversation.sending?chatpress(conversation.id):''" @touchend="!conversation.sending?schatpress():''" @touchcancel="!conversation.sending?schatpress():''" class="content-box" :class="conversation.failed?'bg-danger':(conversation.sending?'bg-warning':'')">
                        <div class="title d-sm-flex mb-2 justify-content-between align-items-center">
                            <div class="row">
                                <h6 class="text-sm text-medium">{{conversation.nama}}</h6>
                                <small class="text-sm text-medium">{{conversation.nomor_induk}}</small>
                            </div>
                            <span class="text-sm">{{conversation.cam.format('HH:mm')}}</span>
                        </div>
                        <div class="content" v-html="conversation.conversation">
                        </div>
                    </div>
                    <div class="dropstart" v-if="false">
                        <button class="btn btn-options dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"><i class="bi bi-three-dots-vertical"></i></button>
                            <ul class="dropdown-menu" style="">
                                <li class="px-2"><a @click="deleteConversation(conversation.id)" href="javascript:void(0)"><i class="lni lni-trash-can"></i> Hapus</a></li>
                                <li v-if="conversation.failed" class="px-2" ><a @click="resend(conversation.id)" href="javascript:void(0)"><i class="far fa-paper-plane"></i> Kirim Ulang</a></li>
                            </ul>
                    </div>
                </div>
                </template>
                <!-- end message-box-->
                <div class="text-center" v-if="conversations.length<=0">
                    <template v-if="ready">
                        <img class="w-25" :src="$store.state.config.base_url+'/assets/img/no-conversations.png'">
                        <h1>Tidak Ada Percakapan</h1>
                    </template>
                    <template v-else>
                        <div class="p-1">
                            <div class="spinner-border" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                        </div>
                    </template>
                </div>
            </div> 
        </div>
        <!-- end message body -->
        <div class="message-form mt-5">
            <div class="message-field">
                <editor :tinymceScriptSrc="$store.state.config.base_url+'/vendors/tinymce/js/tinymce/tinymce.min.js'" v-model="message"  :api-key="tinymcekey" :init="tinymce" />

            </div>
        </div>
    </div>


    <div class="modal fade" id="modal-chatpress" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-md modal-dialog-centered">
            <div class="modal-content card-style">
                <div class="modal-header px-0 border-0">
                    <h5 class="text-bold">Aksi</h5>
                    <button class="border-0 bg-transparent h1" @click="chathold.id=null" data-bs-dismiss="modal">
                        <i class="lni lni-cross-circle"></i>
                    </button>
                </div>
                <div class="modal-body px-0">
                    <div class="content">

                        <ul v-if="chatholddata" class="list-group list-group-flush">
                            <li v-if="!chatholddata.loading" data-bs-dismiss="modal" @click="deleteConversation(chatholddata.id)" style="cursor:pointer"  class="list-group-item">Hapus</li>
                            <li v-if="chatholddata.failed" data-bs-dismiss="modal" @click="resend(chatholddata.id)" style="cursor:pointer" class="list-group-item">Kirim Ulang</li>
                            <li v-if="chatholddata.failed" data-bs-dismiss="modal" @click="message=chatholddata.conversation,deleteConversation(chatholddata.id)" style="cursor:pointer" class="list-group-item">Ubah</li>
                        </ul>

                    </div>
                </div>
            </div>
        </div>
    </div>

    `;
    return {
        name: "jadwal-diskusi",
        props: ['tinymcekey',],
        template: vp_template,
        data() {
            return {
                tinymce: {
                    // Necessary
                    htmlAllowedTags: ['.*'],
                    htmlAllowedAttrs: ['.*'],

                    draggable_modal: true,
                    images_upload_handler: this.images_upload_handler,
                    plugins: [
                        'advlist autolink lists link image charmap print preview anchor',
                        'searchreplace visualblocks code fullscreen',
                        '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_location: 'bottom',
                    menubar: false,
                    toolbar:
                        "Kirim bold italic strikethrough link numlist bullist blockquote | image ",
                    setup: (editor) => {
                        editor.on('keydown', this.shortcut);
                        editor.ui.registry.addButton('Kirim', {
                            icon: 'comment-add',
                            text: "Kirim",
                            onAction: (_) => {
                                this.sendMsg();
                            }
                        });
                    },
                },
                ready: false,
                loading: false,
                sending: false,
                chathold: {
                    timeout: null,
                    modal: null,
                    id: null,
                },
                message: '',
                nama_mapel: '',
                nama_kelas: '',

                lastOld: (new Date()).getTime(),
                lastFetch: (new Date()).getTime(),
                conversations: [],
            }
        },
        mounted() {
            this.notification = new Audio(this.$store.state.config.base_url + '/assets/audio/elearning/notification.mp3');
            this.initConversation();
            this.setLoop();
        },
        methods: {
            chatpress(id) {
                if (this.chathold.timeout) clearTimeout(this.chathold.timeout);
                this.chathold.timeout = setTimeout(() => {
                    this.mdlchatpress();
                    this.chathold.id = id;
                }, 400);
            },
            schatpress() {
                if (this.chathold.timeout) clearTimeout(this.chathold.timeout);
            },
            shortcut(e) {
                if (!e.shiftKey && e.key == "Enter") {
                    e.preventDefault();
                    this.sendMsg();
                }
            },
            setLoop() {
                this.rand = this.conversations.length < 5 ? 2000 : Math.floor(Math.random() * 15000) + 2000;
                setTimeout(() => {
                    this.autoLoadNewest();
                    this.setLoop();
                }, this.rand);
            },
            autoLoadNewest() {
                let dt = new Date();
                dt.setSeconds(dt.getSeconds() - 2);
                if (this.lastFetch > dt.getTime()) return;
                if (this.conversations.length <= 0) return this.initConversation();
                this.loadNewConversations();
            },
            msgScrl(e) {
                if (this.$refs.messagesBox.scrollTop <= 145 && this.lastOld < (new Date()).getTime()) {
                    if (this.conversations.length <= 0) return this.initConversation();
                    return this.loadOldConversations();
                }
                if (this.$refs.messagesBox.scrollHeight - this.$refs.messagesBox.scrollTop === this.$refs.messagesBox.clientHeight) {
                    if (this.conversations.length <= 0) return this.initConversation();
                    return this.loadNewConversations();
                }
            },
            initConversation() {
                if (this.loading) return;
                this.loading = true;
                this.lastFetch = (new Date()).getTime();
                axios({
                    method: 'get',
                    url: window.location.href + "/init",
                }).then((response) => {
                    if (!isObject(response.data)) return setTimeout(this.initConversation, 1000);
                    this.ready = true;
                    this.conversations = response.data.conversations.map(v => {
                        v.cam = mm({ unix: v.created_at });
                        return v;
                    });
                    this.nama_kelas = response.data.nama_kelas;
                    this.nama_mapel = response.data.nama_mapel;
                    setTimeout(() => {
                        this.toLastMsg()
                    }, 100)
                }, (error) => {
                    setTimeout(this.initConversation, 1000);
                }).finally(() => this.loading = false);
            },
            loadOldConversations() {
                if (this.loading) return;
                this.loading = true;
                let lid = this.conversations[0].id;
                this.lastFetch = (new Date()).getTime();
                axios({
                    method: 'get',
                    url: window.location.href + "/oldest?lid=" + lid,
                }).then((response) => {
                    if (!isObject(response.data)) return setTimeout(this.loadOldConversations, 1000);
                    response.data.conversations = response.data.conversations.filter(v => this.conversations.findIndex(sv => sv.id == v.id) == -1).map(v => {
                        v.cam = mm({ unix: v.created_at });
                        return v;
                    }).reverse();
                    this.conversations = [...response.data.conversations, ...this.conversations];
                    let lid2 = this.conversations[response.data.conversations.length];
                    if (response.data.conversations.length > 0 && lid2) {
                        let dt = new Date();
                        dt.setSeconds(dt.getSeconds() + 1);
                        this.lastOld = dt.getTime();
                        setTimeout(() => {
                            this.$refs[lid2.id].scrollIntoView({ block: "nearest", inline: "nearest" })
                        }, 50);
                    }
                }, (error) => {
                    setTimeout(this.loadOldConversations, 1000);
                }).finally(() => this.loading = false);
            },
            loadNewConversations() {
                if (this.loading) return;
                this.loading = true;
                let c = this.conversations.filter(v => !v.sending && !v.failed);
                let lid = c[c.length - 1].id;
                this.lastFetch = (new Date()).getTime();
                axios({
                    method: 'get',
                    url: window.location.href + "/newest?lid=" + lid,
                }).then((response) => {
                    if (!isObject(response.data)) return setTimeout(this.loadNewConversations, 1000);
                    response.data.conversations = response.data.conversations.filter(v => this.conversations.findIndex(sv => sv.id == v.id) == -1).map(v => {
                        v.cam = mm({ unix: v.created_at });
                        return v;
                    })
                    if (response.data.conversations.length > 0 && this.$refs.messagesBox.scrollHeight - this.$refs.messagesBox.scrollTop === this.$refs.messagesBox.clientHeight) {
                        setTimeout(() => {
                            this.toLastMsg()
                        }, 100);
                    }
                    this.conversations = [...this.conversations, ...response.data.conversations];
                    if (response.data.conversations.length > 0) {
                        this.notification.play();
                    }
                }, (error) => {
                    setTimeout(this.loadNewConversations, 1000);
                }).finally(() => this.loading = false);
            },
            toLastMsg() {
                try {
                    if (this.conversations.length > 0) this.$refs[this.conversations[this.conversations.length - 1].id].scrollIntoView({ block: "nearest", inline: "nearest" });
                } catch (error) {

                }
            },
            resend(id) {
                let msg = this.conversations.find(v => v.id == id);
                if (!msg) return;
                if (msg.sending) return;
                if (!msg.failed) return;
                msg.sending = true;
                msg.failed = false;
                axios({
                    method: 'put',
                    data: { msg: { id: msg.id, conversation: msg.conversation }, [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value },
                    url: window.location.href + "/add",
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    msg.id = response.data.id;
                    msg.sending = false;
                    msg.failed = false;
                }, (error) => {
                    msg.sending = false;
                    msg.failed = true;
                });
            },
            sendMsg() {
                if (this.message.length <= 0) return;
                let msg = {
                    id: makeid(),
                    nama: this.$store.state.config.person.name,
                    is_me: "1",
                    sending: true,
                    failed: false,
                    conversation: this.message,
                    nomor_induk: this.$store.state.config.person.nomor_induk,
                    cam: this.mm(),
                    created_at: this.mm().unix(),
                    updated_at: this.mm().unix(),
                }
                this.conversations.push(msg);
                this.message = '';
                setTimeout(() => {
                    this.$refs[msg.id].scrollIntoView({ block: "nearest", inline: "nearest" })
                }, 50)
                axios({
                    method: 'put',
                    data: { msg: { id: msg.id, conversation: msg.conversation }, [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value },
                    url: window.location.href + "/add",
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    let m = this.conversations.find(v => v.id == msg.id);
                    m.id = response.data.id;
                    m.sending = false;
                    m.failed = false;
                    if (this.conversations.length <= 0) return this.initConversation();
                    return this.loadNewConversations();
                }, (error) => {
                    let m = this.conversations.find(v => v.id == msg.id);
                    m.sending = false;
                    m.failed = true;
                });
            },
            deleteConversation(id) {
                let chat = this.conversations.find(v => v.id == id);
                if (!chat) return;
                if (chat.failed) return this.conversations.splice(this.conversations.findIndex(v => v == chat.id), 1);
                if (chat.deleting) return;
                SwalDelete({
                    params: {
                        title: 'Hapus Percakapan',
                        text: 'Ini akan menghapus percakapan, apakah anda yakin?',
                        type: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#3085d6',
                        cancelButtonColor: '#d33',
                        confirmButtonText: 'Ya, Hapus!'
                    },
                    confirmed: () => {
                        chat.deleting = true;
                        axios({
                            method: 'delete',
                            data: { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value, },
                            url: window.location.href + "/delete/" + btoa(id),
                        }).then((response) => {
                            let si = this.conversations.findIndex(v => v.id == id);
                            if (si == -1) return;
                            this.conversations.splice(si, 1);
                        }, (error) => {
                            chat.deleting = false;
                            Swal.fire('Gagal', gaem(error, 'Silahkan Coba Lagi'), 'error');
                        });
                    }
                });
            },
            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);
            },
            mdlchatpress(e = 'show') {
                if (!this.chatpress.modal) {
                    this.chatpress.modal = new bootstrap.Modal(document.getElementById('modal-chatpress'));
                }
                switch (e) {
                    case "hide":
                        this.chatpress.modal.hide();
                        break;
                    case "show":
                        this.chatpress.modal.show();
                        break;
                    case "toggle":
                        this.chatpress.modal.toggle();
                        break;
                    case "dispose":
                        this.chatpress.modal.dispose();
                        break;
                }
            },
            mm() {
                return moment();
            }
        },
        computed: {
            chatholddata() {
                return this.conversations.find(v => v.id == this.chathold.id)
            }
        }
    }
})();
