<template>
    <div class="msg-container">
        <div @click="showMsg()">
            <!-- <i class="el-icon-message-solid bell"></i> -->
            诊单消息
        </div>
        <div class="msgBox" v-if="isShow">
            <el-scrollbar style="height:200px;">
                <div class="msgList">
                    <div
                        v-for="(item,index) in msgList"
                        :key="index"
                        class="msgItem"
                        @click="jumpToChat(item)"
                    >
                        <el-image :src="item.avatarUrl | pathPipe" :fit="'cover'" class="images"></el-image>
                        <span class="name">{{item.name}}</span>
                    </div>
                </div>
            </el-scrollbar>
        </div>
    </div>
</template>
<script>
import { webSocketUrl } from '../../../../config';
export default {
    data() {
        return {
            isShow: false,
            msgList: [],
            $ws: null,
            lockReturn: false,
            timeout: 60 * 1000,
            timeoutObj: null,
            timeoutNum: null,
            serverTimeoutObj: null,
        };
    },
    created() {
        this.initWebSocket();
    },
    methods: {
        initWebSocket() {
            if (window.WebSocket) {
                this.$ws = new WebSocket(webSocketUrl);
                this.$ws.onopen = this.wsOpen;
                this.$ws.onclose = this.wsClose;
                this.$ws.onmessage = this.wsMessage;
                this.$ws.onerror = this.wsError;
            } else {
                this.$message.warning('浏览器暂不支持WebSocket服务');
            }
        },
        wsOpen(e) {
            console.log('...连接成功...');
            // this.startWsHeartbeat();
            this.initLogin();
        },
        wsClose: function(e) {
            console.log('...连接关闭...');
        },
        wsError: function(e) {
            console.log('...连接出现错误...');
            // this.reconnect();
        },
        wsMessage: function(e) {
            // this.resetHeartbeat();
            let messageData = JSON.parse(e.data);
            if (messageData && messageData.cmd === 'UNREAD') {
                let obj = JSON.parse(messageData.msg);
                let arr2 = [];
                for (let i in obj) {
                    if (obj[i]) {
                        let arr = obj[i];
                        if (arr && arr.length > 0) {
                            arr.forEach(item => {
                                arr2.push(item);
                            });
                            if (arr2 && arr2.length > 0) {
                                this.msgList = arr2.filter(item => {
                                    return item.userId !== this.$userId();
                                });
                            }
                        }
                    }
                }
            }
        },
        //重启websocket
        reconnect: function() {
            let _this = this;
            if (_this.lockReturn) {
                return;
            }
            _this.lockReturn = true;
            _this.timeoutNum && clearTimeout(_this.timeoutNum);
            _this.timeoutNum = setTimeout(function() {
                _this.initWebSocket();
                _this.lockReturn = false;
            }, 3000);
        },
        startWsHeartbeat: function() {
            let _this = this;
            _this.timeoutObj && clearTimeout(_this.timeoutObj);
            _this.serverTimeoutObj && clearTimeout(_this.serverTimeoutObj);
            _this.timeoutObj = setInterval(function() {
                //判断websocket当前状态
                if (_this.$ws.readyState != 1) {
                    _this.reconnect();
                }
            }, _this.timeout);
        },
        //重置websocket心跳
        resetHeartbeat: function() {
            let _this = this;
            clearTimeout(_this.timeoutObj);
            clearTimeout(_this.serverTimeoutObj);
            _this.startWsHeartbeat();
        },
        // 初始用户登录
        initLogin() {
            let obj = {};
            obj.cmd = 'WEBLOGINALL';
            obj.type = 1;
            obj.avatarUrl = JSON.parse(sessionStorage.getItem('avatarUrl'));
            obj.time = new Date().getTime();
            obj.fromUser = this.$userId();
            obj.name = '管理员';
            obj.sessionid = this.$userId();
            obj.msg = '管理员登录！';
            this.$ws.send(JSON.stringify(obj));
        },
        showMsg() {
            this.isShow = !this.isShow;
        },
        jumpToChat(data) {
            console.log(data);
            this.$router.push({
                path: '/chat-room',
                query: {
                    id: null,
                    customerServiceId: data.userId,
                    sessionId: data.sessionId,
                    name: data.name,
                },
            });
        },
        reset() {
            this.lockReturn = false;
            this.timeoutObj = null;
            this.timeoutNum = null;
            this.serverTimeoutObj = null;
            this.$ws.onclose();
        },
    },
    watch: {
        $route(to, from) {
            this.isShow = false;
        },
    },
};
</script>


<style lang="stylus" scoped>
.msg-container {
    position: relative;
    height: 35px;
    line-height: 35px;

    .bell {
        font-size: 16px;
        margin-right: 2px;
    }

    .msgBox {
        position: absolute;
        top: 49px;
        right: -50px;
        z-index: 10;
        width: 160px;
        height: 200px;
        border: 1px solid #ebeef5;
        border-radius: 10px;
        background-color: #fff;
        color: #555;
    }

    .msgList {
        padding: 6px 20px;
    }

    .msgItem {
        display: flex;
        align-items: center;

        .images {
            width: 28px;
            height: 28px;
            border-radius: 50%;
        }

        .name {
            margin-left: 20px;
            font-size: 13px;
            color: #606266;
        }
    }
}
</style>