/**
 * 消息推送
 * Copyright (c) 2019 xiaofanku
 * mail:xiaofanku@live.cn
 */
(function($) {
    'use strict';
    var letterSock, config;
    var dtd = $.Deferred();
    //初始化sock
    function init(dtd){
        letterSock = new SockJS(config.remote);
        letterSock.onopen = function() {
           //ETC
           console.log('Letter Socket opened!');
           dtd.resolve();
        };
        
        letterSock.onmessage = function(e) {
            var fn = window[config.callFunctionExp];
            if (typeof fn === "function"){
                fn.call(this, e.data);
            }
        };
        
        letterSock.onclose = function() {
            console.log('Letter Socket close');
        };
        letterSock.onerror = function(e) {
            console.log('Letter Socket has Error: '+e);
            dtd.reject();
        };
        return dtd;
    }
    var getUnReadLetterSize = function(member, previousUx){
        letterSock.send('{"id":"'+member+'", "ux":"'+previousUx+'", "cmd":"1"}');//消息数量,
    };
    //周期的发送查询请求
    function loopRequest(loopUnit){
        setInterval(function(){
            var tux = config.jqEle.attr('data-ux');
            var member = config.jqEle.attr('data-member');
            getUnReadLetterSize(member, tux);
        }, loopUnit); //毫秒
    };
    //Jquery绑定
    $.fn.letterSocket = function(option, loopUnit) {
        var _self=this;
        config = $.extend({jqEle: _self, eleId: _self.attr('id')}, option);
        //初始化sock
        $.when(init(dtd)).done(function(){
            loopRequest(loopUnit);
        }).fail(function(){ 
            console.log("Letter Socket happed fail"); 
        });
        return this;
    }
})(jQuery);