message.js 2.77 KB
/**
 * 我的信息
 * @author: yyqing<yanqing.yang@yoho.cn>
 * @date: 2016/3/21
 */
var $ = require('yoho.jquery');

var $container = $('#message-main-container'),
    $msgCheck = $container.find('.msg-check'),
    $readBtn = $container.find('.read-choose-btn'),
    $checked;

var operationId = [];

require('./message-content');

function hasNew() {
    var newMsg = false;

    $checked = $container.find('.msg-check:checked');
    operationId = [];

    $checked.each(function() {
        var $par = $(this).parent().parent();

        operationId.push($(this).val());
        if ($par.hasClass('new-msg')) {
            newMsg = true;
        }
    });

    if (newMsg) {
        $readBtn.addClass('has-new');
    } else {
        $readBtn.removeClass('has-new');
    }
}

function msgOperation(type, data) {
    var url;

    switch (type) {
        case 'del':
            url = '/home/message/delMessage';
            break;
        case 'read':
            url = '/home/message/readMessage';
            break;
    }

    $.ajax({
        type: 'GET',
        url: url,
        data: data
    }).then(function(jsonData) {
        if (!jsonData.code) {
            if (type === 'del') {
                $container.html(jsonData);
                $msgCheck = $container.find('.msg-check');
                $readBtn = $container.find('.read-choose-btn');
            }
        } else {
            if (jsonData.code === 200) {
                if (type === 'read') {
                    $checked.removeAttr('checked');
                    $checked.parent().parent().removeClass('new-msg');
                    hasNew();
                }
            } else {
                alert(jsonData.message);
            }
        }
    });
}

$container.on('change', 'input[type="checkbox"]', function() {
    var checked = $(this).attr('checked');

    if ($(this).hasClass('choose-all')) {
        if (checked === 'checked') {
            $msgCheck.attr('checked', true);
        } else {
            $msgCheck.removeAttr('checked');
        }
    }
    hasNew();
});

$container.on('click', '.del-btn', function() {
    if (confirm('您确定要删除这条短消息?')) {
        msgOperation('del', $(this).data());
    }
});

$container.on('click', '.del-choose-btn', function() {
    if (!operationId.length) {
        alert('请选中您要删除的消息');
        return;
    }

    if (confirm('确定要删除您选中的消息')) {
        msgOperation('del', {
            id: operationId.join(',')
        });
    }
});

$container.on('click', '.read-choose-btn', function() {
    if ($(this).hasClass('has-new')) {
        msgOperation('read', {
            id: operationId.join(',')
        });
    }
});