address.js 10.1 KB
/**
 * 订单结算页
 * @author: yyq<yanqing.yang@yoho.cn>
 * @date: 2016/12/20
 */

var $ = require('yoho-jquery'),
    hbs = require('yoho-handlebars'),
    area = require('./areaSelect'),
    dialog = require('../../common/dialog');

var Dialog = dialog.Dialog,
    Confirm = dialog.Confirm,
    Alert = dialog.Alert;

var $addrWrap = $('#addr-list'),
    $deliveryAddr = $('#delivery-detail'),
    $supportWay2 = $('#support-way2');

var addressTpl = hbs.compile($('#address-tpl').html()),
    addressItemTpl = hbs.compile($('#address-item-tpl').html());

var addrList = {},
    addrDefault = '';

var addrSelect;

$('.addr-item').each(function() {
    var data = $(this).data();

    if (data.id) {
        if (data.area) {
            data.areaText = data.area.split(' ').join('/');
        }
        addrList[data.id] = data;

        if (data.default) {
            addrDefault = data.id;
        }
    }
});

Dialog.prototype.packageInfo = function() {
    var data = {};

    this.$el.find('input').each(function() {
        var $this = $(this),
            key = $this.attr('name');

        if (key) {
            data[key] = $.trim($this.val());
        }
    });

    data.areaCode = area.val();

    if (!data.phone) {
        delete data.phone;
    }

    if (this.$el.find('.radio-btn.on').length) {
        data.setDefault = true;
    }

    return data;
};

// 地址校验,支持单个字段与多字段
function validateAddress(data) {
    var regx = {
            consignee: /^[\u4e00-\u9fa5_a-zA-Z0-9_]{2,12}$/,
            areaCode: /^[0-9]{6}$/,
            mobile: /^\d{3}(\d{4}|\*{4})\d{1,8}$/,
            phone: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/
        },
        pass = true,
        i;

    data = data || {};
    for (i in data) {
        if (data.hasOwnProperty(i) &&
            regx[i] &&
            !regx[i].test(data[i])) {
            pass = false;
        }
    }
    return pass;
}

// 地址弹窗事件绑定
function bindOperateEvent($el) {
    var $areaBox = $el.find('.area-box');

    $el.on('change', 'input[name="consignee"]', function() {
        var $this = $(this);
        var val = $.trim($this.val()),
            tip = '';

        if (!val) {
            tip = '收货人不能为空';
        } else if (!validateAddress({consignee: val})) {
            tip = '请输入2-12个汉字、英文或数字';
        }
        $this.siblings('.caveat-tip').text(tip);
    }).on('change', 'input[name="address"]', function() {
        var $this = $(this);
        var val = $.trim($this.val()),
            tip = '';

        if (!val) {
            tip = '详细地址不能为空';
        }
        $this.siblings('.caveat-tip').text(tip);

        tip = '';
        if (!validateAddress({areaCode: area.val()})) {
            tip = '请填写完整的省市区信息';
        }
        $areaBox.siblings('.caveat-tip').text(tip);

    }).on('change', 'input[name="mobile"]', function() {
        var $this = $(this);
        var val = $.trim($this.val()),
            tip = '';

        if (!val) {
            tip = '手机号码不能为空';
        } else if (!validateAddress({mobile: val})) {
            tip = '您输入的手机号码格式不正确';
        }
        $this.siblings('.caveat-tip').text(tip);
    }).on('change', 'input[name="phone"]', function() {
        var $this = $(this);
        var val = $.trim($this.val()),
            tip = '';

        if (val && !validateAddress({phone: val})) {
            tip = '您输入的电话格式不正确';
        }
        $this.siblings('.caveat-tip').text(tip);
    }).on('click', '.radio-btn', function() {
        $(this).toggleClass('on');
    });
}

// 设置默认地址
function setDefaultAddr(id, cb) {
    $.ajax({
        url: '/cart/address/setdefault',
        type: 'POST',
        data: {id: id}
    }).done(function(data) {
        if (data.code === 200 && cb && typeof cb === 'function') {
            addrDefault = id;
            return cb();
        }
    });
}

// 设置底部显示送货地址,地址相关的操作会触发该方法
function setShowDeliveryAddr(data) {
    var _h = '';
    var $sel;

    if (!data) {
        $sel = $addrWrap.children('.addr-select');

        if ($sel.length && $sel.data('id')) {
            data = addrList[$sel.data('id')];
        }
    }

    if (data) {
        // 修改地址选中状态
        addrSelect = data.id;

        // 触发配送方式2是否支持状态改变
        $supportWay2.val(data.delivery ? 1 : 0).change();

        _h = '寄送至:' + data.area + '&nbsp;&nbsp;&nbsp;&nbsp;' + data.address +
            '<br>收货人:' + data.consignee + '&nbsp;&nbsp;&nbsp;&nbsp;' + data.mobile;
    }
    $deliveryAddr.html(_h);
}

function handelAddrInfo(data, reqData, $el) {
    var $items = $addrWrap.children(),
        $dom;

    if (reqData.id) {
        $.extend(addrList[reqData.id], {
            consignee: reqData.consignee,
            area: reqData.area,
            areaText: reqData.areaText,
            address: reqData.address,
            mobile: reqData.mobile,
            code: reqData.areaCode,
            phone: reqData.phone,
            delivery: data.is_delivery === 'Y'
        });

        $dom = $(addressItemTpl(addrList[reqData.id]));
        $el.html($dom.html());

        if ($el.hasClass('addr-select')) {
            setShowDeliveryAddr(addrList[reqData.id]);
        }

        if (reqData.setDefault && !$el.hasClass('addr-default')) {
            $el.find('.set-default').trigger('click');
        }
    } else {
        addrList[data.id] = {
            id: data.id,
            consignee: data.consignee,
            area: data.area,
            areaText: data.area.split(' ').join('/'),
            address: data.address,
            mobile: data.mobile,
            code: data.area_code,
            phone: data.phone,
            delivery: data.is_delivery === 'Y'
        };

        $dom = $(addressItemTpl(addrList[data.id]));

        $items.first().before($dom);
        $dom.trigger('click');

        if (reqData.setDefault) {
            $dom.find('.set-default').trigger('click');
        }
    }
}

function newEditAddress(title, info, $el) {
    var addDia = new Dialog({
        content: addressTpl({
            title: title,
            info: info
        }),
        className: 'ope-address-dialog',
        btns: [{
            id: 'save',
            name: '保存',
            btnClass: ['black'],
            cb: function() {
                var data = addDia.packageInfo();

                if (!validateAddress(data)) {
                    addDia.$el.find('input').trigger('change');
                    return;
                }

                info = info || {};

                if (info.id) {
                    data.id = info.id;
                }

                $.ajax({
                    url: '/cart/address/save',
                    type: 'POST',
                    data: data
                }).done(function(resData) {
                    if (resData.code === 200) {
                        $.extend(data, area.text());

                        addDia.close();

                        handelAddrInfo(resData.data, data, $el);
                    } else {
                        new Alert(title + '失败').show();
                    }
                });
            }
        }, {
            id: 'cancel',
            name: '取消',
            btnClass: ['btn-close']
        }]
    }).show();

    info = info || {};
    area.init(addDia.$el, info.code);
    bindOperateEvent(addDia.$el);
}

$('#new-address-btn, #new-address-block').click(function() {
    newEditAddress('新增地址');
});

$addrWrap.on('click', '.addr-item', function() {
    var $this = $(this),
        id = $this.data('id');

    if ($this.hasClass('addr-select')) {
        return;
    }

    $this.siblings('.addr-select').removeClass('addr-select');
    $this.addClass('addr-select');

    setShowDeliveryAddr(addrList[id]);
}).on('click', '.set-default', function(e) {
    var $item = $(this).closest('.addr-item');
    var id = $item.data('id');

    // 阻止事件冒泡
    if (e && e.stopPropagation) {
        e.stopPropagation();
    } else {
        window.event.cancelBubble = true;
    }

    if (id) {
        setDefaultAddr(id, function() {
            $item.siblings('.addr-default').removeClass('addr-default');
            $item.addClass('addr-default');
        });
    }
}).on('click', '.modify-addr', function(e) {
    var $item = $(this).closest('.addr-item');
    var id = $item.data('id');

    // 阻止事件冒泡
    if (e && e.stopPropagation) {
        e.stopPropagation();
    } else {
        window.event.cancelBubble = true;
    }

    if (id && addrList[id]) {
        if (id === addrDefault) {
            addrList[id].default = true;
        }
        newEditAddress('编辑地址', addrList[id], $item);
    }
}).on('click', '.delete-addr', function(e) {
    var $item = $(this).closest('.addr-item');
    var id = $item.data('id'),
        diaCf;

    // 阻止事件冒泡
    if (e && e.stopPropagation) {
        e.stopPropagation();
    } else {
        window.event.cancelBubble = true;
    }

    diaCf = new Confirm({
        className: 'addres-del-confirm',
        content: '<p class="main">删除地址</p><p class="sub">您确定要删除该收货地址吗?</p>',
        cb: function() {
            $.ajax({
                type: 'POST',
                url: '/cart/address/delete',
                data: {
                    id: id
                }
            }).then(function(data) {
                if (data.code === 200) {
                    $item.remove();
                    diaCf.close();
                }
            });
        }
    }).show();
});

$('.addr-opt').on('click', 'span', function() {
    var $this = $(this).parent(),
        $sel;
    var height = 650;

    if ($this.hasClass('open')) {
        height = 212;
        $sel = $addrWrap.find('.addr-select');

        if ($sel.index() > 3) {
            $addrWrap.children().first().before($sel);
        }
    }
    $addrWrap.animate({'max-height': height}, 300);
    $this.toggleClass('open');
});

setShowDeliveryAddr();

// 获取地址信息
exports.getAddress = function() {
    return addrSelect;
};