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

<script>
    export default {
        name: "IM",
        data() {
            return {
                currentUser: this.$store.state.login.currentUser,
                onlineAdress: "",
                wimadress: "",
                user: "",
                uname: "",
                websocket: null,
                layer: null
            }
        },
        mounted() {
            this.$nextTick(() => {
                // TODO 接口未搬迁暂时隐藏
                // this.getInfo();
            })
        },
        destroyed() {
            layer.closeAll();
        },
        methods: {
            // TODO 接口未搬迁暂时隐藏
            getInfo() {
                const _this = this;
                const userInfo = _this.currentUser;
                if(!userInfo) return ;
                this.$http.post('${uc}/head/getInfo',{},{tm: new Date().getTime()}).then(({data}) => {
                    _this.onlineAdress = data.onlineAdress//在线管理地址
                    _this.wimadress = data.wimadress //即时聊天地址
                    _this.user = data.USERNAME  //用户名
                    _this.uname = data.NAME

                    window.user = data.USERNAME
                    _this.initLayim();
                })
            },
            initLayim() {
                const _this = this;
                const userInfo = _this.currentUser;
                layui.use(['layim', 'readyMenu','layer'], function (layim) {
                    this.layer = layui.layer;
                    let f = setInterval(function () {
                        if ("" != _this.wimadress) {
                            clearInterval(f);
                            if (window.WebSocket) {
                                window.webSocket = new WebSocket(encodeURI('ws://' + _this.wimadress)); //wimadress参数在 assets/js-v/sys/index.js 中定义并赋值
                                // window.webSocket = _@this.websocket;
                                window.webSocket.onopen = function () {
                                    console.log(_this.user)
                                    window.webSocket.send(',fhadmin-join,' + _this.user); 	//发送上线消息(把上线状态发送给好友，对方好友栏目本头像从黑白色变彩色)(前提条件：本身在线状态设置为在线状态，否则对方看到的依然是离线状态)
                                    _this.$notify({
                                        title: '提示',
                                        message: '即时通讯已连接成功',
                                        duration: 1500
                                    });
                                };
                                window.webSocket.onerror = function () { 			//连接失败
                                    _this.$notify({
                                        title: '提示',
                                        message: '连接发生错误,刷新或者更换浏览器试试',
                                        duration: 1500
                                    });
                                };
                                window.webSocket.onclose = function () {			//连接断开
                                    _this.$notify({
                                        title: '提示',
                                        message: '已经断开连接',
                                        duration: 1500
                                    });
                                    window.webSocket.send(',fhadmin-leave,');		//发送下线消息
                                };
                                window.webSocket.onmessage = function (message) {	//消息接收
                                    message = JSON.parse(message.data);
                                    console.log(message)
                                    if ('friend' == message.type || 'group' == message.type) { //接收好友或群发送的消息
                                        getFHMessage(message);
                                    } else if ('user_join' == message.type) {
                                        friendOnline(message.user);
                                        _this.$notify({
                                            title: '消息',
                                            message: '好友'+message.name+'上线了',
                                            duration: 1500
                                        });
                                    } else if ('user_leave' == message.type) {
                                        friendOffline(message.user);
                                        _this.$notify({
                                            title: '消息',
                                            message: '好友'+message.name+'下线了',
                                            duration: 1500
                                        });
                                    } else if ('user_online' == message.type) {
                                        friendOnline(message.user);		//好友设置在线状态
                                    } else if ('user_hide' == message.type) {
                                        friendOffline(message.user);	//好友设置隐身状态
                                    } else if ('user_applyfriend' == message.type) {
                                        applyIFriend();					//申请加好友
                                    } else if ('user_emove' == message.type) {
                                        removeFriend(message.user);		//删除好友(被动删，被拉黑)
                                    } else if ('agreefriend' == message.type) {
                                        addFriend(message);				//对方同意添加好友
                                    } else if ('applyqgroup' == message.type) {
                                        applyIQgroup();					//申请加群申请
                                    } else if ('agreeqgroup' == message.type) {
                                        addIQgroup(message);			//对方同意群申请
                                    } else if ('kickoutqgroup' == message.type) {
                                        kickoutIQgroup(message.id);		//踢出群
                                    } else if ('delqgroup' == message.type) {
                                        delQgroup(message.QGROUP_ID);	//群解散
                                        _this.$notify({
                                            title: '消息',
                                            message: message.CONTENT,
                                            duration: 2000
                                        });
                                    }
                                };
                            } else {
                                _this.$notify({
                                    title: '消息',
                                    message: '此浏览器不支持websocket,请用支持HTML5的浏览器或者使用最新谷歌、火狐、360等浏览器',
                                    duration: 2000
                                });
                            }
                            ;
                            _this.$http.post('${uc}/iminterface/getImsign',{},{tm: new Date().getTime()}).then(({data}) => {
                                layim.config({
                                    init: {
                                        url: window.httpurl + '/iminterface/getList'//初始化接口
                                        , type: 'post'
                                        , data: {}
                                    }
                                    , members: {
                                        url: window.httpurl + '/iminterface/getMembers'			//查看群员接口
                                        , data: {}
                                        , type: 'post'
                                    }
                                    , uploadImage: {
                                        url: window.httpurl + '/iminterface/updateImg'			//上传图片接口
                                        , type: 'post' 								//默认post
                                        ,headers: {
                                            Authorization: "Bearer " + JSON.parse(window.sessionStorage.currentUser).token
                                        },
                                    }

                                    , uploadFile: {
                                        url: window.httpurl + '/iminterface/updateFile'			//上传文件接口
                                        , type: 'post' 								//默认post
                                    }
                                    , isAudio: true 									//开启聊天工具栏音频
                                    , isVideo: true 									//开启聊天工具栏视频
                                    /**扩展工具栏*/
                                    , tool: [{
                                        alias: 'code'
                                        , title: '代码'
                                        , icon: '&#xe64e;'
                                    }]
                                    //,brief: true 						//是否简约模式（若开启则不显示主面板）
                                    , title: '我的通讯' 					//自定义主面板最小化时的标题
                                    //,right: '100px' 					//主面板相对浏览器右侧距离
                                    //,minRight: '90px' 				//聊天面板最小化时相对浏览器右侧距离
                                    , initSkin: data ? data.imsign : ""		//1-5 设置初始背景 res.imsign
                                    //,skin: ['aaa.jpg'] 				//新增皮肤
                                    //,isfriend: false 					//是否开启好友
                                    ,isgroup: true 					//是否开启群组
                                    //,min: true 						//是否始终最小化主面板，默认false
                                    , notice: true 						//是否开启桌面消息提醒，默认false
                                    //,voice: false 					//声音提醒，默认开启，声音文件为：default.mp3
                                    , msgbox: window.pageurl + "/static/IM/messageBox.html" 				//消息盒子页面地址，若不开启，剔除该项即可
                                    , find: window.pageurl + "/static/IM/addFrined.html" 	//发现页面地址，若不开启，剔除该项即可
                                    , chatLog: '/static/IM/hismsg_list.html' 	//聊天记录页面地址，若不开启，剔除该项即可

                                });
                                /*基础配置*/
                            })
                        }
                    }, 1000);

                    layim.on('online', function (data) {			//监听在线状态的切换事件
                        window.webSocket.send(',fhadmin-' + data + ',' + _this.user);	//发送在线隐身消息
                        $.ajax({
                            xhrFields: {
                                withCredentials: false
                            },
                            headers: {
                                Authorization: "Bearer " + userInfo.token
                            },
                            type: "POST",
                            url: window.httpurl + '/iminterface/editState',
                            data: {ONLINE: data, TYPE: "online", tm: new Date().getTime()},
                            dataType: 'json',
                            success: function (data) {
                            }
                        });
                    });

                    layim.on('sign', function (data) {				//监听签名修改
                        $.ajax({
                            xhrFields: {
                                withCredentials: false
                            },
                            headers: {
                                Authorization: "Bearer " + userInfo.token
                            },
                            type: "POST",
                            url: window.httpurl + '/iminterface/editState',
                            data: {AUTOGRAPH: data, TYPE: "auto", tm: new Date().getTime()},
                            dataType: 'json',
                            success: function (data) {
                            }
                        });
                    });

                    layim.on('setSkin', function (filename, src) {	//监听更换背景皮肤
                        $.ajax({
                            xhrFields: {
                                withCredentials: false
                            },
                            headers: {
                                Authorization: "Bearer " + userInfo.token
                            },
                            type: "POST",
                            url: window.httpurl + '/iminterface/editState',
                            data: {SIGN: filename, TYPE: "sign", tm: new Date().getTime()},
                            dataType: 'json',
                            success: function (data) {
                            }
                        });
                    });

                    layim.on('tool(code)', function (insert) {		//监听自定义工具栏点击，以添加代码为例
                        layer.prompt({
                            title: '插入代码'
                            , formType: 2
                            , shade: 0
                        }, function (text, index) {
                            layer.close(index);
                            insert('[pre class=layui-code]' + text + '[/pre]'); //将内容插入到编辑器
                        });
                    });

                    /*监听layim建立就绪*/
                    layim.on('ready', function (res) {
                        layui.readyMenu.init(); 					//更新右键点击事件
                        $.ajax({
                            xhrFields: {
                                withCredentials: false
                            },
                            headers: {
                                Authorization: "Bearer " + userInfo.token
                            },
                            type: "POST",
                            url: window.httpurl + '/iminterface/getMsgCount',			//未读消息(加好友群等)总数
                            data: {tm: new Date().getTime()},
                            dataType: 'json',
                            success: function (data) {
                                if ('01' == data.result) {
                                    layim.msgbox(data.count); 		//消息盒子有新消息
                                }
                            }
                        });
                        $.ajax({
                            xhrFields: {
                                withCredentials: false
                            },
                            headers: {
                                Authorization: "Bearer " + userInfo.token
                            },
                            type: "POST",
                            url: window.httpurl + '/iminterface/getNoreadMsg',		//未读消息(离线消息)接口
                            data: {tm: new Date().getTime()},
                            dataType: 'json',
                            success: function (data) {
                                if ('has' == data.result) {
                                    $.each(data.list, function (i, list) {
                                        layim.getMessage({
                                            username: list.NAME 		//消息来源用户名
                                            , avatar: list.PHOTO 		//消息来源用户头像
                                            , id: list.USERNAME 		//消息的来源ID（如果是私聊，则是用户id，如果是群聊，则是群组id）
                                            , type: "friend" 			//聊天窗口来源类型，从发送消息传递的to里面获取
                                            , content: list.CONTENT 	//消息内容
                                            , timestamp: list.CTIME
                                        });
                                    });
                                }
                            }
                        });

                    });

                    //接收到好友或群的消息
                    function getFHMessage(data){
                        console.log(data)
                        layim.getMessage(data);
                    }

                    //接收到好友上线消息，头像取消置灰
                    function friendOnline(id){
                        layim.setFriendStatus(id, 'online'); //设置指定好友在线，即头像取消置灰
                    }

                    //接收到好友下线消息，头像置灰
                    function friendOffline(id){
                        layim.setFriendStatus(id, 'offline'); //设置指定好友下线，即头像置灰
                    }

                    //申请好友消息
                    function applyIFriend(){
                        layim.msgbox('新');
                        $("#fhsmsobj").html('<audio style="display: none;" id="fhsmstsy" src="../../../assets/sound/'+fhsmsSound+'.mp3" autoplay controls></audio>');
                    }

                    //申请加群消息
                    function applyIQgroup(){
                        layim.msgbox('新');
                        $("#fhsmsobj").html('<audio style="display: none;" id="fhsmstsy" src="../../../assets/sound/'+fhsmsSound+'.mp3" autoplay controls></audio>');
                    }

                    //踢出消息
                    function kickoutIQgroup(QGROUP_ID){
                        layui.layim.removeList({
                            type: 'group'
                            ,id: QGROUP_ID //群ID
                        });
                        layim.msgbox('新');
                        $("#fhsmsobj").html('<audio style="display: none;" id="fhsmstsy" src="../../../assets/sound/'+fhsmsSound+'.mp3" autoplay controls></audio>');
                    }

                    //删除好友(被对方拉黑)
                    function removeFriend(FUSERNAME){
                        layim.removeList({
                            type: 'friend' //或者group
                            ,id: FUSERNAME //好友用户名
                        });
                    }

                    //对方同意添加好友(加入好友栏目)
                    function addFriend(message) {
                        layim.addList({
                            type: 'friend' 				//列表类型，只支持friend和group两种
                            ,avatar: message.avatar 		//好友头像
                            ,username: message.username	//好友昵称
                            ,groupid: message.groupid		//所在的分组id
                            ,id: message.id 				//好友id
                            ,status: message.status 		//在线状态
                            ,sign: message.sign		 	//好友签名
                        });
                        layim.msgbox('新');
                        $("#fhsmsobj").html('<audio style="display: none;" id="fhsmstsy" src="../../../assets/sound/'+fhsmsSound+'.mp3" autoplay controls></audio>');
                        layui.readyMenu.init(); 			//更新右键点击事件
                    }

                    //对方同意添群(加入群组栏目)
                    function addIQgroup(message) {
                        layim.addList({
                            type: 'group' 					//列表类型，只支持friend和group两种
                            ,avatar: message.avatar			//群组头像
                            ,groupname: message.groupname 	//群组名称
                            ,id: message.id 					//群组id
                        });
                        layim.msgbox('新');
                        $("#fhsmsobj").html('<audio style="display: none;" id="fhsmstsy" src="../../../assets/sound/'+fhsmsSound+'.mp3" autoplay controls></audio>');
                    }

                    //群解散
                    function delQgroup(QGROUP_ID) {
                        layui.layim.removeList({
                            type: 'group'
                            ,id: QGROUP_ID //群ID
                        });
                        layim.msgbox('新');
                        $("#fhsmsobj").html('<audio style="display: none;" id="fhsmstsy" src="../../../assets/sound/'+fhsmsSound+'.mp3" autoplay controls></audio>');
                    }

                    //监听发送消息
                    layim.on('sendMessage', function (data) {
                        layer.closeAll('loading');
                        let To = data.to;		//当前用户资料
                        let mine = data.mine; 	//发送者数据(消息内容以及发送者资料)
                        /**
                         *    user:发送者用户名
                         *    uname：发送者用户姓名
                         *    To.id：对方用户名
                         *    To.type：消息类型 group or friend
                         *    mine.avatar:发送者用户头像
                         *    mine.content：消息内容
                         */
                        window.webSocket.send(",fhadmin-msg," + user + ",fh," + _this.uname + ",fh," + To.id + ",fh," + To.type + ",fh," + mine.avatar + ",fh," + mine.content + ',fh,' +mine.id);
                    });

                    //监听群员
                    layim.on('members', function (data) {
                        console.log(data);
                    });

                    //监听聊天窗口的切换
                    layim.on('chatChange', function (res) {
                        let type = res.data.type;
                        if (type === 'friend') {
                        } else if (type === 'group') {
                        }
                    });

                });
            }
        }
    }
</script>

<style scoped>
    /*@import '/public/static/layui/css/layui.css';*/
    /*@import '/public/static/layui/css/contextMenu.css';*/
</style>