cart-helper.js 24 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 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
/**
 * Created by yoho on 2016-12-21.
 */
'use strict';

const _ = require('lodash');
const helpers = global.yoho.helpers;
const md5 = require('md5');
const logger = global.yoho.logger;

const PROMOTION_TYPE_TAG_MAP = {
    Cashreduce: '满减',         // 满减
    Degressdiscount: '折扣',    // 分件折扣
    Cheapestfree: '满减',       // 满X免1
    Discount: '折扣',           // 打折
    Gift: '赠品',
    Needpaygift: '加价购',
    SpecifiedAmount: '满减',     // X件X元
    FreeShippingCost: '免运费',
    VipFreeShippingCost: '免运费'
};

const GOODS_TYPE_TAG_MAP = {
    gift: '赠品',
    price_gift: '加价购'
};

/**
 * 从用户加入购物车的COOKIE取出购物车凭证
 */
const getShoppingKeyByCookie = (req) => {

    return req.cookies._SPK || '';
};

/**
 * 转换价格
 *
 * @param float|string $price 价格
 * @return float|string 转换之后的价格
 */
const transPrice = (price) => {
    return price ? (price * 1).toFixed(2) : '0.00';
};

const identIconReplace = (ret) => {
    let repstr = '<span style=\'color:#ff575c\'>$&</span>';

    return ret && ret.replace(/¥/g, '¥').replace(/\d件/g, repstr).replace([.0-9]*元/g, repstr) || '';
};

/**
 * 生成公开的TOKEN凭证
 *
 * @param string $string 字符串
 * @return string
 */
const makeToken = (str) => {
    return md5(md5(str + '#@!@#'));
};

/**
 * cookie cart-del-list 的数据操作
 * @param req
 * @param res
 * @param addsStr 向删除列表中加入数据
 * @param delId 删除列表中移除某个 id 的产品
 */
const getCartDelList = (req, res, addsStr, delSkuId) => {

    let cartDelListStr = req.cookies['cart-del-list'] || '';
    let isMod = false;
    let cookieDelStr = '';

    try {
        let cartDelList = cartDelListStr ? JSON.parse(cartDelListStr) : [];
        let addList = addsStr ? JSON.parse(addsStr) : null;

        // 追加
        if (addList && addList.length && _.isArray(cartDelList)) {
            isMod = true;
            cartDelList = cartDelList.concat(addList);
        }

        if (delSkuId) {
            isMod = true;
            _.remove(cartDelList, it => {
                return Number(it.productSku) === Number(delSkuId);
            });
        }

        if (isMod) {

            if (cartDelList && cartDelList.length > 0) {
                cookieDelStr = JSON.stringify(cartDelList);
            }

            res.cookie('cart-del-list', cookieDelStr, {
                domain: '.yohobuy.com',
                path: '/'
            });
        }
        return cartDelList;
    } catch (err) {
        logger.error(err);
    }

    return null;
};

/**
 * 购物车商品
 * @param array cartGoods 购物车商品列表
 * @param bool isAdvanceCart 是否是预售购物车(和上市期有关)
 * @param bool inValid 是否是不可用商品(失效商品),默认不是(有效商品)
 * @param bool isOffShelves 是否卖光了, 默认否
 * @param array analysis 第三方数据分析用的
 * @return array 处理之后的购物车商品数据
 */
const formatCartGoods = (cartGoods, isAdvanceCart, inValid, isOffShelves, analysis) => {

    return _.map(cartGoods, (it) => {
        it.last_vip_price = transPrice(it.last_vip_price);
        it.sales_price = transPrice(it.sales_price);
        it.last_price = transPrice(it.last_price);

        let goods = {
            id: it.product_sku,
            skn: it.product_skn,
            pid: it.product_id,
            brandId: it.brand_id,
            isChecked: it.selected === 'Y',
            productTitle: it.product_name,
            imgCover: it.goods_images ? helpers.image(it.goods_images, 64, 88) : '',
            productColor: it.factory_goods_name,
            productSize: it.size_name,
            productPrice: it.sales_price,
            productNum: Number(it.buy_number),
            storageNum: Number(it.storage_number),
            isSoldOut: parseInt(it.storage_number, 10) === 0 || parseInt(it.off_shelves, 10) === 1, // 已售罄
            isVipPrice: it.last_vip_price < it.sales_price && it.discount_tag === 'V',
            isStuPrice: it.last_vip_price < it.sales_price && it.discount_tag === 'S',
            yohoIcon: Number(it.get_yoho_coin) || 0,
            productSubtotal: transPrice(it.last_vip_price * it.buy_number),
            promotionId: it.promotion_id || 0,
            isLimitSkn: it.is_limit_skn === 'Y',  // is_limit_skn=Y 不支持7天无理由退货
            isAdvance: isAdvanceCart
        };

        // 划线的价格
        if (it.last_vip_price < it.sales_price) {
            goods.productPrice = it.last_vip_price;
            goods.linePrice = it.sales_price; // 划线的价格
        }

        if (it.min_buy_number) {
            goods.minBuyNumber = Number(it.min_buy_number);

            if (goods.minBuyNumber > 1) {
                goods.tipMessage = goods.minBuyNumber + '件起购';
            }
        }

        // 已下架
        if (isOffShelves) {
            goods.isTipNoStore = true;
            goods.tipMessage = '库存不足';
            goods.isOffShelve = true;
        } else if (!inValid) {  // 有效
            if (goods.productNum > goods.storageNum) {
                goods.isTipNoStore = true; // 是否在结算时候显示库存不足
                goods.tipMessage = '库存不足';
            } else if (goods.storageNum <= 3) {
                goods.tipMessage = '仅剩' + goods.storageNum + '件';
            }
        } else { // 失效商品
            goods.inValid = true;
        }

        // advanceBuy=>是否加价购,soldOut=>失效商品;
        if (!it.goods_type) {
            goods.inValid = true;
        } else if (it.goods_type === 'gift') {  // gift=>是否赠品    && it.isAdvanceBuy
            goods.isGift = true;
            goods.productPrice = it.last_price;
            goods.linePrice = it.sales_price; // 划线的价格
            goods.productSubtotal = it.subtotal ? transPrice(it.subtotal) : goods.productPrice;
        } else if (it.goods_type === 'price_gift') { // price_gift=>是否加价购
            goods.isPriceGift = true;
            goods.productPrice = it.last_price;
            goods.linePrice = it.sales_price; // 划线的价格
            goods.productSubtotal = it.subtotal ? transPrice(it.subtotal) : goods.productPrice;
        } else if (it.real_price === 0) {    // 免单
            goods.productPrice = it.sales_price;
            goods.xForOne = true;

            // 分析用: 商品ID列表
            if (_.isArray(_.get(analysis, 'ids'))) {
                analysis.ids.push(it.product_skn);
            }

            // 分析用: CRITEO
            if (_.isArray(_.get(analysis, 'criteo'))) {
                analysis.criteo.push({
                    id: it.product_skn,
                    quantity: Number(it.buy_number),
                    price: it.last_vip_price
                });
            }
        } else {
            // 分析用: 商品ID列表
            if (_.isArray(_.get(analysis, 'ids'))) {
                analysis.ids.push(it.product_skn);
            }

            // 分析用: CRITEO
            if (_.isArray(_.get(analysis, 'criteo'))) {
                analysis.criteo.push({
                    id: it.product_skn,
                    quantity: Number(it.buy_number),
                    price: it.last_vip_price
                });
            }
        }

        goods.tag = GOODS_TYPE_TAG_MAP[it.goods_type];

        // 商品类型:预售或普通
        goods.goodsType = isAdvanceCart ? 'advance' : 'ordinary';

        // 上市期
        if (isAdvanceCart && it.expect_arrival_time) {
            goods.preSellDate = it.expect_arrival_time;
        }

        // 商品链接
        goods.link = helpers.getUrlBySkc(it.product_id, it.goods_id, it.cn_alphabet);

        return goods;
    });
};

/**
 * 购物车统计
 */
const formatShoppingCartData = (sc) => {

    return {
        discountAmount: sc.discount_amount,     // 活动价
        fastShoppingCost: sc.fast_shopping_cost,
        gainYohoCoin: sc.gain_yoho_coin,        // 获赠有货币个数
        goodsCount: sc.goods_count,
        isMultiPackage: sc.is_multi_package,
        lastOrderAmount: (parseFloat(sc.last_order_amount)).toFixed(2),      // 商品金额总计
        orderAmount: sc.order_amount,   // 商品总价
        //  package_list,[],
        promotionFormula: sc.promotion_formula,
        promotionFormulaList: _.map(sc.promotion_formula_list, it => {
            return {
                promotion: it.promotion,
                promotionAmount: it.promotion_amount
            };
        }),
        selectedGoodsCount: sc.selected_goods_count,
        shippingCost: sc.shipping_cost,
        strDiscountAmount: sc.str_discount_amount,
        strOrderAmount: sc.str_order_amount
    };
};

/**
 * 全局优惠头部信息
 */
const formatPromotionInfos = (infoList) => {
    return _.map(infoList, it => {
        return {
            cutdownAmount: it.cutdown_amount,
            promotionId: it.promotion_id,
            promotionDesc: identIconReplace(it.promotion_title),
            promotionType: it.promotion_type,
            tag: PROMOTION_TYPE_TAG_MAP[it.promotion_type]
        };
    });
};

/**
 * 过时商品
 * offShelvesList 过时商品列表
 *
 */
const formatOffShelves = (offShelvesList, isAdvanceCart, analysis) => {
    return formatCartGoods(offShelvesList, isAdvanceCart, false, true, analysis);
};

/**
 * 售罄商品
 */
const formatSoldOuts = (soldOutsList, isAdvanceCart, analysis) => {
    return formatCartGoods(soldOutsList, isAdvanceCart, false, false, analysis);
};

/**
 * 格式化单个加价购商品
 */
const formatPriceGiftOne = (it) => {

    let gift = {
        // isShowGift: isGift, // 控制是否显示赠品
        // isFold: true, // 控制是否[展开]
        promotionId: it.promotion_id,
        promotionTitle: it.promotion_title,
        promotionDesc: identIconReplace(it.promotion_desc), // + '(注:您看到的商品可能因为下单时间差已售完)',  // subjoinType
        maxSelectNumber: it.max_select_number,
        promotionType: it.promotion_type,
        tag: PROMOTION_TYPE_TAG_MAP[it.promotion_type],
        isGift: it.promotion_type === 'Gift',
        isPriceGift: it.promotion_type === 'Needpaygift'
    };

    gift.goodsList = _.map(it.goods_list, (g) => {

        let goods = {
            id: g.product_id,
            skn: g.product_skn,
            subjoinTitle: g.product_name,
            imgCover: g.goods_images ? helpers.image(g.goods_images, 65, 90) : '',
            subjoinPrice: transPrice(g.last_price),
            marketPrice: gift.isGift ? '' : transPrice(g.market_price),
            yohoIcon: 0,
            isGift: gift.isGift,
            isPriceGift: gift.isPriceGift
        };

        // 商品链接
        if (g.goods_id) {
            // let cnAlphaBet = g.cn_alphabet ? g.cn_alphabet : md5(g.product_name);
            goods.subjoinLink = helpers.getUrlBySkc(g.product_id, g.goods_id, g.cn_alphabet);
        } else {
            let uri = `/product/show_${g.product_id}_${g.product_skn}/${makeToken(g.product_skn)}.html`;

            goods.subjoinLink = helpers.urlFormat(uri, null, 'item');
        }

        return goods;
    });

    return gift;
};

/**
 * 可选加价购
 * isGift 是否是赠品:true-赠品
 */
const formatPriceGifts = (giftList) => {

    return _.map(giftList, (it) => {
        return formatPriceGiftOne(it);
    });
};

/**
 * 购物车赠品
 */
/* const formatGifts = (giftList) => {
    return formatPriceGifts(giftList);
};*/

const checkGoodsIsSel = (goodsList, promotionId, selectedGiftsList) => {

    return _.map(goodsList, goods => {

        _.forEach((selectedGiftsList || []), gift => {

            if (goods.id === gift.id && promotionId === gift.promotionId) {
                goods.isCheckedGift = true;
                goods.checkedGiftPid = gift.pid;
                goods.checkedGiftSkn = gift.skn;
                return;
            }
        });

        return goods;
    });
};

/**
 * 格式化promotion 里的数据
 */
const formatPromotion = (it, selectedGiftsList) => {

    // "status": 0, // 状态 0 未满足 10 已满足 [20 售光 30 更换 ]
    let status = parseInt(it.status, 10);
    let tsPromotionIds = (it.ts_promotion_ids && it.ts_promotion_ids.join(',')) || it.promotion_id || '';
    let info = {
        status: status,
        conditionUnit: it.condition_unit,   // 0满足,1 件,2金额
        conditionValue: it.condition_value,
        giftPrice: it.gift_price,   // 赠品或加价购商品价格
        giftGoodsList: formatCartGoods(it.gift_goods_List),  // 可供选择的赠品或加价购商品列表
        promotionId: tsPromotionIds, // 促销id
        promotionDesc: identIconReplace(it.promotion_desc),
        promotionType: it.promotion_type,  // 促销类型
        // list.yohobuy.com?psp_id=10408
        promotionPageUrl: helpers.urlFormat('', {psp_id: tsPromotionIds}, 'list'),
        tag: PROMOTION_TYPE_TAG_MAP[it.promotion_type],

        isGift: it.promotion_type === 'Gift',
        isPriceGift: it.promotion_type === 'Needpaygift',
        isNotReach: status === 0,   // 未满足
        isReach: status === 10 || status === 30 || status === 20,     // 满足条件
        isEmpty: status === 20,     // 已售完
        isSelected: status === 30   // 已选择,可更换
    };

    // 判断赠品/加价购商品,是否被选中
    info.giftGoodsList = checkGoodsIsSel(info.giftGoodsList, info.promotionId, selectedGiftsList);

    if (info.giftGoodsList) {
        info.giftGoodsListStr = JSON.stringify(info.giftGoodsList);
    }

    return info;
};

/**
 * 优惠池头部优惠信息列表
 */
const formatPoolPromotionInfos = (infoList, selectedGiftsList) => {

    return _.map(infoList, it => {
        return formatPromotion(it, selectedGiftsList);
    });
};

/**
 * 格式化子优惠池信息,返回商品列表,子优惠列表放在每个商品中
 */
const formatSubPromotionPools = (pools, selectedGiftsList, isAdvance, analysis) => {

    let goodsListPool = _.map(pools, p => {
        let pool = {
            poolType: p.pool_type,
            isBrandGroup: Number(p.pool_type) === 1,
            goodsList: formatCartGoods(p.goods_list, isAdvance, false, false, analysis),
            promotionInfos: formatPoolPromotionInfos(p.promotion_list, selectedGiftsList)
        };

        let goodsList = pool.goodsList;

        if (goodsList && goodsList.length) {
            pool.goodsList = _.map(goodsList, g => {
                g.promotionInfos = pool.promotionInfos;
                return g;
            });
        }

        return pool;
    });

    // [ [goods, goods], [goods, ..], [] ] => [goods, goods ]
    // return _.flatten(goodsListPool);

    return goodsListPool;
};

const _disablePools = (goodsList, isCheck, isBtnDisab) => {
    return _.map(goodsList, p => {

        return Object.assign(p, {isCheck: isCheck, isBtnDisab: isBtnDisab});
    });
};

/**
 * giftsList, priceGifts 已选择的赠品和加价购,判断可选的赠品和加价购是否被选中
 * 优惠池
 */
const formatPromotionPools = (pools, selectedGiftsList, isAdvance, analysis) => {
    return _.map(pools, p => {
        p.pool_type = parseInt(p.pool_type, 10);

        let pool = {
            poolId: p.pool_id,
            poolTitle: p.pool_title,
            isChecked: p.selected === 'Y',
            batchNo: p.pool_batch_no,
            productNum: parseInt(p.pool_buy_number, 10),
            storageNum: parseInt(p.pool_storage_number, 10),
            poolType: p.pool_type,
            isBrandGroup: p.pool_type === 1,
            goodsList: formatCartGoods(p.goods_list, isAdvance, false, false, analysis),
            promotionInfos: formatPoolPromotionInfos(p.promotion_list, selectedGiftsList)
        };

        if (p.sub_pool) {
            pool.subs = formatSubPromotionPools(p.sub_pool, selectedGiftsList, isAdvance, analysis);

            /*
            if (_.isArray(goodsWithPromotion) && goodsWithPromotion.length) {
                pool.goodsList = goodsWithPromotion.concat(pool.goodsList);
            }*/
        }

        // 套餐不须要列表中有删除、收藏按钮
        if (p.pool_type === 3) {
            pool.goodsList = _disablePools(pool.goodsList, true, true);
            pool.minBuyNumber = 1;
        }

        return pool;
    });
};

// 失效处理
const formatSoldOutPools = (pools, selectedGiftsList, isAdvance, analysis) => {
    return _.map(pools, p => {
        p.pool_type = parseInt(p.pool_type, 10);

        let pool = {
            poolId: p.pool_id,
            poolTitle: p.pool_title,
            isChecked: p.selected === 'Y',
            batchNo: p.pool_batch_no,
            productNum: parseInt(p.pool_buy_number, 10),
            storageNum: parseInt(p.pool_storage_number, 10),
            poolType: p.pool_type,
            isBrandGroup: p.pool_type === 1,
            goodsList: formatCartGoods(p.goods_list, isAdvance, true, false, analysis),
            promotionInfos: formatPoolPromotionInfos(p.promotion_list, selectedGiftsList)
        };

        // 套餐不须要列表中有删除、收藏按钮
        if (p.pool_type === 3) {
            pool.goodsList = _disablePools(pool.goodsList, true, true);
            pool.minBuyNumber = 1;
            pool.inValid = true;
        }

        return pool;
    });
};

const formatCart = (cartDataRet, uid, shoppingKey, cartDelList) => {

    let analysisData = {
        ids: [],
        criteo: []
    };  // 存放分析用的数据

    let result = {
        isEmpty: false,
        isLogin: !!uid,
        searchUrl: helpers.urlFormat('', null, 'search'),   // 搜索链接(再逛逛)
        listUrl: helpers.urlFormat('', null, 'list'),
        viewOrderUrl: helpers.urlFormat('/home/orders', {
            t: new Date().getTime()
        })
    };

    // 未登录
    if (!uid) {
        result.loginUrl = helpers.urlFormat('/signin.html', {
            refer: helpers.urlFormat('/cart/cart')
        });
    }

    // 调用接口,获取购物车数据
    // let cartDataRet = yield cartApi.cartData(uid, shoppingKey);
    let cartData = cartDataRet && cartDataRet.data;
    let advCartData = _.get(cartData, 'advance_cart_data');
    let ordCartData = _.get(cartData, 'ordinary_cart_data');

    // 移除的商品列表
    result.deleteShop = cartDelList;

    // 接口异常时,购物车置为空
    if (!cartData) {
        result.isEmpty = true;

        // UdpLog::info('【购物车】校验参数传递auth', 'uid:' . $uid . 'shoppingKey:' . $shoppingKey);
        return result;
    }

    result.advanceCart = {
        // 未参加活动的商品
        // goodsList: chelper.formatCartGoods(_.get(advCartData, 'goods_list'), true, false, false, analysisData),
        pools: formatPromotionPools(_.get(advCartData, 'goods_pool_list'), null, true, analysisData),
        offShelves: formatOffShelves(_.get(advCartData, 'off_shelves_goods_list'), true, analysisData),
        soldOuts: formatSoldOuts(_.get(advCartData, 'sold_out_goods_list'), true, analysisData),
        promotionInfos: formatPromotionInfos(_.get(advCartData, 'promotion_info')),
        stat: formatShoppingCartData(_.get(advCartData, 'shopping_cart_data')),
        ensureUrl: helpers.urlFormat('/cart/ensure', {
            type: 2
        })
    };

    // let giftsList = formatPriceGifts(_.get(ordCartData, 'gift_list'));
    // let priceGifts = formatPriceGifts(_.get(ordCartData, 'price_gift'));
    let goodsList = formatCartGoods(_.get(ordCartData, 'goods_list'), false, false, false, analysisData);

    result.ordinaryCart = {
        // 全场可选的赠品
        // gifts: giftsList,   // chelper.formatGifts(_.get(ordCartData, 'gift_list')),
        // 全场可选的加价购商品列表
        // priceGifts: priceGifts, // chelper.formatPriceGifts(_.get(ordCartData, 'price_gift')),
        giftsPromotionInfos: formatPoolPromotionInfos(_.get(ordCartData, 'g_gift_list')),
        priceGiftsPromotionInfos: formatPoolPromotionInfos(_.get(ordCartData, 'g_price_gift_list')),

        // 已选择的全场加价购和赠品
        goodsList: goodsList,

        pools: formatPromotionPools(_.get(ordCartData, 'goods_pool_list'), goodsList, false, analysisData),

        offShelves: formatOffShelves(_.get(ordCartData, 'off_shelves_goods_list'), false, analysisData),
        soldOuts: formatSoldOuts(_.get(ordCartData, 'sold_out_goods_list'), false, analysisData),
        soldOutPools: formatSoldOutPools(_.get(ordCartData, 'sold_out_goods_pool'), goodsList, false, analysisData),

        promotionInfos: formatPromotionInfos(_.get(ordCartData, 'promotion_info'), goodsList),
        stat: formatShoppingCartData(_.get(ordCartData, 'shopping_cart_data')),
        ensureUrl: helpers.urlFormat('/cart/ensure'),

        // 免运费提示
        tips: _.get(ordCartData, 'shipping_cost_prompt.shipping_cost_tips', ''),

        // 低档赠品
        matchGiftIds: _.get(ordCartData, 'match_gift_ids', []).join(',')
    };

    let advStat = result.advanceCart.stat;
    let ordStat = result.ordinaryCart.stat;

    // 为空
    if (!_.get(advStat, 'goodsCount', 0)) {
        result.advanceCart = false;
    }

    if (!_.get(ordStat, 'goodsCount', 0)) {
        result.ordinaryCart = false;
    }

    if (!result.advanceCart && !result.ordinaryCart) {
        result.isEmpty = true;
        return result;
    }

    if (_.get(result, 'ordinaryCart.promotionInfos')) {
        result.ordinaryCart.promotionInfos = _.filter(result.ordinaryCart.promotionInfos, pinfo => {
            return pinfo && pinfo.tag && Number(pinfo.promotionId) === 0;
        });
    }

    // promotionInfos,  gifts, priceGifts 放一起展示
    let hasGifts = _.get(result, 'ordinaryCart.giftsPromotionInfos') &&
        _.get(result, 'ordinaryCart.giftsPromotionInfos').length;
    let hasPrices = _.get(result, 'ordinaryCart.priceGiftsPromotionInfos') &&
        _.get(result, 'ordinaryCart.priceGiftsPromotionInfos').length;
    let hasPromo = _.get(result, 'ordinaryCart.promotionInfos') && _.get(result, 'ordinaryCart.promotionInfos').length;
    let orderAmount = (parseFloat(_.get(advStat, 'orderAmount', 0)) +
    parseFloat(_.get(ordStat, 'orderAmount', 0))).toFixed(2);
    let lastOrderAmount = (parseFloat(_.get(advStat, 'lastOrderAmount', 0)) +
    parseFloat(_.get(ordStat, 'lastOrderAmount', 0))).toFixed(2);

    if (result.ordinaryCart) {
        result.ordinaryCart.hasGlobalBlock = hasGifts || hasPrices || hasPromo;
    }
    result.stat = {
        orderAmount: orderAmount,
        lastOrderAmount: lastOrderAmount,
        discountAmount: (orderAmount - lastOrderAmount).toFixed(2),
        gainYohoCoin: parseFloat(_.get(advStat, 'gainYohoCoin', 0)) + parseFloat(_.get(ordStat, 'gainYohoCoin', 0)),
        goodsCount: _.get(advStat, 'goodsCount', 0) + _.get(ordStat, 'goodsCount', 0),
        selectedGoodsCount: _.get(advStat, 'selectedGoodsCount', 0) + _.get(ordStat, 'selectedGoodsCount', 0)
    };

    // 普通购物车和预售购物车都为空
    /* if (ordinaryCount === 0 && advanceCount === 0 && ordinarySoldOut && advanceSoldOut) {
     result.isEmpty = true;
     return result;
     }*/

    // 预售和普通都有商品
    if (result.advanceCart && _.get(result, 'advanceCart.stat.selectedGoodsCount') > 0 &&
        result.ordinaryCart && _.get(result, 'ordinaryCart.stat.selectedGoodsCount') > 0) {
        result.stat.mix = true;
    } else if (result.advanceCart && _.get(result, 'advanceCart.stat.selectedGoodsCount') > 0) {
        result.stat.ensureUrl = result.advanceCart.ensureUrl;
    } else if (result.ordinaryCart && _.get(result, 'ordinaryCart.stat.selectedGoodsCount') > 0) {
        result.stat.ensureUrl = result.ordinaryCart.ensureUrl;
    }

    Object.assign(result, {
        ids: _.isArray(analysisData.ids) ? analysisData.ids.join(',') : '',
        criteo: analysisData.criteo || ''
    });

    return result;
};

module.exports = {
    transPrice,
    getShoppingKeyByCookie,
    formatCartGoods,

    // formatGifts,
    formatPriceGiftOne,
    formatPriceGifts,
    formatShoppingCartData,
    formatPromotion,
    formatPromotionPools,
    formatPromotionInfos,
    formatOffShelves,
    formatSoldOuts,
    formatCart,

    getCartDelList
};