import {global} from "http://talk.kospo.co.kr:3000/static/js/module/variable.js";
import {infoMessage, systemMessage, talkMapping, messageMapping} from "http://talk.kospo.co.kr:3000/static/js/module/render.js";
import {getMessage, getTalkListEvent, setChatList, setChatRead} from "http://talk.kospo.co.kr:3000/static/js/module/apis.js";
import {showNotification} from 'http://talk.kospo.co.kr:3000/static/js/notification.js';
import {talkEvent} from "http://talk.kospo.co.kr:3000/static/js/module/talkEvent.js";
import Common from "http://talk.kospo.co.kr:3000/static/js/utils.js";
import {HubEvent} from "http://talk.kospo.co.kr:3000/static/js/module/hubEvent.js"

// 소켓 메시지 이벤트

const receiver = {
    workOnline: (payload) => {
        const introOnline = global.shadowRoot.querySelector('#intro-online');
        introOnline.classList.remove('offline');
        introOnline.classList.add('online');
    },
    workOffline: (payload) => {
        const introOnline = global.shadowRoot.querySelector('#intro-online');
        introOnline.classList.remove('online');
        introOnline.classList.add('offline');
    },
    online: (payload) => {
        const onlineList = [];
        if (payload.works.length === 0) {
            const chatList = global.shadowRoot.querySelectorAll(`div[data-target-sabun="${payload.sabun}"]`)

            chatList.forEach((el) => {
                onlineList.push(el.dataset.talkId);
                const offline = el.querySelector('.status-offline')
                if (offline) {
                    offline.classList.remove('status-offline')
                    offline.classList.add('status-online')
                }
            })
        } else {
            const chatList = global.shadowRoot.querySelectorAll('.chat-wrap');
            chatList.forEach((el) => {
                // const targetSabun = el.getAttribute('data-target-sabun');
                const smSabun = el.getAttribute('data-work-sm-sabun');
                if (smSabun.includes(payload.sabun)) {
                    onlineList.push(el.dataset.talkId);
                    const offline = el.querySelector('.status-offline')

                    if (offline) {
                        offline.classList.remove('status-offline')
                        offline.classList.add('status-online')
                    }
                }

            })

        }

        global.talkData.forEach((talk) => {
            if (onlineList.includes(talk.talkId)) {
                talk.talkMembers.forEach((tm) => {
                    if (tm.sabun === payload.sabun) {
                        tm.onlineYn = true;
                    }
                })
            }
        })
    },
    offline: (payload) => {
        const offlineList = [];
        let onlineYn = false;
        if (payload.works.length === 0) {
            const chatList = global.shadowRoot.querySelectorAll(`div[data-target-sabun="${payload.sabun}"]`)
            chatList.forEach((el) => {
                offlineList.push(el.dataset.talkId);
                const offline = el.querySelector('.status-online')
                if (offline) {
                    offline.classList.remove('status-online')
                    offline.classList.add('status-offline')
                }
            })
        } else {
            let oldtalkId = "";
            const chatList = payload.talks.filter((ch) => {
                if (ch.sabun !== global.user.sabun && ch.onlineYn) oldtalkId = ch.talkId;
                if (ch.sabun !== global.user.sabun) return ch;
            })

            chatList.forEach((cl) => {
                if (oldtalkId !== cl.talkId) {
                    const chatEl = global.shadowRoot.querySelector(`div[data-talk-id="${cl.talkId}"]`);
                    if (chatEl) {
                        const online = chatEl.querySelector('.status-online')
                        if (online) {
                            online.classList.remove('status-online')
                            online.classList.add('status-offline')
                        }
                        const smSabun = chatEl.getAttribute('data-work-sm-sabun');
                        if (smSabun.includes(payload.sabun)) {
                            offlineList.push(chatEl.dataset.talkId);
                        }
                    }

                }

            })
        }
        global.talkData.forEach((talk) => {
            if (offlineList.includes(talk.talkId)) {
                talk.talkMembers.forEach((tm) => {
                    if (tm.sabun === payload.sabun) {
                        tm.onlineYn = false;
                    }
                })
            }
        })
    },
    error: (payload) => {
        global.notifier.alert(payload.message)
    },
    join: (payload) => {
        setChatList(payload)
        if(localStorage.getItem(global.tab) === '' || localStorage.getItem(global.tab) === null ) {
            if (!(payload.work.smUsers.map((sm) => sm.sabun).toString().indexOf(global.user.sabun) > -1)) {
                // 방 생성자 주입
                if (payload.tabId === global.tabId) {
                    /* 방 생성자 초기화 */
                    console.log("*(*******************A")
                    global.chatCreator = null;
                    talkEvent.messageShow();
                    localStorage.setItem(global.tabId, payload.talkId)
                    talkEvent.talkHeaderChange(payload.work.workNm, payload.work.smUsers.map((sm) => sm.name).join(','));

                }

            }
        }

    },
    change: (payload) => {
        setChatList(payload)
        const cacheTalk = global.talkData.filter((talk) => talk.talkId === payload.talkId)[0];
        cacheTalk.messageParams = {};
        cacheTalk.messageParams.talkId = payload.talkId;
        cacheTalk.messageParams.start = 0;
        cacheTalk.messageParams.row = 30;
        cacheTalk.lastMessage = payload.lastMessage;
        cacheTalk.lastMessageDate = payload.lastMessageDate;
        cacheTalk.talkMessages = payload.talkMessages;
        cacheTalk.talkMembers = payload.talkMembers
        console.log('user change', cacheTalk)


        if (!(payload.work.smUsers.map((sm) => sm.sabun).includes(global.user.sabun))) {
            // 방 생성자 주입
            if (payload.insSabun === global.user.sabun) {

                const _this = global.shadowRoot.querySelector(`div[data-talk-id="${payload.talkId}"]`)
                const talkId = _this.dataset.talkId;
                const workId = _this.dataset.workId;
                const workNm = _this.dataset.workNm;
                const workSmNm = _this.dataset.workSmNm;

                const currentTalkId = localStorage.getItem(global.tabId)
                if (currentTalkId === payload.prevTalkId) {

                    talkEvent.talkHeaderChange(workNm, workSmNm)

                    global.talkClean();
                    global.scrollMoreFlag = false;
                    localStorage.setItem(global.tabId, talkId);
                    localStorage.setItem('workId', workId);
                    localStorage.setItem('workNm', workNm);
                }

                talkMapping(global.talkData)
            }
        }

    },
    start: (payload) => {
        if(localStorage.getItem(global.tabId) === payload.talkId) {
            if (global.user.sabun !== payload.insSabun) {
                const cacheTalk = global.talkData.filter((talk) => talk.talkId === payload.talkId)[0];
                cacheTalk.talkMembers = cacheTalk.talkMembers.filter((member) => (member.sabun === 'info' || member.sabun === global.user.sabun || member.sabun === payload.insSabun) )
                // 앤드 유저 이벤트 설정
                const room = global.shadowRoot.querySelector(`div[data-talk-id="${payload.talkId}"]`);
                room.dataset.workSmNm = payload.insName
                room.dataset.workSmSabun = payload.insSabun
                talkEvent.talkTitleChange(payload.talkId, payload.insSabun)
                talkEvent.talkHeaderChange(null, payload.insName)

            } else {
                // 유지보수 담당자 이벤트 설정
                const room = global.shadowRoot.querySelector(`div[data-talk-id="${payload.talkId}"]`);
                room.setAttribute("data-work-sm-nm", payload.insName)
                room.setAttribute("data-work-sm-sabun", payload.insSabun)
                talkEvent.talkHeaderChange(null, payload.insName)
            }
        }


    },
    leave: (payload) => {
        /*구독 취소*/
        talkEvent.talkRemove(payload.talkId);
        if (Common.isMaster()) {
            console.log('unsubscribe')
            talkEvent.unsubscribe(payload.talkId);
        }

        if(localStorage.getItem(global.tabId) === payload.talkId) {
            talkEvent.talkHeaderChange('', '')
            global.reset()
        }

    },
    delete: (payload) => {
        /*구독 취소*/
        talkEvent.talkRemove(payload.talkId);
        if (Common.isMaster()) {
            console.log('unsubscribe')
            talkEvent.unsubscribe(payload.talkId);
        }
    },
    close: (payload) => {
        if (Common.isMaster()) {
            talkEvent.unsubscribe(payload.talkId);
        }
        if (localStorage.getItem(global.tabId) === payload.talkId && !payload.force) {
            global.element.chatEditorArea.classList.add('cus-hide');
            const chatRatingConfirmWrapper = global.shadowRoot.querySelector('.chat-rating-confirm-wrapper')
            chatRatingConfirmWrapper.classList.remove('cus-hide')
            chatRatingConfirmWrapper.classList.add('cus-show')
        }

        const room = global.shadowRoot.querySelector(`div[data-talk-id="${payload.talkId}"]`);

        /*상담 강제 종료시 만족사 조사 제외 완료 처리*/
        if(payload.force) {
            room.dataset.compYn = true;
            room.dataset.ratingYn = true;
        }


        room.classList.add('chat-close');
        const avatar = room.querySelector('.avatar')
        avatar.classList.remove('status-online')
        avatar.classList.remove('status-offline')
        avatar.classList.add('status-do-not-disturb')

        const roomData = global.talkData.filter((talk) => talk.talkId === payload.talkId)[0];
        roomData.closeYn = true;
        talkMapping(global.talkData)
        if(localStorage.getItem(global.tabId) === payload.talkId) {
            global.element.chatEditorArea.classList.add('cus-hide');
        }

    },
    intro: (payload) => {
        if(localStorage.getItem(global.tabId) === payload.talkId) {
            infoMessage(payload.message)
            talkEvent.messageShow()
        }
    },
    message: async (payload) => {

        //기초 데이터 초기화
        global.yourOldDate = '';
        global.mineOldDate = '';
        global.currDay = '';
        let incrementIdxFlag = true;
        let listening = 1;
        // Common.setListening(1);
        const master = Common.isMaster();

        /*현재 톡방이 첨부파일 메시지 와 동일한 방이면 메시지 맵핑*/
        if(master) {

            if ((localStorage.getItem(global.tabId) === payload.talkId && document.visibilityState === 'hidden') || (localStorage.getItem(global.tabId) === payload.talkId && global.shadowRoot.querySelector('.chat-floating').classList.contains('cus-hide'))) {
                listening = 3
            } else if (localStorage.getItem(global.tabId) === payload.talkId) {
                listening = 2
            }

            // 우선순위가 되는 상태 간격 조절
            // Common.setListening(payload.talkId, listening);
        } else {
            listening = 99
            // await Common.sleep(400)
        }


        /*메시지 호출이 안된 상태이면 제외 첫 접근도 안된 상태로 메시지 맵핑 필요없음*/
        const cacheTalk = global.talkData.filter((talk) => talk.talkId === payload.talkId)[0];
        /* 메시지 존재 여부에 따른 분기 처리 */
        try {
            if (cacheTalk.talkMessages !== undefined) {
                messageMapping(payload.talkId, {talks: [payload]}, 'after', false)
            } else {
                messageMapping(payload.talkId, {talks: [payload]}, 'after', true)
            }
        } catch(e) {
            global.notifier.alert('통신 오류가 발생 했어요.<br/>새로고침 해주세요.')
            return;
        }

        /*
        톡방에 입장중이면 썸네일 메시지 전송
        입장중이 아니면 톡방 목록에 배지 카운트 추가및 메시지 메시지 변경
        *  */

        const msg = payload.message.includes('[매뉴얼]') ? '[매뉴얼]' : payload.message
        // await Common.sleep(200)
        // listening = Common.getListening(payload.talkId);
        if (listening === 1) {
            if(master) {
                if (payload.type !== 'QUESTION') {
                    showNotification({
                        workNm: payload.workNm,
                        talkId: payload.talkId,
                        message: msg,
                        insName: payload.insName,
                    });
                }
            }
        } else if(listening === 2 || listening === 3) {
            // 메인탭만 작동하도록 조치
            // 현재 톡방 에 입장중이며 해당 탭이 비활성화 인상태 일시 쿠키값 변경

            // if (localStorage.getItem(global.tabId) === payload.talkId && !document.hasFocus()) {
            //     Common.setListening(payload.talkId, 1);
            // }

            if (master) {
                talkEvent.readMessage(payload.talkId)
            }

            if (payload.insSabun !== global.user.sabun) {
                if (master) {
                    setChatRead(payload.talkId)
                }
                // 기타 톡방으로 메시지 읽음 전송
                console.log('read')
                HubEvent.send(global.talkParams({
                    type: "READ",
                    talkId: payload.talkId,
                    insSabun: global.user.sabun
                }))

            }

            // 스크롤 옵저버가 꺼져 있을시 메시지 팝업으로 활성화
            if (!global.scrollObserveFlag && payload.talkId === localStorage.getItem(global.tabId) && payload.insSabun !== global.user.sabun) {
                talkEvent.preMessageShow(msg)
            }
            if (listening === 3) {
                if (master) {
                    if (payload.type !== 'QUESTION') {
                        showNotification({
                            workNm: payload.workNm,
                            talkId: payload.talkId,
                            message: msg ,
                            insName: payload.insName,
                        });
                    }
                }
            }

            incrementIdxFlag = false;
        } else {
            incrementIdxFlag = false;
        }


        // 톡방 데이터 주입
        global.talkData.forEach((talk, idx) => {
            if (talk.talkId === payload.talkId) {
                talk.unReadCnt = incrementIdxFlag ? talk.unReadCnt + 1 : 0;
                if (payload.type !== 'QUESTION') {
                    talk.lastMessage = msg;
                    talk.lastMessageDate = payload.insDate;
                }
            }
        })

        // 톡방 재정의
        talkMapping(global.talkData)

        // 메인 배지 재정의
        if (payload.type !== 'QUESTION') {
            talkEvent.badgeChange()
        }
    },
    infoMessage: (payload) => {
        console.log('infoMessage')
        if(localStorage.getItem(global.tabId) === payload.talkId) {
            if (payload.insSabun === global.user.sabun) {
                systemMessage(payload.message);
                // showNotification(payload.workNm, payload.talkId, message)
            }
        }

    },
    externalSave: (payload) => {
        const cacheTalk = global.talkData.filter((talk) => talk.talkId === payload.talkId)[0];
        cacheTalk.reqId = payload.reqId;
    },
    typed: (payload) => {
        const currentTalkId = localStorage.getItem(global.tabId)
        if (currentTalkId === payload.talkId) {
            if (payload.insSabun !== global.user.sabun) {
                talkEvent.messageTyped(payload);
            }
        }
    },
    untyped: (payload) => {
        const currentTalkId = localStorage.getItem(global.tabId)
        if (currentTalkId === payload.talkId) {
            if (payload.insSabun !== global.user.sabun) {
                talkEvent.messageUnTyped(payload);
            }
        }
    },
    read: (payload) => {
        if (payload.insSabun === global.user.sabun) {
            talkEvent.readMessage(payload.talkId)
        }
    },
    attachStart: async (payload) => {
        // 마스터 와 그외 탭간의 간격 조절
        // 파일소켓 구독
        payload.talkAttachDtos.forEach((att) => {
            att.uploading = payload.uploading;
        })
        talkEvent.fileSubscribe(payload);
        await Common.sleep(200)
        global.yourOldDate = '';
        global.mineOldDate = '';
        global.currDay = '';
        let incrementIdxFlag = true;
        let listening = 1;
        let sleepSecond = 10
        const master = Common.isMaster();

        /*현재 톡방이 첨부파일 메시지 와 동일한 방이면 메시지 맵핑*/
        if(master) {
            if ((localStorage.getItem(global.tabId) === payload.talkId && document.visibilityState === 'hidden') || (localStorage.getItem(global.tabId) === payload.talkId && global.shadowRoot.querySelector('.chat-floating').classList.contains('cus-hide'))) {
                listening = 3
            } else if (localStorage.getItem(global.tabId) === payload.talkId) {
                listening = 2
            }

            // 우선순위가 되는 상태 간격 조절
            Common.setListening(payload.talkId, listening);
        } else {
            await Common.sleep(100)
        }

        /*메시지 호출이 안된 상태이면 제외 첫 접근도 안된 상태로 메시지 맵핑 필요없음*/
        const cacheTalk = global.talkData.filter((talk) => talk.talkId === payload.talkId)[0];
        if (cacheTalk.talkMessages !== undefined) {
            messageMapping(payload.talkId, {talks: [payload]}, 'after', false)
            // if (localStorage.getItem(global.tabId) === payload.talkId) {
            //     const uploadWrap = global.shadowRoot.querySelector(`div[data-key="${payload.attach.key}"]`);
            //     const messageWrap = uploadWrap.querySelector('.chat-message');
            //     messageWrap.style.whiteSpace = 'nowrap';
            //
            //     /* 다운로드 시작시 배경 페이드 활성화 */
            //     const imageFade = uploadWrap.querySelector('.file-fade')
            //     imageFade.classList.remove('cus-hide');
            //     /*다운로드 버튼 비활성화*/
            //     const downloadBtn = uploadWrap.querySelector('.chat-gallery-option')
            //     downloadBtn.classList.remove('cus-show')
            //     downloadBtn.classList.add('cus-hide')
            //     const chatFile = uploadWrap.querySelector('.chat-file')
            //     if (chatFile) {
            //         /*프로그레스 설정*/
            //         chatFile.insertAdjacentHTML('beforeend', `<div class="progress" style="margin-top:5px; margin-bottom:5px;">
            //                     <div class="progress-bar bg-low-purple" role="progressbar" style="width:0%;" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100">0%</div>
            //                 </div>
            //                 `)
            //     } else {
            //         messageWrap.insertAdjacentHTML('beforeend', `<div class="progress" style="margin-top:5px; margin-bottom:5px;">
            //                     <div class="progress-bar bg-low-purple" role="progressbar" style="width:0%;" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100">0%</div>
            //                 </div>
            //                 `)
            //     }
            // }
        }


        /*
        톡방에 입장중이면 썸네일 메시지 전송
        입장중이 아니면 톡방 목록에 배지 카운트 추가및 메시지 메시지 변경
        *  */
        listening = Common.getListening(payload.talkId);
        if (listening === 1 || global.shadowRoot.querySelector('.chat-floating').classList.contains('cus-hide')) {
            if (master) {
                showNotification({
                    workNm: payload.workNm,
                    talkId: payload.talkId,
                    message: payload.message,
                    insName: payload.insName,
                });
            }
            // if (global.user.sabun !== payload.insSabun) {
            //     const chatBadge = global.shadowRoot.querySelector('.unread.badge');
            //     // let badgeCount = chatBadge.innerText;
            //     // badgeCnt = parseInt(badgeCount) + 1;
            // }
        } else {
            // 메인탭에서만 작동 하도록 조치
            if (master) {
                talkEvent.readMessage(payload.talkId)
            }

            // 기타 탭으로 메시지 읽음 전송
            if (payload.insSabun !== global.user.sabun) {
                if (master) {
                    setChatRead(payload.talkId)
                }
                HubEvent.send(global.talkParams({
                    type: "READ",
                    talkId: payload.talkId,
                    insSabun: global.user.sabun
                }))
            }

            if (master && !document.hasFocus()) {
                showNotification({
                    workNm: payload.workNm,
                    talkId: payload.talkId,
                    message: payload.message,
                    insName: payload.insName,
                });
            }

            // 스크롤 옵저버가 꺼져 있을시 메시지 팝업으로 활성화
            if (!global.scrollObserveFlag && payload.talkId === localStorage.getItem(global.tabId) && payload.insSabun !== global.user.sabun) {
                talkEvent.preMessageShow(payload.message)
            }

            incrementIdxFlag = false;
        }


        // 톡방 정보에 정보 주입
        global.talkData.forEach((talk, idx) => {
            if (talk.talkId === payload.talkId) {
                talk.unReadCnt = incrementIdxFlag ? talk.unReadCnt + 1 : 0;
                talk.lastMessage = payload.message;
                talk.lastMessageDate = payload.insDate;
                global.talkData.splice(idx, 1)
                global.talkData = [talk, ...global.talkData]
            }
        })

        // 톡방 재정의
        talkMapping(global.talkData)

        // 메인 배지 재정의
        talkEvent.badgeChange()
    },
    attachProgress: (payload) => {
        if (localStorage.getItem(global.tabId) === payload.talkId) {
            const uploadWrap = global.shadowRoot.querySelector(`div[data-ins-date="${payload.insDate}"]`);
            const progressBar = uploadWrap.querySelector('.progress-bar')
            if (progressBar) {
                if(Number(progressBar.style.width.replace('%', '')) < Number(payload.attach.percent.replace('%', ''))) {
                    progressBar.style.width = payload.attach.percent;
                    progressBar.innerText = payload.attach.percent;
                }
            }
        }

    },
    attachEnd: (payload) => {
        /*파일 구독 삭제*/
        if (Common.isMaster()) {
            console.log('attachEnd : ' + JSON.stringify(global.fileSubscribeList[payload.talkId]))
            global.fileSubscribeList[payload.talkId].unsubscribe()
            delete global.fileSubscribeList[payload.talkId];
        }


        const cacheTalk = global.talkData.filter((talk) => talk.talkId === payload.talkId)[0];
        if (cacheTalk.talkMessages !== undefined) {

            cacheTalk.talkMessages.talks.forEach((talks) => {
                if(talks.insDate === payload.insDate) {
                    talks.talkAttachDtos.forEach((att) => {
                        att.uploading = false;
                    })
                }
            })
        }

        console.log(cacheTalk)
        if (localStorage.getItem(global.tabId) === payload.talkId) {
            messageMapping(payload.talkId, cacheTalk.talkMessages, 'before', true)
        }
    },
    otherInit: (payload) => {
        global.talkData = payload.talkData
        console.log(global)
        getTalkListEvent();
    },
    messageLine: (payload) => {
        const cacheTalk = global.talkData.filter((talk) => talk.talkId === payload.talkId)[0];
        cacheTalk.talkMessages = JSON.parse(payload.talkMessages);
        cacheTalk.messageParams = JSON.parse(payload.messageParams)
        console.log(`receiver MESSAGE_LINE : `, cacheTalk)
        if (localStorage.getItem(global.tabId) === payload.talkId) {
            console.log('messageMapping')
            messageMapping(payload.talkId, cacheTalk.talkMessages, 'before', true)
            if (cacheTalk.talkMessages.length !== cacheTalk.talkMessages.total) {
                setTimeout(() => {
                    global.scrollMoreFlag = true;
                }, 1000)
            }
        }

    },
    moreMessageLine: (payload) => {
        const cacheTalk = global.talkData.filter((talk) => talk.talkId === payload.talkId)[0];
        cacheTalk.talkMessages.talks = [...payload.talkMessages.talks, ...cacheTalk.talkMessages.talks];
        console.log(`receiver MORE_MESSAGE_LINE : `, cacheTalk)
        if (localStorage.getItem(global.tabId) === payload.talkId) {
            console.log('messageMapping', global.oldScrollPosition)
            messageMapping(payload.talkId, cacheTalk.talkMessages, 'before', true)
            talkEvent.messageScrollOriginalPositionMove();

            if (payload.result === 'success') {
                global.scrollMoreFlag = true;
            } else if (payload.result === 'last') {
                global.scrollMoreFlag = false;
            }
        }
    },
    talkRefresh: (payload) => {
        global.talkData = JSON.parse(payload.talkData)
        console.log('talkRefresh', global.talkData)
    },
    changeLoginInfo: (payload) => {
        console.log('work_count', payload.notStart)
        const introOnline = global.shadowRoot.querySelector('#intro-online')
        if (payload.notStart < 5) {
            introOnline.style.setProperty('--after-content', `'지금은 바로 답변 받으실 수 있어요'`);
            introOnline.style.setProperty('--before-background', '#00d27a');
        } else if (payload.notStart < 10) {
            introOnline.style.setProperty('--after-content', `'현재 문의량이 많아 답변이 늦어져요. (대기시간 10분)'`);
            introOnline.style.setProperty('--before-background', '#fd7e14');
        } else if (payload.notStart >= 10) {
            introOnline.style.setProperty('--after-content', `'현재 문의량이 많아 답변이 늦어져요. (대기시간 30분)'`);
            introOnline.style.setProperty('--before-background', '#e63757');
        }
    }
}


export default receiver;