var me;
loadCurrUserInfo();
function loadCurrUserInfo() {
    $.ajax({
        url:"/api/user/getCurrentUserInfo",
        type:"get",
        success:function (data) {
            data = eval(data);
            if (data.success){
                $("#login-user").show();
                $("#login-menu").hide();
                data = data.data;
                me = data;
                $("#author-name").text(me.userName);
                $("#author-photo").attr("src", me.photo);
            } else {
                location.href="/h5/auth";
            }
        },error:function () {
            location.href="/h5/auth";
        }
    })
}

var isDone = 1;
var lastId = "";
var size = 10;
var userLikeMomentMap = new HashMap();
loadMoments(size, lastId)
function loadMoments() {
    if (lastId == "") {
        // 首屏加载，清空页面数据
        $("#moment-list-container").empty();
    }
    $.ajax({
        url:"/api/moment/timeLine?size="+size+"&lastId="+lastId,
        type:"get",
        success:function (data) {
            data = eval(data);
            if (data.success){
                var list = data.data;
                if (list.length == 0) {
                    return;
                }
                $.each(list, function (index, moment) {
                    lastId = moment.id;
                    var m = "<div class=\"moment-card\" id=\"moment-card-"+moment.id+"\">\n" +
                        "            <div class=\"moment-card-left\">\n" +
                        "                <img src=\""+moment.userInfo.photo+"?x-oss-process=image/resize,m_fill,w_50,h_50\" class=\"user-photo\">\n" +
                        "            </div>\n" +
                        "            <div class=\"moment-card-right\" id=\"moment-card-right-"+moment.id+"\">\n" +
                        "                <div class=\"moment-card-username\">"+moment.userInfo.userName+"</div>\n" +
                        "                <div class=\"moment-card-content\">"+moment.content+"</div>\n";
                    if (moment.video != null && moment.video != '') {
                        m += "                <div class=\"moment-card-image-content\"><video width='300' controls name=\"media\"><source src=\""+moment.video+"\" type=\"video/mp4\"></video></div>\n";
                    }
                    if (moment.imageList != null && moment.imageList.length > 0) {
                        m += "                <div class=\"moment-card-image-content\">\n";
                        var imageSize = moment.imageList.length;
                        for (var j = 0; j < imageSize; j++) {
                            m += " <img class=\"moment-image-"+imageSize+" moment-image-id-"+moment.id+"\" src=\""+moment.imageList[j]+"\" onclick='previewImg("+moment.id+", "+j+")'>\n";
                        }
                        m += "</div>\n";
                    }
                    m += "                <div class=\"moment-card-footer\">\n" +
                        "                    <span class=\"moment-time\">"+formatMsgTime(moment.pubTime)+"</span>\n" +
                        "                    <button id=\"ctrl-"+moment.id+"\" class=\"moment-ctrl-btn\">··</button>\n" +
                        "                </div>";
                    // 记录用户是否点过赞
                    userLikeMomentMap.put(moment.id, moment.isLike);
                    var hasLike = moment.likeCount > 0;
                    var likeDisplay = hasLike ? "display: block" : "display: none";
                    m += "               <div class='like-container' id='like-container-"+moment.id+"' style='text-align: left; padding: 4px; font-size: 13px; background-color: whitesmoke; border-radius: 3px; "+likeDisplay+"'>" +
                                "                   <svg style='vertical-align: middle' t=\"1730995118998\" class=\"icon\" viewBox=\"0 0 1024 1024\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" p-id=\"6137\" width=\"16\" height=\"16\"><path d=\"M512 901.747c-13.584 0-26.122-4.18-37.094-13.061-8.882-7.315-225.698-175.02-312.424-311.38-28.735-44.93-68.441-106.057-68.441-192.784 0-144.718 108.147-262.269 240.326-262.269 67.396 0 131.657 30.825 177.633 84.637 45.453-54.335 109.192-84.637 177.11-84.637 132.702 0 240.327 117.551 240.327 262.27 0 85.159-37.094 143.673-67.396 191.216l-1.045 1.567c-86.727 136.36-303.543 304.588-312.425 311.38-10.449 8.359-22.987 13.06-36.571 13.06zM334.367 164.049c-109.714 0-198.53 98.743-198.53 220.473 0 74.188 33.959 127.478 61.649 170.319 83.07 130.09 294.138 294.139 303.02 300.93 3.657 2.613 7.314 4.18 11.494 4.18s7.837-1.567 11.494-4.18c8.882-6.791 219.95-170.84 303.02-300.93l1.045-1.568c28.212-44.93 60.604-95.608 60.604-168.75 0-121.209-89.339-220.474-198.53-220.474-60.082 0-115.984 29.257-153.6 80.98l-6.27 8.881c-4.18 5.225-10.449 8.36-16.718 8.36s-13.061-3.135-16.718-8.36l-6.27-8.881c-39.706-51.2-96.13-80.98-155.69-80.98z\" p-id=\"6138\"></path></svg>" +
                                "                       <span id='like-users-"+moment.id+"'>";
                            if (hasLike) {
                                for (let i = 0; i < moment.likeUsers.length; i++) {
                                    var likeUser = moment.likeUsers[i];
                                    m += "<span style='color: #050565' id='like-" + moment.id + "-" + likeUser.userId + "'>" + likeUser.userName + ",</span>";
                                }
                            }
                    m +=  "</span>" +
                          "</div>" +
                          "            </div>\n" +
                        "            <div style=\"clear: both\"></div>\n" +
                        "        </div>";
                    $("#moment-list-container").append(m);
                    initCtrlEvent();
                })
            }
        }
    })
}

$(function(){
    $(window).scroll(function () {
        var pageH = $(document.body).outerHeight(true); //整个网页高度
        var winH = $(window).height(); //页面可视区域高度
        var scrollT = $(window).scrollTop(); //滚动条top
        if (pageH  - winH - scrollT - 100 <= 0.5) {//滚动到哪个位置触发加载事件，在这里设置
            if (isDone == 1) {
                isDone = 0;
                loadMoments();
                setTimeout('Delay()', 800); //延时2秒
            }
        }
    });
})

//用于延时触发加载下一页，当滚动条到最下方时  正在加载下一页同时滚动条又在拉动 可能会引起瞬间再次向后台发送加载下一页的请求,延时一下解决这问题
function Delay() {
    isDone = 1;
}

//页面层-图片
function previewImg(id, start) {
    var imgUrls = "[";
    $(". moment-image-id-"+id).each(function(index, node){
        imgUrls += "{\"src\": \""+node.src+"\"},";
    });
    imgUrls = imgUrls.substring(0, imgUrls.length - 1);
    imgUrls += "]";
    layer.photos({
        photos: {"start": start, "data": eval(imgUrls)}
        ,anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机
        ,shade: [0.8, '#000']
        ,success: function() {
            //以鼠标位置为中心的图片滚动放大缩小
            $(document).on("mousewheel",".layui-layer-photos",function(ev){
                var oImg = this;
                var ev = event || window.event;//返回WheelEvent
                //ev.preventDefault();
                var delta = ev.detail ? ev.detail > 0 : ev.wheelDelta < 0;
                var ratioL = (ev.clientX - oImg.offsetLeft) / oImg.offsetWidth,
                    ratioT = (ev.clientY - oImg.offsetTop) / oImg.offsetHeight,
                    ratioDelta = !delta ? 1 + 0.1 : 1 - 0.1,
                    w = parseInt(oImg.offsetWidth * ratioDelta),
                    h = parseInt(oImg.offsetHeight * ratioDelta),
                    l = Math.round(ev.clientX - (w * ratioL)),
                    t = Math.round(ev.clientY - (h * ratioT));
                $(".layui-layer-photos").css({
                    width: w, height: h
                    ,left: l, top: t
                });
                $("#layui-layer-photos").css({width: w, height: h});
                $("#layui-layer-photos>img").css({width: w, height: h});
            });
        }
        ,end: function(){ //销毁回调

        }
    });
}

function formatMsgTime(timespan){
    var dateTime = new Date(timespan);
    var year = dateTime.getFullYear();
    var month = dateTime.getMonth() + 1;
    var day = dateTime.getDate();
    var hour = dateTime.getHours();
    var minute = dateTime.getMinutes();
    var nowDate = new Date();
    var now_new = new Date().getTime()
    var milliseconds = 0;
    var timeSpanStr;
    milliseconds = now_new - timespan;
    if (milliseconds <= 1000 * 60 * 1) {
        timeSpanStr = '刚刚';
    }
    else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) {
        timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前';
    }
    else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) {
        timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前';
    }
    else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) {
        timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前';
    }
    else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year == nowDate.getFullYear()) {
        timeSpanStr = day + ' / ' + month + '月';
    } else {
        timeSpanStr = year + ' / ' + month + ' / ' + day;
    }
    return timeSpanStr;
};

function initCtrlEvent() {
    layui.use(['layer'], function(){
        var layer = layui.layer;
        $('.moment-ctrl-btn').on('click', function() {
            // 显示提示，方向设置为2（左上），并自定义样式
            layer.tips('<button onclick="likeMoment(\''+$(this).attr("id").substring(5)+'\')" class="like-moment-btn"><svg t="1730901718958" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4279" width="20" height="20"><path d="M667.786667 117.333333C832.864 117.333333 938.666667 249.706667 938.666667 427.861333c0 138.250667-125.098667 290.506667-371.573334 461.589334a96.768 96.768 0 0 1-110.186666 0C210.432 718.368 85.333333 566.112 85.333333 427.861333 85.333333 249.706667 191.136 117.333333 356.213333 117.333333c59.616 0 100.053333 20.832 155.786667 68.096C567.744 138.176 608.170667 117.333333 667.786667 117.333333z m0 63.146667c-41.44 0-70.261333 15.189333-116.96 55.04-2.165333 1.845333-14.4 12.373333-17.941334 15.381333a32.32 32.32 0 0 1-41.770666 0c-3.541333-3.018667-15.776-13.536-17.941334-15.381333-46.698667-39.850667-75.52-55.04-116.96-55.04C230.186667 180.48 149.333333 281.258667 149.333333 426.698667 149.333333 537.6 262.858667 675.242667 493.632 834.826667a32.352 32.352 0 0 0 36.736 0C761.141333 675.253333 874.666667 537.6 874.666667 426.698667c0-145.44-80.853333-246.218667-206.88-246.218667z" fill="#ffffff" p-id="4280"></path></svg>点赞</button><button onclick="commentMoment(\''+$(this).attr("id").substring(5)+'\')"  style="margin-left: 20px" class="comment-moment-btn"><svg t="1730901750731" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5564" width="20" height="20"><path d="M291.636 385.404c-30.49 0-55.207 25.633-55.207 57.266 0 31.637 24.717 57.272 55.207 57.272 30.486 0 55.203-25.635 55.203-57.272C346.839 411.038 322.122 385.404 291.636 385.404L291.636 385.404z" fill="#ffffff" p-id="5565"></path><path d="M512.461 385.404c-30.49 0-55.208 25.633-55.208 57.266 0 31.637 24.722 57.272 55.208 57.272 30.486 0 55.204-25.635 55.204-57.272C567.665 411.038 542.947 385.404 512.461 385.404L512.461 385.404z" fill="#ffffff" p-id="5566"></path><path d="M733.287 385.404c-30.492 0-55.208 25.633-55.208 57.266 0 31.637 24.716 57.272 55.208 57.272 30.486 0 55.202-25.635 55.202-57.272C788.489 411.038 763.773 385.404 733.287 385.404L733.287 385.404z" fill="#ffffff" p-id="5567"></path><path d="M843.697 99.077 181.221 99.077c-60.972 0-110.41 51.287-110.41 114.539l0 429.487c0 63.256 50.543 121.56 112.92 121.56l168.257 0c29.33 31.245 150.716 156.912 150.716 156.912 5.389 5.606 14.124 5.606 19.514 0 0 0 88.87-100.764 146.775-156.912l172.193 0c62.376 0 112.92-58.308 112.92-121.56L954.106 213.615C954.107 150.363 904.673 99.077 843.697 99.077zM899.451 643.298c0 31.669-26.565 64.899-57.799 64.899L672.075 708.197c-20.543 0-39.009 21.123-39.009 21.123L514 852.815 394.955 729.32c0 0-22.676-21.123-42.112-21.123L183.267 708.197c-31.235 0-57.794-33.23-57.794-64.899L125.473 213.205c0-31.677 24.751-57.353 55.28-57.353l663.411 0c30.53 0 55.287 25.676 55.287 57.353L899.451 643.298z" fill="#ffffff" p-id="5568"></path><path d="M898.905 643.103" fill="#ffffff" p-id="5569"></path></svg>评论</button>', this, {
                tips: [2, '#000'], // 2代表方向，'#000'是提示框的背景颜色
                time: 0, // 3秒后自动关闭
                skin: 'no-border'
            });
        });
        // 监听页面点击事件，点击空白处关闭提示
        $(document).on('click', function(event) {
            // 判断用户点击的元素是否是提示框的目标元素或其子元素
            if ($(event.target).hasClass('moment-ctrl-btn')) {
                return;
            }
            if (!$(event.target).hasClass('layui-layer-tips') && !$(event.target).parents('.layui-layer-tips').length) {
                // 如果不是，则关闭当前打开的提示框
                layer.closeAll('tips');
            }
        });
    });
}

loadMessageCount();
function loadMessageCount() {
    $.ajax({
        url:  "/api/message/unreadCount",
        type: "get",
        success:function (data) {
            data = eval(data);
            if (data.success){
                var unReadCount = data.data.unReadAllMessageCount;
                if (unReadCount > 0) {
                    $("#momentRedPoint").show();
                }
            }
        }
    })
}

/**
 * 动态点赞
 *
 * @param momentId
 */
function likeMoment(momentId) {
    layer.closeAll('tips');

    var isLike = userLikeMomentMap.get(momentId);
    if (isLike) {
        // 当前动态已经点过赞
        $("#like-"+momentId+"-"+me.userId).remove();
        cancelBehavior('LIKE', 'MOMENT', momentId);
        userLikeMomentMap.put(momentId, false);
    } else {
        // 未点赞
        $("#like-container-"+momentId).show();
        $("#like-users-"+momentId).append("<span style='color: #050565' id='like-"+momentId+"-"+me.userId+"'>"+me.userName+",</span>");
        behavior('LIKE', 'MOMENT', momentId);
        userLikeMomentMap.put(momentId, true);
    }
}

function commentMoment(momentId) {
    layer.closeAll('tips');
    layer.msg("评论暂未支持~");
}

function behavior(behaviorType, resourceType, resourceId) {
    $.ajax({
        url: "/api/resource/behavior",
        type: "post",
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify({
            resourceId: resourceId,
            resourceType: resourceType,
            behaviorType: behaviorType,
        }),
        success:function (data) {
            data = eval(data);
            if (data.success){

            } else {
                layer.msg(data.msg);
                if (data.msg.indexOf("未登录") > -1) {
                    login();
                }
            }
        },error:function () {
            layer.msg("服务端异常");
        }
    })
}

function cancelBehavior(behaviorType, resourceType, resourceId) {
    $.ajax({
        url: "/api/resource/cancelBehavior",
        type: "post",
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify({
            resourceId: resourceId,
            resourceType: resourceType,
            behaviorType: behaviorType,
        }),
        success:function (data) {
            data = eval(data);
            if (data.success){
                if ('CTC_PATH' == resourceType && 'FOCUS' == behaviorType) {
                    refreshStarStatus(false);
                }
            } else {
                layer.msg(data.msg);
                if (data.msg.indexOf("未登录") > -1) {
                    login();
                }
            }
        },error:function () {
            layer.msg("服务端异常");
        }
    })
}

//简单的哈希表,begin
function HashMap() {
    /** Map 大小 * */
    var size = 0;
    /** 对象 * */
    var entry = new Object();

    /** 存 * */
    this.put = function(key, value) {
        if (!this.containsKey(key)) {
            size++;
        }
        entry[key] = value;
    }

    /** 取 * */
    this.get = function(key) {
        return this.containsKey(key) ? entry[key] : "";
    }

    /** 删除 * */
    this.remove = function(key) {
        if (this.containsKey(key) && (delete entry[key])) {
            size--;
        }
    }

    /** 是否包含 Key * */
    this.containsKey = function(key) {
        return (key in entry);
    }

    /** 是否包含 Value * */
    this.containsValue = function(value) {
        for ( var prop in entry) {
            if (entry[prop] == value) {
                return true;
            }
        }
        return false;
    }

    /** 所有 Value * */
    this.values = function() {
        var values = new Array();
        for ( var prop in entry) {
            values.push(entry[prop]);
        }
        return values;
    }

    /** 所有 Key * */
    this.keys = function() {
        var keys = new Array();
        for ( var prop in entry) {
            keys.push(prop);
        }
        return keys;
    }

    /** Map Size * */
    this.size = function() {
        return size;
    }

    /* 清空 */
    this.clear = function() {
        size = 0;
        entry = new Object();
    }
}
