address.js 12.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
/**
 * 订单结算页
 * @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 stringHandle = require('../../common/stringHandle');

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

var $addrWrap = $('#addr-list'),
    $deliveryAddr = $('#delivery-detail'),

    // $payType2 = $('#pay-type2'),
    $supportWay2 = $('#support-way2');
var csrfToken = $('input[name=_csrf]').val();

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

var addrList = {},
    addrDefault = '';

var addrSelect;

function handleAreaText(areaInfo) {
    var maxLength = 30;
    var aList, tlen = 0;

    if (areaInfo.length > maxLength) {
        aList = areaInfo.split(' ');

        if (aList[3] && aList[3].length) {
            tlen = aList[3].length;
        }

        return areaInfo.substr(0, maxLength - tlen - 2) + '...' + (aList[3] || '');
    }

    return areaInfo;
}

// 获取地址数据
$('.addr-item').each(function() {
    var data = $(this).data();

    if (data.id) {
        if (data.area) {
            data.areaText = data.area.split(' ').join('/');
            data.areaShow = handleAreaText(data.area);

            if (data.area !== data.areaShow) {
                $(this).find('.area').text(data.areaShow);
            }
        }
        addrList[data.id] = data;

        if (data['default']) { // eslint-disable-line
            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($('<div/>').text($this.val()).html());
        }
    });

    data.areaCode = area.val();

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

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

    return data;
};

function syncShowMoreBtn() {
    setTimeout(function() {
        if ($addrWrap.children().length > 4) {
            $addrWrap.addClass('more');
        } else {
            $addrWrap.removeClass('more');
        }
    }, 0);
}

// 地址校验,支持单个字段与多字段
function validateAddress(data) {
    var regx = {
            consignee: /^([\u4e00-\u9fa5\w*]{1,20})$/,
            areaCode: /^[0-9]{6,9}$/,
            mobile: /^\d{3}(\d{4}|\*{4})\d{4}$/, // 手机号11位校验 by 新飞 2017.7.11
            phone: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/,
            address: /^[a-zA-Z0-9-#()()\u4e00-\u9fa5]+$/
        },
        pass = true,
        i;

    data = data || {};
    for (i in data) {
        if (data.hasOwnProperty(i)) {
            if (regx[i] && !regx[i].test(data[i])) {
                pass = false;
            }
            if (i === 'consignee' && stringHandle.chinese2(data[i]) > 20) {
                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 (stringHandle.chinese2(val) > 20) {
            tip = '收货人姓名最多支持20个字符';
        } else if (!validateAddress({consignee: val})) {
            tip = '收货人姓名不支持特殊符号';
        }
        $this.siblings('.caveat-tip').text(tip);
    }).on('change', 'input[name="address"]', function() {
        var $this = $(this);
        var val = $.trim($this.val()),
            tip = '';

        if (!val) {
            tip = '详细地址不能为空';
        }

        if (!validateAddress({address: 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,
            _csrf: csrfToken
        }
    }).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;

        setTimeout(function() {
            // 触发支付方式2(货到付款)是否支持状态改变
            // $payType2.val(data.cashdelivery ? 1 : 0).change(); // 5.4.1版本与线上逻辑保持一致,故注释

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

        _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,
            areaShow: handleAreaText(reqData.area),
            areaText: reqData.areaText,
            address: reqData.address,
            mobile: reqData.mobile,
            code: reqData.areaCode,
            phone: reqData.phone,
            delivery: data.is_delivery === 'Y',
            cashdelivery: data.is_cash_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,
            areaShow: handleAreaText(reqData.area),
            areaText: data.area.split(' ').join('/'),
            address: data.address,
            mobile: data.mobile,
            code: data.area_code,
            phone: data.phone,
            delivery: data.is_delivery === 'Y',
            cashdelivery: data.is_cash_delivery === 'Y'
        };

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

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

        syncShowMoreBtn();

        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;
                }

                data._csrf = csrfToken;

                $.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; // eslint-disable-line
        }
        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,
                    _csrf: csrfToken
                }
            }).then(function(data) {
                if (data.code === 200) {
                    $item.remove();
                    diaCf.close();
                    syncShowMoreBtn();
                }
            });
        }
    }).show();
});

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

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

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

syncShowMoreBtn();
setShowDeliveryAddr();

exports.area = area;

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