simple-header.js 2.43 KB
var $ = require('yoho.jquery');

if ($('.simple-header').size() > 0) {
    $('.tool-options').on('mouseenter', function() {
        $(this).find('.tool-select').fadeIn();
    }).on('mouseleave', function() {
        $(this).find('.tool-select').fadeOut();
    });
}

/**
 * 格式化用户名
 * @return {[type]} [description]
 */
function formatUsernName(userName) {
    var name,
        char,
        _num = 0,
        _length = 0,
        t;

    for (t = 0; t < userName.length; t++) {
        char = userName.substr(t, 1);
        if (/.*[\u4e00-\u9fa5]+.*$/.test(char)) {
            _length += 2;
        } else {
            _length += 1;
        }
    }
    if (_length <= 10) {
        name = userName;
    } else {
        _num = 0;
        name = '';
        for (t = 0; t < userName.length; t++) {
            if (_num < 10) {
                char = userName.substr(t, 1);
                if (char !== '*') {
                    if (/.*[\u4e00-\u9fa5]+.*$/.test(char)) {
                        _num += 2;
                    } else {
                        _num += 1;
                    }
                }
                name += char;
            }
        }
        if (name.length < userName.length) {
            name += '...';
        }
    }
    return name;
}

/**
 * 设置简单头部登陆状态
 * @return {[type]} [description]
 */
function setLoginStatus(_data) {
    var loginHtml,
        name;

    if (_data && _data.href && _data.href.user) {
        name = formatUsernName(_data.href.user);
        loginHtml = '<span>Hi~</span><a href="">' +
                    name + '</a>&nbsp;<a href="' + _data.href.logout + '">[退出]</a>';
    } else {
        name = formatUsernName(_data.user);
        loginHtml = '<span>Hi~</span><a href="">' +
                    name + '</a>&nbsp;<a href="http://www.yohobuy.com/signin.html">[请登录]</a>' +
                    '<a href="http://www.yohobuy.com/reg.html">[免费注册]</a>';
    }
    $('.header-tool li').eq(0).html(loginHtml);
}

/**
 * 获取登录信息
 * @return {[type]} [description]
 */
function actionLoginInfo() {
    $.ajax({
        type: 'GET',
        url: '/common/getSimpleHeader',
        data: {},
        success: function(data) {
            if (data.code === 200) {
                setLoginStatus(data.data);
            }
        }
    });
}

/**
 * 初始化函数
 * @return {[type]} [description]
 */
exports.init = function() {
    actionLoginInfo(); //获取登录信息
}