
//et页面绘制
var height=$(window).height()-80;
$(".table-scroll").height(height);

$(window).resize(function() {
	var screenWidth = ($(window).width()) *0.7;//获得当前网页可视宽度
	document.getElementsByClassName("chat01").height = height;
})

var firstMsgType = 'NN';

var msgTypeImg = new Map();
msgTypeImg['NS'] = {name: '新股提醒', image: 'new.png', logintip: '新股消息不错过'};
msgTypeImg['TA'] = {name: '交易提醒', image: 'jiao.png', logintip: '交易进展时刻提醒'};
msgTypeImg['AM'] = {name: '账户提醒', image: 'zhang.png', logintip: '时刻了解账户变动'};
msgTypeImg['NN'] = {name: '资讯提醒', image: 'zi.png', logintip: '优质资讯尽在掌握'};
msgTypeImg['FS'] = {name: '理财提醒', image: 'li.png', logintip: '理财提醒更贴心'};
msgTypeImg['SV'] = {name: '服务提醒', image: 'fu.png', logintip: '服务相关提醒不错过'};
msgTypeImg['SN'] = {name: '系统提醒', image: 'setting.png', logintip: '系统消息随时收'};


//解析url里面的参数
function GetRequest() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if(url.indexOf("?") != -1) {
        var str = url.substr(1);
        if(str.indexOf('&') != -1) {
            var strs = str.split('&');
            for(var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
            }
        } else {
            theRequest[str.split("=")[0]] = (str.split("=")[1]);
        }
    }
    return theRequest;
}
var urlParam = GetRequest();


// 解密函数title、content
function decode_title_content (str) {
    str = str.replace(/[\r\n]/g, ""); 
    str = str.replace(/\s/g, "="); 
    str = decode64(str);
    return str;
}

//消息中心时间格式处理
function xxzxTime(t, type){
    if(type == 'day'){
        return t.substr(0,4)+'-'+t.substr(4,2)+'-'+t.substr(6,2);
    }else if(type == 'second'){
        return t.substr(8,2)+':'+t.substr(10,2)+':'+t.substr(12,2);
    }else if(type == 'minute'){
        return t.substr(8,2)+':'+t.substr(10,2);
    }else if(type == 'all'){
        return t.substr(0,4)+'-'+t.substr(4,2)+'-'+t.substr(6,2)+' '+t.substr(8,2)+':'+t.substr(10,2)+':'+t.substr(12,2);
    }else if(type == 'et'){
        return t.substr(0,8)+' '+t.substr(8,2)+':'+t.substr(10,2);
    }    
}

//获取消息收藏列表
exports.GetStoreData('0').then(function(res){
    var totalNum = res.RNUM;
    var storeList = res.list;
    if(totalNum > 0){
        for(var i=0; i<storeList.length; i++){
            var info = {};
            info.msgID = storeList[i].msgid;
            info.msgTitle = decode_title_content(storeList[i].msgtitle);
            info.msgTime = xxzxTime(storeList[i].TopicTime, 'et');
            info.msgSummary = storeList[i].msgsummary;
            storeNavList.push(info);
        }
        storeNavList.reverse();
        gtjaWebEtLoginApi.addXXZXTypeListSC(storeNavList);
               
    }           
});

//展示某条消息
function readMsg(msgid, container){
    exports.GetSingleData(msgid).then(function (res) {
        if (res.RNUM > 0) {
            var info = res.list[0];
            var msgType = info.msgtype;
            var msgTitle = info.msgtitle;
            var msgCon = info.msgcontent;
            var msgTime = info.TopicTime;
            var fy_version = 'v2.2.8'; // 富易版本号
            var hrefUrl = '';
            msgTitle = decode_title_content (msgTitle);
            msgCon = decode_title_content (msgCon);
            //TopicTime处理
            msgTime = msgTime.substr(0, 4) + '-' + msgTime.substr(4, 2) + '-' + msgTime.substr(6, 2) + ' ' + msgTime.substr(8, 2) + ':' + msgTime.substr(10, 2) + ':' + msgTime.substr(12, 2);
        


            var content_str = ''; //总内容字符串
            // =============增加策略消息内容 start======================
            var topicId = info.topicid;
            function CLMonitorType (BSFLAG) {
                switch (BSFLAG) {
                    case "0": return "挂单买入";
                    break;
                    case "1": return "挂单卖出";
                    break;
                    case "2": return "止盈止损";
                    break;
                    case "3": return "反弹买入";
                    break;
                    case "4": return "回落卖出";
                    break;
                }
            }
            if (msgType == "text" || msgType == "HTML") {
                $('.collect').remove();
                // 对topicid=33的消息的处理
                var html_text_str = ''; // type为text、html类型
                if (topicId == '33') {
                    var time_font = '<div class="collect-scale"><p class="time">' + msgTime +'</p><p class="right-p"><span class="scale">字号:<a href="###">大</a><a href="###">中</a><a href="###">小</a></span></p></div>';
                    var con = JSON.parse(msgCon);
                    var data = JSON.parse(con.DATA);
                    var MSG_TYPE = con.MSG_TYPE;
                    var strategyId = data.STRATEGY_ID;
                    var strategyType = data.STRATEGY_TYPE;
                    var fundId = data.CUACCT_CODE;
                    var stockCode = data.TRADE_STOCK_CODE;
                    var stockName = data.TRADE_STOCK_NAME;
                    var traderAccount = data.TRDACCT;
                    var stockPrice = data.ORDER_PRICE;
                    var credit_Flag = data.CREDIT_TYPE;
                    var stockQty = data.ORDER_QTY;
                    var market = data.MARKET;
                    var CFTime = data.TIGGER_TIME;
                    var AutoOlder = data.AUTO_ORDER_FLAG;
                    var remark = data.REMARK;
                    var traderNo = data.STTRADE_NO;
                    console.log(MSG_TYPE)
                    console.log(strategyType)
                    if (MSG_TYPE == 'CF') {
                        html_text_str = '<div class="htmltype-box">' +
                            '<h3 class="htmltype-title">策略触发提醒</h3>' + time_font +
                            '<div class="htmltype-text">您的' + strategyId + '号<strong style="color: red;">'+CLMonitorType(strategyType)+'</strong>策略已经触发，策略已经失效<br>' +
            '证券名称：'+ stockName + '&nbsp(&nbsp' + stockCode + '&nbsp)<br>' +
            '委托价格：' + stockPrice + '<br>' +
            '委托数量：' + stockQty + '<br>' +
            '触发时间：' + CFTime + '</div>' +
                        // '<a class="entrust-btn">立即委托</a>' +
                        '</div>';
                    } else if (MSG_TYPE == 'WTSB') {
                        html_text_str = '<div class="htmltype-box">' +
                        '<h3 class="htmltype-title">策略埋单失败提醒</h3>' + time_font +
                        '<div class="htmltype-text">您的' + strategyId + '号<strong style="color: red;">'+CLMonitorType(strategyType)+'</strong>策略委托失败，策略已经失效<br>' +
        '证券名称：'+ stockName + '&nbsp(&nbsp' + stockCode + '&nbsp)<br>' +
        '委托价格：' + stockPrice + '<br>' +
        '委托数量：' + stockQty + '<br>' +
        '失败原因：' + remark + '</div>' +
                    '</div>';
                    } else if (MSG_TYPE == 'CLSX') {
                        html_text_str = '<div class="htmltype-box">' +
                        '<h3 class="htmltype-title">策略执行失败提醒</h3>' + time_font +
                        '<div class="htmltype-text">您的' + strategyId + '号<strong style="color: red;">'+CLMonitorType(strategyType)+'</strong>策略埋单失败，策略已经失效<br>' +
        '证券名称：'+ stockName + '&nbsp(&nbsp' + stockCode + '&nbsp)<br>' +
        '委托价格：' + stockPrice + '<br>' +
        '委托数量：' + stockQty + '<br>' +
        '失败原因：' + remark + '</div>' +
                    '</div>';
                    }
                } else {
                    html_text_str = '<div class="htmltype-box">' +
                    '<h3 class="htmltype-title">' + msgTitle +'</h3>' + time_font +
                    '<div class="htmltype-text">' + msgCon +'</div>' +
                    '</div>';
                }
                content_str += html_text_str;
                // =============增加策略消息内容 end======================
            } else if (msgType == "URL") {
                $('.collect').remove();
                hrefUrl = msgCon;
                content_str += '<div class="jsontype-box"><iframe class="iframe-box" src="'+ hrefUrl +'"></iframe></div>';
            } else if (msgType == "JSON") {
                $('.collect').remove();
                if (msgCon.indexOf('https') != -1) {
                   hrefUrl = 'https://dl.app.gtja.com/public/fy/fyinfo/index.html?url=' + msgCon + '&vs=' + fy_version + '&ty=fy'
                } else if (msgCon.indexOf('http') != -1) {
                   hrefUrl = 'http://dl.app.gtja.com/public/fy/fyinfo/index.html?url=' + msgCon + '&vs=' + fy_version + '&ty=fy'
                }
                content_str += '<div class="jsontype-box"><iframe class="iframe-box" src="'+ hrefUrl +'"></iframe></div>';
            }
            var QRcode_str = '<div class="code-box">' +
                '<img src="imgs/fyQRcode.png" class="smallImg" alt="">' +
                '<span class="big">点击放大</span>' +
                '<img src="imgs/fyQRcode.png" class="bigImg" alt="">' +
                '<span>扫码关注“国泰君安微理财”<br>免费赠送操盘通知大礼包</span>' +
                '</div>';
            content_str += QRcode_str;
            
            container.html(content_str);

            $('.big').hover(function() {
                $('.bigImg').show();
            }, function () {
                $('.bigImg').hide();
            });

            $('.bigImg').hover(function() {
                $(this).show();
            }, function () {
                $(this).hide();
            });

            $('.back-collect').append('<a href="###" class="collect">收藏</a>');

            // 点击收藏
            $('.collect').on('click', function() {
                exports.SetStoring(msgid).then(function (res) {
                    if (res.RNUM > 0) {
                        var collect_status = res.list[0].msg;
                        if (collect_status == '1') {
                            // 收藏成功
                            $('.collect').css('background', 'url("./imgs/cancel_collect.png") no-repeat left center');
                        } else {
                            // 收藏失败
                            $('.collect').css('background', 'url("./imgs/collect.png") no-repeat left center');
                        }
                    }
                });
            });
            // 点击取消收藏
            $('.cancel-collect').on('click', function() {
                exports.CancelCollect(msgid).then(function (res) {
                    if (res.RNUM > 0) {
                        var collect_status = res.list[0].msg;
                        if (collect_status == '1') {
                            // 取消收藏成功
                            $('.cancel-collect').css('opacity', '0');
                            $('.deletSC').append('<span class="cancel_ok">取消成功</span>');
                            $('.cancel_ok').show();
                            $('.cancel_ok').animate({opacity:"1", top:'10px'}, 400);
                            $('.cancel_ok').animate({opacity:"0"}, 600);
                        } else {
                            // 取消收藏失败
                            $('.cancel-collect').css('background', 'url("./imgs/cancel_collect.png") no-repeat left center');
                        }      
                    }
                });
            });
            // 点击变化字体大小
            $('.scale').on('click', 'a', function() {
                var aTxt = $(this).text();
                if (aTxt == '大') {
                    $('.htmltype-text').css('fontSize', '16px');
                } else if (aTxt == '中') {
                    $('.htmltype-text').css('fontSize', '14px');
                } else if (aTxt == '小') {
                    $('.htmltype-text').css('fontSize', '12px');
                }
            })
        }
    });   
}

//点击查看某条消息
function typeReadMsg(obj){
    var obj = $(obj);
    var msgid = obj.attr("data-msgid");
    // var msgContainer = $(".single-msg");
    var msgContainer = $(".content-box");
    readMsg(msgid, msgContainer);
    $(".single-msg").animate({left:'0px'});
}

function returnMsgList(){
    $(".single-msg").animate({left:'2000px'});
}

//点击查看某类消息,返回最多50条;点击后所有未读消息置为已读
function getTypeMsg(type, domEl){
    exports.getUserInfo().then(function (userinfo) {
        if(userinfo.USERCOUNT <= 0){
            var htmlStr = '<div class="xxzx-wrap NS-no-msg">' +
                    '<img src="./imgs/NS_pic.png">' +
                    '<span class="NS_nodata_text">' + msgTypeImg[type].logintip + '</span>' +
                    '<p class="NS-login">' +
                    '<button type="button" class="login-btn">登录</button>' +
                    '</p></div>';
            var s = $(htmlStr);
            domEl.find(".xxzxTypeContent").append(s);
            return;
        }
        var userInfo = userinfo.list[userinfo.USERCOUNT];
        var imgName = '';
        switch(type) {
            case 'NN':
                imgName = msgTypeImg['NN'].image;
                break;
            case 'NS':
                imgName = msgTypeImg['NS'].image;
                break;
            case 'TA':
                imgName = msgTypeImg['TA'].image;
                break;
            case 'AM':
                imgName = msgTypeImg['AM'].image;
                break;
            case 'FS':
                imgName = msgTypeImg['FS'].image;
                break;
            case 'SV':
                imgName = msgTypeImg['SV'].image;
                break;
            case 'SN':
                imgName = msgTypeImg['SN'].image;
                break;
        }

        exports.GetInfocentClassData(userInfo.USER_CUSTID, type, '0').then(function (res) {
            if(res.RNUM > 0){
                var newsList = (res.list).reverse();
                var htmlStr = '<div class="xxzx-wrap"><div class="single-msg"><p class="back-collect"><a href="###" onclick="returnMsgList()"><返回</a></p><div class="content-box"></div></div><ul class="type-msg-content">';

                for(var i=0; i<newsList.length; i++){
                    // if(newsList[i].isread == '1'){
                    //     exports.SetReading(newsList[i].msgid);
                    // }
                    var msgTitle = decode_title_content(newsList[i].msgtitle);
                    var msgAbst = decode_title_content(newsList[i].msgsummary);
                    var msgTime = xxzxTime(newsList[i].TopicTime, 'all');
                    var str = [
                        '<li class="msg-list" onclick="typeReadMsg(this)" data-msgid='+newsList[i].msgid+'>',
                        '<span class="msg-list-time">'+msgTime+'</span>',
                        '<div class="img-con"><img src="et/images/' + imgName + '" class="msg-img"/>',
                        '<p class="title-abst-frame"><span class="msg-list-title">'+msgTitle+'</span> ',
                        '<span class="msg-list-abst">'+msgAbst+'</span></p></div></li>'
                    ].join("");
                    htmlStr += str;
                }
                htmlStr += '</ul></div>';                           
            }else{
                var htmlStr = '<div class="xxzx-wrap no-msg"><img src="./imgs/nodata_pic.png"><span class="nodata_text">暂无消息</span></div>';
            }
            var s = $(htmlStr);  
            domEl.find(".xxzxTypeContent").append(s);
            // 将滚动条默认设为底部
            $('.type-msg-content').scrollTop($('.type-msg-content')[0].scrollHeight);   
        })
    });
}

//收藏页右侧界面
function readSCmsg(msgid, domEl){
    var msgContainer = domEl.find(".xxzxTypeContent");
    // msgContainer = msgContainer.append("<div class='deletSC'>取消收藏</div>");
    msgContainer = msgContainer.append("<div class='deletSC'><a href='###' class='cancel-collect'>取消收藏</a></div>");
    readMsg(msgid, msgContainer);
}

$(function(){
    // gtjaWebEtLoginApi.checkLogin();
    // gtjaWebEtLoginApi.openChatWin('', '');
	exports.getUserInfo().then(function(userInfo){
        //登录et
		var userInfo = userInfo.list[userInfo.USERCOUNT];
        var loginFlag = (userInfo.USER_CUSTID == '')?false:true;
        var msgTypeList = ['NS','TA','AM','NN','FS','SV','SN'];
        var typeArray = [];        

        if(false){
            gtjaWebEtLoginApi.custId = userInfo.USER_CUSTID;
            gtjaWebEtLoginApi.custType='3';
            gtjaWebEtLoginApi.ettoken = userInfo.USER_OLDTOKEN;
        }else{
            var min = 1000, max = 10000000;
            gtjaWebEtLoginApi.custId = Math.floor(Math.random()*(max-min-1)+min);
            gtjaWebEtLoginApi.custType='-1';
        }
        gtjaWebEtLoginApi.checkLogin();


        //获取消息收藏列表
        exports.GetStoreData('0').then(function(res){
            var totalNum = res.RNUM;
            var storeList = res.list;
            var storeNavList = [];
            if(totalNum > 0){
                for(var i=0; i<storeList.length; i++){
                    var info = {};
                    info.msgID = storeList[i].msgid;
                    info.msgTitle = decode_title_content(storeList[i].msgtitle);
                    info.msgTime = xxzxTime(storeList[i].TopicTime, 'et');
                    info.msgSummary = storeList[i].msgsummary;
                    storeNavList.push(info);
                }
                storeNavList.reverse();
                gtjaWebEtLoginApi.addXXZXTypeListSC(storeNavList);
                       
            }           
        });


        //响应人资料获取
        // exports.uc['客户响应人查询']({
        //     CUST_CODE: '03' + ('000000000000000000000' + userInfo.USER_CUSTID).substr(-12);
        // }).then(function(res){
        //     if(res.RNUM > 0){
        //         var xyr = res.list[0];

        //     }
        // })

        //初始化类别顺序，获取消息中心列表        
        exports.GetInfocentData(userInfo.USER_CUSTID, '0').then(function (res) {
            var msgTypeArray = [];
            var typeList = res.list;
            firstMsgType = typeList[0].busid;
            for(var i=0; i<msgTypeList.length; i++){
                var obj = {
                    typeID: msgTypeList[i],
                    typeName: msgTypeImg[msgTypeList[i]].name,
                    typeimg: msgTypeImg[msgTypeList[i]].image,
                    recentlyMsgTime: '',
                    recentlyMsyContent: '',
                    unreadMsgCount: ''
                };
                typeArray.push(obj);
            }

            for(var i=0; i<res.RNUM; i++){
                for(var j=0; j<typeArray.length; j++){
                    if(typeList[i].busid == typeArray[j].typeID){
                        typeArray.splice(j, 1);
                        break;
                    }
                }

                var obj = {};
                obj.typeID = typeList[i].busid;
                obj.typeName = typeList[i].busname;
                obj.recentlyMsyContent = decode_title_content(typeList[i].msgtitle);
                obj.unreadMsgCount = typeList[i].count;
                obj.typeimg = msgTypeImg[typeList[i].busid].image;
                var t = typeList[i].TopicTime;
                obj.recentlyMsgTime = xxzxTime(t, 'et');
                msgTypeArray.push(obj);
            }
            msgTypeArray = msgTypeArray.concat(typeArray);
            msgTypeArray.reverse();
            gtjaWebEtLoginApi.addXXZXTypeList(msgTypeArray);

            //通过不同url参数，定位至不同会话      
            /*if(urlParam["kfjid"]){
                if(urlParam["kfjid"] == 'lx'){
                    gtjaWebEtLoginApi.openChatWin('', '');
                }else{
                    if(urlParam["kfname"]){
                        gtjaWebEtLoginApi.openChatWin(urlParam["kfjid"], urlParam["kfname"]);
                    }else{
                        gtjaWebEtLoginApi.openChatWin(urlParam["kfjid"], '');
                    }                
                }
            }else if(urlParam["msgtype"]){
                gtjaWebEtLoginApi.viewType(urlParam["msgtype"]);
                if(urlParam["msgid"]){
                    var msgContainer = $(".single-msg")
                    readMsg(msgid, msgContainer);
                    $(".single-msg").animate({left:'0px'});                
                }
            }else{
                gtjaWebEtLoginApi.viewType(firstMsgType);
            }*/
            var kfjid="016206.1_4@chat.gtja.com";
            var kfname="凌宏健";
            gtjaWebEtLoginApi.openChatWin(kfjid,kfname);            
        })

	});
})
