var VPChatTP = (function () {
    let vp_template = `
    <div v-if="ready" style="position: fixed; right: 56px; bottom: 0px; z-index: 99;">
        
        <div v-show="pop" class="css-257zdh">
            <div class="css-1cobriv">
                <div class="css-1jltq8c">
                    <div class="css-1qdvk2a">
                        <div class="lftTopContent">
                            <h1 class="css-1rlh37j">Chat </h1>
                            <div title="Keluar" v-if="createmode.state" style="cursor:pointer" class="css-nop2ox" @click="createmode.state=false,createmode.selectmode=false">
                                <i class="fas fa-minus" ></i>
                            </div>
                            <div title="Buat Pesan" v-if="!createmode.state" style="cursor:pointer" class="css-nop2ox" @click="createmode.state=true,refreshUser()">
                                <i class="fas fa-users" ></i>
                            </div>
                            
                        </div>
                        
                        <div class="lftBottomContent">
                            <div height="auto" :class="'css-'+(focussearch?'d6ycei':'4xpgu2')" class="searchList e1v32nag0 active">
                                <button aria-label="Tombol pencarian" height="auto" type="submit" class="css-n7z893 e1v32nag1"><i class="fas fa-search"></i></button>
                                <input @focus="focussearch=true" @blur="focussearch=false"  aria-label="Bidang pencarian" data-unify="Search" id="iptChatListSearch" placeholder="Cari pengguna..." type="text" class="css-1jp1me2 e110g5pc0" v-model="searchquery">
                            </div>
                            

                        </div>

                    </div>
                    <div class="css-13eugn5">
                        <template v-if="createmode.state">
                            <template v-if="users.ready">
                                <div v-for="(u,i) in users_filtered" class="css-bycr5z my-1" :class="u.selected?'bg-info':''" @click="u.selected=!u.selected">
                                    <div class="chatImgWrapper"><img class="chatImg" :src="u.photo" :onerror="$store.state.config.onerrorAvatar" :alt="'Foto '+u.fullname"></div>
                                    <div class="chatContent">
                                        <p class="chatName">{{u.fullname}}</p>
                                        <template v-if="recentChatByUserId(u.id)">
                                            <span style="font-size:10px" v-html="(recentChatByUserId(u.id).message||'').replace(/(<([^>]+)>)/ig, '').substring(0,15)"></span>
                                        </template>
                                        <template v-else v-for="(role,ri) in u.roles"> 
                                            <span v-if="ri<1" class="css-1batapf mx-1">{{role.toUpperCase()}}</span>
                                        </template >
                                    </div>
                                </div>
                            </template>
                            <div v-else-if="!users.ready" class="text-center my-5">
                                <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                            </div>
                        </template>
                        <template v-else>
                            <div v-if="chat_list.ready" v-for="(cl,i) in chat_list_filtered" class="css-bycr5z my-1" @click="chat_list.current_chat=cl.id,initConversation()">
                                <div class="chatImgWrapper"><img class="chatImg" :src="cl.group_photo" :alt="cl.group_name"></div>
                                <div class="chatContent">
                                    <p class="chatName">{{cl.group_name}}</p>
                                    <span style="font-size:10px;" v-html="(cl.message||'').replace(/(<([^>]+)>)/ig, '').substring(0,15)"></span>
                                </div>
                            </div>
                            <div v-else-if="!chat_list.ready" class="text-center my-5">
                                <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                            </div>
                        </template>
                    </div>
                </div>
                <div class="css-1q5zhi9" aria-label="chat-right-side">
                    <div class="css-1ofqeah">
                        <template v-if="current_chat&&!createmode.state">
                        <div class="css-1aeei8j">
                            <div class="css-5pk8rw" data-testid="colChatUserHeader"><img class="headerImg" data-testid="imgChatUserHeader" :src="current_chat.group_photo" alt="Chat User"></div>
                            <div class="css-1uqp3dz" data-testid="colChatNamaToko" ><div class="profileNameWrapper"><p class="profileName" data-testid="spnChatNamaToko">{{current_chat.group_name}}</p><marquee v-if="current_chat.group_type=='group'" scrolldelay="200" class="profileLabel adminLabel" >{{current_chat.member_name}}</marquee></div></div>
                            <span class="css-17a79zy" @click="current_chat_dot=!current_chat_dot"><span data-testid="ddlChatThreeDotsButton"><svg class="unf-icon" viewBox="0 0 24 24" width="24" height="24" fill="var(--color-icon-enabled, #2E3137)" style="display: inline-block; vertical-align: middle;"><path fill-rule="evenodd" clip-rule="evenodd" d="M13.48 5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0Zm-1.5 8.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm0 7a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path></svg></span>
                                <div class="headerSettingMenu" :class="current_chat_dot?'active':''">
                                    <ul class="headerSettingMenuList">
                                        <li v-if="current_chat.group_type=='private'" @click="outConversations" class="headerSettingMenuItem"><span class="headerSettingMenuItemText"><span data-testid="btnChatOptionDelete">Hapus</span></span></li>
                                        <li v-if="current_chat.group_type=='group'" @click="outConversations" class="headerSettingMenuItem"><span class="headerSettingMenuItemText"><span data-testid="btnChatOptionDelete">Keluar</span></span></li>
                                    </ul>
                                </div>
                            </span>
                            <div class="css-1njd2sx" @click="pop=false" data-testid="btnChatCloseWidget"><svg class="unf-icon" viewBox="0 0 24 24" width="24" height="24" fill="var(--color-icon-enabled, #2E3137)" style="display: inline-block; vertical-align: middle;">
                                    <path d="M12 15.25a.74.74 0 0 1-.53-.22l-5-5A.75.75 0 0 1 7.53 9L12 13.44 16.47 9a.75.75 0 0 1 1.06 1l-5 5a.74.74 0 0 1-.53.25Z"></path>
                                </svg>
                            </div>
                        </div>
                        </template>
                        <template v-else>
                            <div class="css-n8c3k8" >
                                <div class="css-1njd2sx" @click="pop=false" data-testid="btnChatCloseWidget"><svg class="unf-icon" viewBox="0 0 24 24" width="24" height="24" fill="var(--color-icon-enabled, #2E3137)" style="display: inline-block; vertical-align: middle;">
                                        <path d="M12 15.25a.74.74 0 0 1-.53-.22l-5-5A.75.75 0 0 1 7.53 9L12 13.44 16.47 9a.75.75 0 0 1 1.06 1l-5 5a.74.74 0 0 1-.53.25Z"></path>
                                    </svg></div>
                            </div>
                        </template>
                        <div class="css-gur5g7">
                            <div v-if="createmode.state" class="css-1g7lik7">
                                <template v-if="user_selected.length>0">
                                    <input v-if="user_selected.length>1" v-model="createmode.group_name" class="my-2 form-input form-control" type="text" placeholder="Masukan nama grup">
                                    <button :disabled="user_selected.length>1&&createmode.group_name.length<1" @click="createConversation" class="btn btn-success">Mulai 
                                        <span v-if="createmode.loading" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                                        <i v-else class="fas fa-paper-plane"></i>
                                    </button>
                                </template>
                                <template v-else>
                                    <img :src="$store.state.config.base_url+'/assets/img/no-conversations.png'" alt="tidak ada percakapan" class="css-7wh13m w-50 mx-auto">
                                    <h1 class="css-vtask5">Mari memulai obrolan!</h1>
                                    <p class="css-lm81xx">Pilih pesan di samping untuk mulai chat dengan seseorang.</p>
                                </template>
                            </div>

                            <div v-else-if="current_chat" class="css-y3djy0">
                                <div class="css-g27kww" ref="messagesBox" @scroll="msgScrl">
                                    <div class="chatLoadMore" aria-label="load-more"></div>
                                    <div class="css-19idom">
                                            <template v-if="current_chat.ready">
                                                <div v-if="current_chat.conversations.length<1" class="css-1umja9p"><span class="my-5">Belum Ada Percakapan</span></div>
                                                <template v-for="(chat,ci) in current_chat.conversations.filter(v=>!v.deleting)">
                                                    
                                                    <template v-if="ci!=0">
                                                        <template v-if="chat.cam.format('YYYY-MM-DD')==mm().subtract(1,'d').format('YYYY-MM-DD')&&chat.cam.format('YYYY-MM-DD')!=current_chat.conversations[ci-1].cam.format('YYYY-MM-DD')">
                                                            <div class="css-1umja9p"><span>Kemarin</span></div>
                                                        </template>
                                                        <template v-else-if="chat.cam.format('YYYY-MM-DD')==mm().format('YYYY-MM-DD')&&chat.cam.format('YYYY-MM-DD')!=current_chat.conversations[ci-1].cam.format('YYYY-MM-DD')">
                                                            <div class="css-1umja9p"><span>Hari Ini</span></div>
                                                        </template>
                                                        <template v-else-if="chat.cam.format('YYYY-MM')!=current_chat.conversations[ci-1].cam.format('YYYY-MM')">
                                                            <div v-if="chat.cam.format('YYYY')==mm().format('YYYY')" class="css-1umja9p"><span>{{chat.cam.format('DD MMMM')}}</span></div>
                                                            <div v-else class="css-1umja9p"><span>{{chat.cam.format('DD MMMM YYYY')}}</span></div>
                                                        </template>
                                                    </template>
                                                    <template v-else>
                                                        <template v-if="chat.cam.format('YYYY-MM-DD')==mm().subtract(1,'d').format('YYYY-MM-DD')">
                                                            <div class="css-1umja9p"><span>Kemarin</span></div>
                                                        </template>
                                                        <template v-else-if="chat.cam.format('YYYY-MM')!=mm().format('YYYY-MM')">
                                                            <div v-if="chat.cam.format('YYYY')==mm().format('YYYY')" class="css-1umja9p"><span>{{chat.cam.format('DD MMMM')}}</span></div>
                                                            <div v-else class="css-1umja9p"><span>{{chat.cam.format('DD MMMM YYYY')}}</span></div>
                                                        </template>
                                                    </template>

                                                    <template v-if="chat.is_me">
                                                        <div class="css-1et5gtj" ref="chat.id" :id="chat.id">
                                                            <div aria-label="Chat Content" class="css-1gv96f6">
                                                                <div class="css-15vxjx" style="cursor:pointer" :class="chat.sending?'bg-warning':(chat.failed?'bg-danger':'')" @mousedown="!chat.sending?chatpress(chat.id):''" @mouseleave="!chat.sending?schatpress():''" @mouseup="!chat.sending?schatpress():''" @touchstart="!chat.sending?chatpress(chat.id):''" @touchend="!chat.sending?schatpress():''" @touchcancel="!chat.sending?schatpress():''">
                                                                    <div class="css-1fwt90x" v-html="chat.message"></div>
                                                                    <div class="css-1ugwlvx">
                                                                        <div class="css-18nf9ow">
                                                                            <div><svg v-if="!chat.sending&&!chat.failed" class="unf-icon" viewBox="0 0 24 24" width="16" height="16" fill="var(--GN500, #00AA5B)" style="display: inline-block; vertical-align: middle;"><path fill-rule="evenodd" clip-rule="evenodd" d="M7.713 15.694A.74.74 0 0 0 8 15.75a.74.74 0 0 0 .53-.22l6-6a.75.75 0 0 0-1.06-1.06L8 13.94l-2.47-2.47a.75.75 0 0 0-1.06 1.06l3 3a.74.74 0 0 0 .243.164Zm4.5 0a.74.74 0 0 0 .287.056.74.74 0 0 0 .5-.22l6-6a.75.75 0 0 0-1.03-1.06l-6 6a.75.75 0 0 0 .243 1.223Z"></path></svg></div>
                                                                            <span class="css-4wnuo">{{chat.cam.format('HH:mm')}}</span>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </template>
                                                    <template v-else>
                                                        <div class="css-f9a7ks" ref="chat.id" :id="chat.id">
                                                            <template v-if="current_chat.group_type=='group'">
                                                                <template v-if="ci==0">
                                                                    <div aria-label="Name" class="chat-name">{{chat.fullname}}{{chat.nomor_induk?' - '+chat.nomor_induk:''}}</div>
                                                                </template>
                                                                <template v-else>
                                                                <div v-if="current_chat.conversations[ci-1].user_id!=chat.user_id" aria-label="Name" class="chat-name">{{chat.fullname}}{{chat.nomor_induk?' - '+chat.nomor_induk:''}}</div>
                                                                </template>
                                                            </template>
                                                            <div aria-label="Chat Content" class="css-131k1b7">
                                                                <div class="css-beymw7">
                                                                    <div class="css-1fwt90x" v-html="chat.message"></div>
                                                                    <div class="css-1kw7fu3">
                                                                        <div class="css-18nf9ow"><span class="css-4wnuo">{{chat.cam.format('HH:mm')}}</span></div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </template>
                                                </template>
                                            </template>
                                            <template v-else>
                                                <div class="text-center my-5">
                                                    <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                                                </div>
                                            </template>

                                    </div>
                                    <div class="chatLoadMore"></div>
                                </div>
                                <div>
                                    <div class="css-1flhz5">
                                        <div class="css-1nylpq2">
                                            <div class="css-7g8pum">
                                                <div class="css-1hc581n" id="target-chat-reply">
                                                    <div class="css-1utqunl">
                                                        <div class="css-1g6c7h8" aria-label="Bubble Reply"></div>
                                                        <editor class="css-1qtfsal" v-model="message" :tinymceScriptSrc="$store.state.config.base_url+'/vendors/tinymce/js/tinymce/tinymce.min.js'" :init="tinymce"></editor>
                                                        <textarea v-if="false" class="css-1qtfsal" rows="1" placeholder="Tulis pesan..." data-testid="iptChatTextarea"></textarea>
                                                    </div>
                                                </div>
                                            </div><button :disabled="message.length<1" @click="sendMsg" type="button" class="css-1tlze9j"><svg class="unf-icon" viewBox="0 0 24 24" width="22" height="22" fill="var(--N0, #FFFFFF)" style="display: inline-block; vertical-align: middle;">
                                                    <path fill-rule="evenodd" clip-rule="evenodd" d="M21.35 11.32 5.66 3.19a1.81 1.81 0 0 0-1.81.28 1.8 1.8 0 0 0-.55 1.77L4.72 12 3.3 18.71a1.75 1.75 0 0 0 .7 1.81 1.68 1.68 0 0 0 1 .34c.266 0 .528-.069.76-.2l15.61-8a.759.759 0 0 0 .41-.67.77.77 0 0 0-.43-.67ZM5 19.34a.14.14 0 0 1-.15 0 .27.27 0 0 1-.1-.27L6 13.36l6.8-.87a.5.5 0 0 0 0-1L6 10.61 4.76 4.93a.33.33 0 0 1 .07-.32.32.32 0 0 1 .17-.06L19.36 12 5 19.34Z"></path>
                                                </svg></button>
                                        </div>
                                        <div class="css-dioskd"></div>
                                    </div>
                                </div>
                            </div>

                            <div v-else class="css-1g7lik7">
                                <img :src="$store.state.config.base_url+'/assets/img/no-conversations.png'" alt="tidak ada percakapan" class="css-7wh13m w-50 mx-auto">
                                <h1 class="css-vtask5">Mari memulai obrolan!</h1>
                                <p class="css-lm81xx">Pilih pesan di samping untuk mulai chat dengan seseorang.</p>
                            </div>
                            
                        </div>
                    </div><input type="file" accept="image/*" hidden="">
                </div>
            </div>
        </div>


        <div v-show="!pop" class="css-rggoxp" @click="pop=true">
            <div class="css-t6bv10">
                <div class="css-1j4q7i1-unf-tooltip" data-unify="Tooltip">
                    <div class="css-d5ck6m" data-testid="divGlobalActions-chat">
                        <div style="position: relative;"><svg class="unf-icon" viewBox="0 0 24 24" width="24" height="24" fill="var(--NN500, #8D96AA)" style="display: inline-block; vertical-align: middle;">
                                <path fill-rule="evenodd" clip-rule="evenodd" d="M3.66 21.67a.84.84 0 0 0 .34.08.74.74 0 0 0 .45-.15l3.8-2.85H17A3.71 3.71 0 0 0 20.75 15V7A3.71 3.71 0 0 0 17 3.25H7A3.71 3.71 0 0 0 3.25 7v14a.76.76 0 0 0 .41.67ZM6.13 4.907A2.2 2.2 0 0 1 7 4.75h10A2.2 2.2 0 0 1 19.25 7v8A2.2 2.2 0 0 1 17 17.25H8a.74.74 0 0 0-.45.15l-2.8 2.1V7a2.2 2.2 0 0 1 1.38-2.093ZM16 9.74H8a.75.75 0 0 1 0-1.5h8a.75.75 0 1 1 0 1.5Zm-3 4H8a.75.75 0 1 1 0-1.5h5a.75.75 0 1 1 0 1.5Z"></path>
                            </svg></div>
                        <p data-unify="Typography" color="var(--NN500, #8D96AA)" class="css-1qg82bs-unf-heading e1qvo2ff8">Chat</p>
                    </div>
                </div>
            </div>
        </div>

    </div>


    <div class="modal fade" id="modal-chathold" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-md modal-dialog-centered">
            <div class="modal-content card-style">
                <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.message,deleteConversation(chatholddata.id)" style="cursor:pointer" class="list-group-item">Ubah</li>
                        </ul>

                    </div>
                </div>
            </div>
        </div>
    </div>
    `;
    return {
        name: "chat-tp",
        template: vp_template,
        data() {
            return {
                tinymce: {
                    menubar: false,
                    images_upload_handler: this.images_upload_handler,
                    plugins: ['image', 'paste', 'autoresize'],
                    toolbar_location: 'bottom',
                    menubar: false,
                    toolbar: false,
                    inline: true,
                    setup: (editor) => {
                        editor.on('keydown', this.shortcut);
                    },
                    content_style: "p { margin: 0; }",
                },
                searchquery: '',
                pop: false,
                ready: false,
                loading: false,
                createmode: {
                    loading: false,
                    group_name: '',
                    state: false,
                    timeout: null,
                },
                current_chat_dot: false,
                filteropen: false,
                focussearch: false,
                message: '',
                chat_list: {
                    data: [],
                    current_chat: null,
                    loading: false,
                    ready: false,
                    lastFetch: 0,
                },
                users: {
                    data: [],
                    loading: false,
                    ready: false,
                    lastFetch: 0,
                },
                chathold: {
                    timeout: null,
                    modal: null,
                    id: null,
                },
            }
        },
        mounted() {
            this.notification = new Audio(this.$store.state.config.base_url + '/assets/audio/elearning/notification.mp3');
            this.loadConfig();
        },
        watch: {
            pop(v) {
                localStorage.setItem("chat-pop", v ? 1 : 0);
            },
        },
        methods: {
            loadConfig() {
                axios({
                    method: 'GET',
                    url: this.$store.state.config.base_url + "/panel/conversations/config",
                }).then((response) => {
                    if (!isObject(response.data)) return setTimeout(this.loadConfig, 2000);
                    if (parseInt(response.data.active) != 1) return;
                    this.ready = true;
                    this.pop = localStorage.getItem('chat-pop') == 1;
                    this.loadChatList();
                    setInterval(this.refreshChatList, 10000);
                    setInterval(this.autoLoadNewest, 3000);
                }, (error) => {
                    return setTimeout(this.loadConfig, 2000);
                });
            },
            chatpress(id) {
                if (this.chathold.timeout) clearTimeout(this.chathold.timeout);
                this.chathold.timeout = setTimeout(() => {
                    this.mdlchathold();
                    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();
                }
            },
            createMode() {
                this.createmode.state = !this.createmode.state;
                if (!this.users.ready) return this.loadUsers();
                if (this.users.lastFetch < mm().subtract(5, 'm').unix()) this.loadUsers();
            },
            createConversation() {
                if (this.createmode.loading) return;
                let data = { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value };
                let newUsers = this.users.data.filter(u => u.selected).map(u => u.id);
                if (newUsers.length < 1) return;
                data.users_id = newUsers;
                if (newUsers.length == 1) {
                    let chat = this.recentChatByUserId(newUsers[0]);
                    if (chat) {
                        this.createmode.state = false;
                        this.users.data.map(u => {
                            u.selected = false
                            return u;
                        });
                        this.chat_list.current_chat = chat.id;
                        if (chat.conversations.length < 1) this.initConversation();
                        return;
                    };
                    data.group_name = 'Private Chat';
                } else {
                    data.group_name = this.createmode.group_name;
                }
                this.createmode.loading = true;
                axios({
                    data,
                    method: 'POST',
                    url: this.$store.state.config.base_url + "/panel/conversations/create",
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.chat_list.current_chat = response.data.gc_id;
                    this.createmode.state = false;
                    this.createmode.group_name = '';
                    this.chat_list.data.push({
                        id: response.data.gc_id,
                        group_name: response.data.group_name,
                        conversations: [],
                        ready: true,
                    })
                    return this.refreshChatList(true);
                }, (error) => {
                }).finally(() => this.createmode.loading = false);
            },
            recentChatByUserId(uid) {
                return this.chat_list.data.find(c => c.user_id == uid && c.group_type == 'private');
            },
            getChatByGCId(gcid) {
                return this.chat_list.data.find(c => c.id == gcid);
            },
            resend(id) {
                if (!this.current_chat) return;
                let msg = this.current_chat.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: msg.message, [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value },
                    url: this.$store.state.config.base_url + `/panel/conversations/add/${btoa(msg.gc_id)}`,
                }).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(),
                    gc_id: this.chat_list.current_chat,
                    user_id: this.$store.state.config.person.id,
                    fullname: this.$store.state.config.person.name,
                    is_me: 1,
                    sending: true,
                    failed: false,
                    message: 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.current_chat.conversations.push(msg);
                this.message = '';
                setTimeout(() => {
                    let el = document.getElementById(msg.id);
                    if (!el) return;
                    el.scrollIntoView({ block: "nearest", inline: "nearest" })
                }, 50)
                axios({
                    method: 'put',
                    data: { msg: msg.message, [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value },
                    url: this.$store.state.config.base_url + `/panel/conversations/add/${btoa(msg.gc_id)}`,
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    let m = this.getChatByGCId(msg.gc_id).conversations.find(v => v.id == msg.id);
                    m.id = response.data.id;
                    m.sending = false;
                    m.failed = false;
                    this.refreshChatList(true)
                }, (error) => {
                    let m = this.getChatByGCId(msg.gc_id).conversations.find(v => v.id == msg.id);
                    m.sending = false;
                    m.failed = true;
                });
            },
            refreshUser(newest = true) {
                if (newest) return this.loadUsers();
                if (!this.users.ready) return this.loadUsers();
                if (this.users.lastFetch > mm().subtract(15, 's').unix()) this.loadUsers();
            },
            refreshChatList(newest = true) {
                if (newest) return this.loadChatList();
                if (!this.chat_list.ready) return this.loadChatList();
                if (this.chat_list.lastFetch > mm().subtract(15, 's').unix()) this.loadChatList();
            },
            msgScrl(e) {
                if (!this.current_chat) return;
                if (this.$refs.messagesBox.scrollTop <= 60 && this.current_chat.lastFetch < mm().unix()) {
                    if (this.current_chat.conversations.length <= 0) return this.initConversation();
                    return this.loadOldConversations();
                }
                if (this.$refs.messagesBox.scrollHeight - this.$refs.messagesBox.scrollTop === this.$refs.messagesBox.clientHeight) {
                    if (this.current_chat.conversations.length <= 0) return this.initConversation();
                    return this.loadNewConversations();
                }
            },
            outConversations() {
                let gc_id = this.current_chat.id;
                SwalDelete({
                    params: {
                        title: 'Keluar Percakapan',
                        text: 'Ini akan menghapus percakapan, apakah anda yakin?',
                        type: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#3085d6',
                        cancelButtonColor: '#d33',
                        confirmButtonText: 'Ya, Keluar!'
                    },
                    confirmed: () => {
                        this.current_chat.ready = false;
                        axios({
                            method: 'delete',
                            data: { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value, },
                            url: this.$store.state.config.base_url + `/panel/conversations/out/${btoa(gc_id)}`,
                        }).then((response) => {
                            let si = this.chat_list.data.findIndex(v => v.id == gc_id);
                            if (si == -1) return;
                            this.chat_list.data.splice(si, 1);
                        }, (error) => {
                            Swal.fire('Gagal', gaem(error, 'Silahkan Coba Lagi'), 'error');
                            let si = this.chat_list.data.findIndex(v => v.id == gc_id);
                            if (si == -1) return;
                            si.ready = false;
                        });
                    }
                });
            },
            initConversation() {
                if (this.loading) return;
                this.loading = true;
                this.lastFetch = mm().unix();
                let gc_id = this.chat_list.current_chat;
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + "/panel/conversations/init/" + btoa(gc_id),
                }).then((response) => {
                    if (!isObject(response.data)) return setTimeout(this.initConversation, 1000);
                    let old = this.chat_list.data.find(c => c.id == gc_id);
                    old.ready = true;
                    old.conversations = response.data.conversations.map(v => {
                        v.sending = false;
                        v.failed = false;
                        v.is_me = parseInt(v.is_me);
                        v.cam = mm({ unix: v.created_at });
                        return v;
                    });
                    setTimeout(() => {
                        this.toLastMsg()
                    }, 100)
                }, (error) => {
                    setTimeout(this.initConversation, 1000);
                }).finally(() => this.loading = false);
            },
            toLastMsg() {
                if (!this.current_chat) return;
                try {
                    if (this.current_chat.conversations.length < 1) return;
                    let el = document.getElementById(this.current_chat.conversations[this.current_chat.conversations.length - 1].id);
                    if (!el) return;
                    el.scrollIntoView({ block: "nearest", inline: "nearest" });
                } catch (error) {
                    console.log(error)

                }
            },
            autoLoadNewest() {
                if (!this.current_chat) return;
                if (!this.current_chat.lastFetch) this.current_chat.lastFetch = mm().unix();
                if (this.current_chat.lastFetch > mm().subtract(5, 's').unix()) return;
                if (this.current_chat.conversations.length <= 0) return this.initConversation();
                this.loadNewConversations();
            },
            loadNewConversations() {
                if (this.loading || !this.current_chat) return;
                this.loading = true;
                let c = this.current_chat.conversations.filter(v => !v.sending && !v.failed);
                let gc_id = this.current_chat.id;
                let lid = c[c.length - 1].id;
                this.current_chat.lastFetch = mm().unix();
                axios({
                    method: 'get',
                    url: `${this.$store.state.config.base_url}/panel/conversations/newest/${btoa(gc_id)}/${btoa(lid)}`,
                }).then((response) => {
                    if (!isObject(response.data)) return setTimeout(this.loadNewConversations, 1000);
                    let chat = this.chat_list.data.find(v => v.id == gc_id);
                    response.data.conversations = response.data.conversations.filter(v => chat.conversations.findIndex(sv => sv.id == v.id) == -1).map(v => {
                        v.sending = false;
                        v.failed = false;
                        v.is_me = parseInt(v.is_me);
                        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);
                    }
                    chat.conversations = [...chat.conversations, ...response.data.conversations];
                    if (response.data.conversations.length > 0) {
                        this.notification.play();
                    }
                    this.chat_list.data = this.chat_list.data.map(cl => {
                        let n = response.data.conversations.find(v => v.gc_id == cl.id);
                        if (n) {
                            cl.message = n.message;
                            cl.updated_at = n.updated_at;
                        }
                        return cl;
                    })
                }, (error) => {
                    setTimeout(this.loadNewConversations, 1000);
                }).finally(() => this.loading = false);
            },
            loadOldConversations() {
                if (this.loading || !this.current_chat) return;
                this.loading = true;
                let c = this.current_chat.conversations.filter(v => !v.sending && !v.failed);
                let gc_id = this.current_chat.id;
                let fid = c[0].id;
                this.current_chat.lastFetch = mm().unix();
                axios({
                    method: 'get',
                    url: `${this.$store.state.config.base_url}/panel/conversations/oldest/${btoa(gc_id)}/${btoa(fid)}`,
                }).then((response) => {
                    if (!isObject(response.data)) return setTimeout(this.loadOldConversations, 1000);
                    let chat = this.chat_list.data.find(v => v.id == gc_id);
                    response.data.conversations = response.data.conversations.filter(v => chat.conversations.findIndex(sv => sv.id == v.id) == -1).map(v => {
                        v.sending = false;
                        v.failed = false;
                        v.is_me = parseInt(v.is_me);
                        v.cam = mm({ unix: v.created_at });
                        return v;
                    }).reverse();
                    chat.conversations = [...response.data.conversations, ...chat.conversations];
                    let fid2 = chat.conversations[response.data.conversations.length];
                    if (response.data.conversations.length > 0 && fid2) {
                        this.current_chat.lastFetch = mm().unix();
                        setTimeout(() => {
                            try {
                                let el = document.getElementById(fid2.id);
                                if (!el) return;
                                el.scrollIntoView({ block: "nearest", inline: "nearest" })
                            } catch (error) {
                            }
                        }, 100);
                    }
                }, (error) => {
                    setTimeout(this.loadOldConversations, 1000);
                }).finally(() => this.loading = false);
            },
            loadChatList() {
                if (this.chat_list.loading) return;
                this.chat_list.loading = true;
                let lcl = null;
                if (this.chat_list.data.length > 0) lcl = this.chat_list_sorted[0];
                axios({
                    method: 'GET',
                    url: this.$store.state.config.base_url + `/panel/conversations/chat-list`,
                }).then((response) => {
                    if (!isObject(response.data)) return setTimeout(this.loadChatList, 1000);
                    this.chat_list.data = response.data.conversations.map(v => {
                        let old = this.chat_list.data.find(c => c.id == v.id);
                        v.ready = old ? old.ready : false;
                        v.conversations = old ? old.conversations : [];
                        v.cam = mm({ unix: v.created_at });
                        v.uam = mm({ unix: v.updated_at });
                        return v;
                    });
                    this.chat_list.ready = true
                    this.chat_list.lastFetch = mm().unix();
                    if (this.chat_list.data.length < 1) return;
                    if (!lcl) return;
                    let clcl = this.chat_list_sorted[0];
                    if (parseInt(clcl.updated_at) <= parseInt(lcl.updated_at) || ((clcl.id == lcl.id && clcl.message == lcl.message) || this.chat_list.current_chat == clcl.id)) return;
                    this.notification.play();

                }, (error) => {

                }).finally(() => this.chat_list.loading = false);
            },
            loadUsers() {
                if (this.users.loading) return;
                this.users.loading = true;
                axios({
                    method: 'GET',
                    url: this.$store.state.config.base_url + `/panel/conversations/users`,
                }).then((response) => {
                    if (!isObject(response.data)) return setTimeout(this.loadUsers, 1000);
                    this.users.data = response.data.users.map(v => {
                        v.roles = v.role.split(',');
                        v.selected = false;
                        return v;
                    });
                    this.users.ready = true
                    this.users.lastFetch = mm().unix();
                }, (error) => {

                }).finally(() => this.users.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/conversations/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);
            },
            deleteConversation(id) {
                if (!this.current_chat) return;
                let chat = this.current_chat.conversations.find(v => v.id == id);
                if (!chat) return;
                if (chat.failed) return this.current_chat.conversations.splice(this.current_chat.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: this.$store.state.config.base_url + "/panel/conversations/delete/" + btoa(chat.gc_id) + "/" + btoa(chat.id),
                        }).then((response) => {
                            let si = this.chat_list.data.find(v => v.id == chat.gc_id);
                            if (si == -1) return;
                            let c = si.conversations.findIndex(v => v.id == chat.id);
                            if (c == -1) return;
                            si.conversations.splice(c, 1);
                        }, (error) => {
                            chat.deleting = false;
                            Swal.fire('Gagal', gaem(error, 'Silahkan Coba Lagi'), 'error');
                        });
                    }
                });
            },
            mdlchathold() {
                if (!this.chathold.modal) this.chathold.modal = new bootstrap.Modal(document.getElementById('modal-chathold'));
                this.chathold.modal.show();
            },
            mm() {
                return mm();
            },
        },
        computed: {
            chat_list_filtered() {
                return this.chat_list.data.filter(v => {
                    if (this.searchquery.length < 1) return true;
                    return v.group_name.toLowerCase().includes(this.searchquery.toLowerCase());
                }).sort((a, b) => b.updated_at - a.updated_at);
            },
            chat_list_sorted() {
                return this.chat_list.data.sort((a, b) => b.updated_at - a.updated_at);
            },
            users_filtered() {
                return this.users.data.filter(v => {
                    if (this.searchquery.length < 1) return true;
                    return v.fullname.toLowerCase().includes(this.searchquery.toLowerCase());
                });
            },
            cmselectmode() {
                return this.users.data.filter(v => v.selected).length > 0;
            },
            user_selected() {
                return this.users.data.filter(v => v.selected);
            },
            current_chat() {
                return this.chat_list.data.find(c => c.id == this.chat_list.current_chat);
            },
            chatholddata() {
                if (!this.current_chat) return null;
                return this.current_chat.conversations.find(v => v.id == this.chathold.id)
            }
        },
    }
})();
