address.js 11.7 KB
/**
 * 订单确认页地址相关
 * @author:xuqi<qi.xu@yoho.cn>
 * @date: 2016/7/12
 */

var $ = require('yoho-jquery'),
    Hbs = require('yoho-handlebars'),
    cascadingAddress = require('../../plugins/cascading-address'),
    popup = require('../../plugins/dialog');

var $receiver = $('#receiver');

var Dialog = popup.Dialog,
    Confirm = popup.Confirm;

var addressDialogTpl;
var addressTpl;

// 判断是否是Y
Hbs.registerHelper('isY', function(value, options) {
    if (value === 'Y') {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});

addressDialogTpl = Hbs.compile($('#address-dialog-tpl').html());
addressTpl = Hbs.compile($('#address-list-tpl').html());

// address dialog 数据验证
function validateAddress($el) {
    var field = {
        name: [
            {
                noEmpty: true,
                err: '收货人不能为空'
            },
            {
                regx: /[\u4e00-\u9fa5a-zA-Z\d]{2,12}/,
                err: '请输入2-12个汉字、英文或数字'
            }
        ],
        detail: [
            {
                noEmpty: true,
                err: '详细地址不能为空'
            },
            {
                regx: /[\u4e00-\u9fa5a-zA-Z\d#-()]+/,
                err: '只能包含数字、字母、汉字、#、-、()及其组合'
            }
        ],
        mobile: [
            {
                noEmpty: true,
                err: '手机号码不能为空'
            },
            {
                regx: /\d+/,
                err: '手机号码格式不正确'
            }
        ],
        phone: [
            {
                regx: /[\d-]+/,
                err: '只能包含数字、-组合',
                skipWhenEmpty: true
            }
        ]
    };

    var key,
        $cur,
        cur,
        vaKey,
        vaRegx;

    var pass = true;

    for (key in field) {
        if (field.hasOwnProperty(key)) {
            $cur = $el.find('.address-' + key);
            cur = $cur.val();

            // 按顺序去验证对应filed的值
            for (vaKey = 0; vaKey < field[key].length; vaKey++) {
                vaRegx = field[key][vaKey];

                // 非空验证、非空下正则验证、其他正则验证
                if ((vaRegx.noEmpty && cur === '') || (vaRegx.regx &&
                    (vaRegx.skipWhenEmpty ? !(cur === '' || vaRegx.regx.test(cur)) : !vaRegx.regx.test(cur))
                )) {
                    pass = false;
                    $cur.siblings('.error-tips').find('em').text(vaRegx.err).end().removeClass('hide');
                    break;
                }
            }
        }
    }

    return pass;
}

// 更新收货信息:姓名,手机号码,区域,详细
function receiver(ad) {
    $receiver.html(ad.consignee + ' ' + ad.mobile + ' ' + ad.area + ' ' + ad.address);
}

// 地址弹窗Factory
function addressDialogFactory(opt, $the) {
    var address = new Dialog({
        closeIcon: false,
        className: 'address',
        content: addressDialogTpl(opt),
        btns: [
            {
                id: 'save-address',
                btnClass: ['save-address'],
                name: '保存',
                cb: function() {
                    var $el = address.$el,
                        consignee,
                        detail,
                        mobile,
                        phone,
                        areaCode;

                    // 验证输入
                    if (validateAddress(address.$el)) {

                        // form value
                        consignee = $el.find('.address-name').val();
                        detail = $el.find('.address-detail').val();
                        mobile = $el.find('.address-mobile').val();
                        phone = $el.find('.address-phone').val();
                        areaCode = $el.address.getAreaIds().split(',')[2];

                        if (opt && opt.id) {

                            // update
                            $.ajax({
                                type: 'POST',
                                url: '/me/address/update',
                                data: {
                                    id: opt.id,
                                    uid: '8050484', // todo
                                    consignee: consignee,
                                    address: detail,
                                    mobile: mobile,
                                    phone: phone,
                                    'area_code': areaCode // eslint-disable-line
                                }
                            }).then(function(data) {
                                var updated;

                                if (data.code === 200) {
                                    updated = {
                                        consignee: consignee,
                                        address: detail,
                                        mobile: mobile,
                                        phone: phone,
                                        area_code: data.data.area_code, // eslint-disable-line
                                        id: opt.id,
                                        focus: $the.hasClass('focus'),
                                        area: $el.address.getAreaLabels().replace(/,/g, ' ')
                                    };

                                    $the.before(addressTpl({
                                        address: [updated]
                                    }));

                                    // 如果当前地址正在被使用,则更新收货信息
                                    if ($the.hasClass('focus')) {
                                        receiver(updated);
                                    }

                                    $the.remove();
                                    address.close();
                                }
                            });
                        } else {

                            // add
                            $.ajax({
                                type: 'POST',
                                url: '/me/address/add',
                                data: {
                                    uid: '8050484', // todo
                                    consignee: consignee,
                                    address: detail,
                                    mobile: mobile,
                                    phone: phone,
                                    'area_code': areaCode, // eslint-disable-line
                                    init: opt.init
                                }
                            }).then(function(data) {
                                var the;

                                if (data.code === 200) {
                                    the = $.extend(data.data, {
                                        focus: true
                                    });

                                    $('.address.focus').removeClass('focus');

                                    $('#address-list').prepend(addressTpl({
                                        address: [the]
                                    }));

                                    // 新地址默认使用,更新收货信息
                                    receiver(the);

                                    address.close();
                                }
                            });
                        }
                    }
                }
            },
            {
                id: 'cancel-address',
                btnClass: ['cancel-address', 'white'],
                name: '取消',
                cb: function() {
                    address.close();
                }
            }
        ]
    });

    return address;
}

/**
 * 初始化弹窗内容
 * @param $el dialog的jquery对象
 * @param areaCode 区码,初始化选择区域的组件
 */
function initAddressContent($el, areaCode) {

    // 初始化地址组件/将组件attr到$el方便操作
    $el.address = cascadingAddress({
        el: '#address'
    });

    if (areaCode) {
        $el.address.setAddress(areaCode + ''); // need convert to string
    }
}

/**
 * 新增地址
 * @param isInit Boolean 是否地址列表无地址(首次添加不显示取消按钮)
 */
function newAddress(isInit) {
    var address;

    address = addressDialogFactory();

    if (isInit) {
        address.$el.addClass('is-init');
    }

    initAddressContent(address.$el);

    address.show();
}

// 显示全部地址
$('.address-all').click(function() {
    $(this).siblings('.address-list').removeClass('shrink').end().addClass('vhide');
});

// 新增地址
$('.new-address').click(newAddress);

$('.address-list').on('click', '.address', function() {

    // 地址切换
    var $this = $(this);

    if ($this.hasClass('focus')) {
        return;
    }

    $this.addClass('focus');
    $this.siblings('.focus').removeClass('focus');

    // 切换地址后切换收货信息
    receiver({
        consignee: $this.data('name'),
        area: $this.data('area'),
        mobile: $this.data('mobile'),
        address: $this.data('address')
    });
}).on('click', '.modify', function(e) {


    // 修改地址
    var $this = $(this).closest('.address');
    var areaCode = $this.data('areacode');
    var address = addressDialogFactory({
        updateAddress: true,
        id: $this.data('id'),
        name: $this.data('name'),
        mobile: $this.data('mobile'),
        phone: $this.data('phone'),
        areacode: areaCode,
        detail: $this.data('address')
    }, $this);

    initAddressContent(address.$el, areaCode);

    address.show();

    e.stopPropagation();
}).on('click', '.delete', function(e) {

    // 删除地址
    var $this = $(this).closest('.address');

    var delConfirm = new Confirm({
        className: 'address-confirm-dialog',
        content: '<p class="main">删除地址</p><p class="sub">您确定要删除该收货地址吗?</p>',
        cb: function() {

            // 确认删除,do something
            $.ajax({
                type: 'POST',
                url: '/me/address/del',
                data: {
                    uid: '8050484',
                    id: $this.data('id')
                }
            }).then(function(data) {
                if (data.code === 200) {

                    // 若当前选中,则移除后选中默认地址
                    if ($this.hasClass('focus')) {
                        $this.siblings('.default').addClass('focus');
                    }
                    $this.remove();
                    delConfirm.close();
                }
            });
        }
    }).show();

    e.stopPropagation();
}).on('click', '.set-default', function(e) {

    // 设置为默认地址
    var $this = $(this).closest('.address');

    $.ajax({
        type: 'POST',
        url: '/me/address/default',
        data: {
            uid: '8050484',
            id: $this.data('id')
        }
    }).then(function(data) {
        if (data.code === 200) {

            // 切换default和focus状态
            $this.addClass('default focus');
            $this.siblings('.default, .focus').removeClass('default focus');
        }
    });
    e.stopPropagation();
});

// 页面加载时请求地址列表,若有则展示列表;若无则直接显示新建弹窗并不可被关闭
$.ajax({
    url: '/me/address/list'
}).then(function(data) {
    var list;

    if (data && data.code === 200) {
        list = data.data;
        if (list.length === 0) {

            // new address
            newAddress(true);
        } else {
            $('#address-list').append(addressTpl({
                address: data.data
            }));

            // 填收货人信息
            receiver(data.data[0]);
        }
    }
});