cart-service.js 26.8 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 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
/**
 * 商品详情models
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2016/5/6
 */

'use strict';

const Promise = require('bluebird');
const co = Promise.coroutine;
const _ = require('lodash');
const helpers = global.yoho.helpers;
const md5 = require('md5');

const ERROR_400_MESSAGE = '系统繁忙,请稍候再试!';
const productAPI = require('./product-api');
const cartApi = require('./cart-api');
const chelper = require('./cart-helper');

const _getProductIntroAsync = (productSkn) => {
    return co(function * () {
        let result = yield Promise.props({
            sizeInfo: productAPI.sizeInfoAsync(productSkn)
        });

        return result;
    })();
};

/**
 * 获得sku商品数据
 */
const _getSkuDataByProductBaseInfo = (data) => {
    let totalStorageNum = 0;
    let skuGoods = null;// sku商品
    let defaultImage = '';// 默认图
    let chooseSkuFlag = false; // 选中状态

    if (_.isEmpty(_.get(data, 'goods_list', []))) {
        return {
            totalStorageNum,
            skuGoods,
            defaultImage
        };
    }

    skuGoods = _.get(data, 'goods_list', []).reduce((acc, cur, pos)=> {

        // 如果status为0,即skc下架时就跳过该商品$value['status'] === 0
        let goodsGroup = {};

        if (_.isEmpty(cur.color_image)) {
            return acc;
        }

        if (cur.images_list) {
            // 商品列表
            goodsGroup.productSkc = cur.product_skc;
            goodsGroup.src = helpers.image(cur.color_image, 40, 40);
            goodsGroup.title = `${_.trim(data.product_name)} ${cur.color_name}`;
            goodsGroup.name = cur.factory_goods_name;
            goodsGroup.focus = false;
            goodsGroup.total = 0;
            goodsGroup.thumbs = [];
            goodsGroup.size = [];
        }

        _.get(cur, 'images_list', []).forEach((good) => {
            if (good.image_url) {
                goodsGroup.thumbs.push({
                    url: '',
                    shower: helpers.image(good.image_url, 420, 560),
                    img: helpers.image(good.image_url, 75, 100)
                });
            }
        });

        // 缩略图空,不显示
        if (_.isEmpty(goodsGroup.thumbs)) {
            return acc;
        }

        // 默认第一张图片
        if (pos === 0) {
            defaultImage = helpers.image(cur.color_image, 420, 560);
        }

        // 商品的尺码列表
        _.get(cur, 'size_list', []).forEach((size) => {
            if (data.attribute === 3) {
                // 虚拟商品,门票默认最大为4,
                size.storage_number = size.storage_number > 4 ? 4 : size.storage_number;
            }

            // 如果status为0,即skc下架时就跳过该商品
            if (cur.status === 0) {
                size.storage_number = 0;
            }

            goodsGroup.size.push({
                name: size.size_name,
                sku: size.product_sku,
                num: _.parseInt(size.storage_number),
                goodsId: size.size_id
            });

            // 单个sku商品的总数
            goodsGroup.total += _.parseInt(size.storage_number);

            if (goodsGroup.total > 0 && !chooseSkuFlag) { // 默认选中该sku商品
                goodsGroup.focus = true;
                chooseSkuFlag = true;// 选中sku商品
            }

            totalStorageNum += _.parseInt(size.storage_number);

        });

        acc.push(goodsGroup);
        return acc;
    }, []);

    if (!_.isEmpty(skuGoods) && !chooseSkuFlag) { // 没有选中一个sku商品,默认选中第一个sku商品
        _.head(skuGoods).focus = true;
    }

    return {
        defaultImage: defaultImage,
        skuGoods: skuGoods,
        totalStorageNum: totalStorageNum
    };
};

/**
 * 使sizeBoList id以 sizeAttributeBos id顺序一样
 * @param sizeInfoBo
 */
const _sizeInfoBoSort = (sizeInfoBo) => {
    if (!sizeInfoBo.sizeBoList || !sizeInfoBo.sizeAttributeBos) {
        return {};
    }

    _.get(sizeInfoBo, 'sizeBoList', []).forEach((sizeBoList, sizek)=> {
        let sortAttr = {};

        sizeBoList.sortAttributes.forEach(sortAttributes => {
            sortAttr[sortAttributes.id] = sortAttributes;
        });

        sizeInfoBo.sizeBoList[sizek].sortAttributes = sortAttr;
    });

    _.get(sizeInfoBo, 'sizeBoList', []).forEach((sizeBoList, sizek)=> {
        let sortAttr = [];

        sizeInfoBo.sizeAttributeBos.forEach(val => {
            if (sizeBoList.sortAttributes[val.id]) {
                sortAttr.push(sizeBoList.sortAttributes[val.id]);
            }
        });

        sizeInfoBo.sizeBoList[sizek].sortAttributes = sortAttr;

    });

    return sizeInfoBo;
};

/**
 * 获取尺寸信息
 * @param sizeInfo
 * @returns {{}}
 */
const _getSizeData = (sizeInfo) => {

    // 尺码信息
    if (!_.has(sizeInfo, 'sizeInfoBo')) {
        return {};
    }

    sizeInfo.sizeInfoBo = _sizeInfoBoSort(sizeInfo.sizeInfoBo);

    let boyReference = _.get(sizeInfo, 'productExtra.boyReference', false);
    let girlReference = _.get(sizeInfo, 'productExtra.girlReference', false);
    let gender = _.get(sizeInfo, 'productDescBo.gender', 3);
    let referenceName = (function() {
        if (gender === 3 && boyReference) {
            return '参考尺码(男)';
        } else if (gender === 3 && girlReference) {
            return '参考尺码(女)';
        } else {
            return '参考尺码';
        }
    }());

    // 判断是否显示参考尺码
    let showReference = (boyReference && _.get(sizeInfo, 'sizeInfoBo.sizeBoList[0].boyReferSize', false)) ||
        (girlReference && _.get(sizeInfo, 'sizeInfoBo.sizeBoList[0].girlReferSize', false));

    if (!_.has(sizeInfo, 'sizeInfoBo.sizeAttributeBos')) {
        return {};
    }

    // 尺码信息头部
    let size = {
        thead: [{name: '吊牌尺码', id: ''}],
        tbody: []
    };

    // 显示参考尺码
    if (showReference) {
        size.thead[1] = {name: referenceName, id: ''};
    }

    _.get(sizeInfo, 'sizeInfoBo.sizeAttributeBos', []).forEach((value) => {
        size.thead.push({
            name: value.attributeName || ' ',
            id: value.id
        });
    });

    _.get(sizeInfo, 'sizeInfoBo.sizeBoList', []).forEach((value) => {
        let sizes = [];

        // 吊牌尺码
        sizes.push(value.sizeName);

        // 判断是否显示参考尺码
        if (boyReference && (gender === 1 || gender === 3) && showReference) {
            sizes.push(_.get(value, 'boyReferSize.referenceName', ' '));
        } else if (girlReference && (gender === 2 || gender === 3) && showReference) {
            sizes.push(_.get(value, 'girlReferSize.referenceName', ' '));
        } else {
            if (size.thead[1] && showReference) {
                size.thead[1] = {};
            }
        }

        // 其他尺码信息
        _.get(value, 'sortAttributes', []).forEach(attr => {
            sizes.push(_.get(attr, 'sizeValue', ' '));
        });

        // 尺码信息
        size.tbody.push(sizes);
    });

    // 参考尺码为空
    if (_.isEmpty(size.thead[1]) && showReference) {
        // 移除这个值
        size.thead.splice(1, 1);
    }

    // 测量方式
    if (sizeInfo.sizeImage) {
        size.sizeImg = sizeInfo.sizeImage;
    }

    return size;
};

/**
 * 商品尺码信息
 *
 * @param productSkn
 * @param maxSortId
 * @return object
 */
const _getIntroInfo = (productSkn, additionalData)=> {
    if (!productSkn) {
        return {};
    }

    let sizeInfo = additionalData.sizeInfo;

    if (_.isEmpty(sizeInfo)) {
        return {};
    }

    let result = {};

    // 尺寸数据
    result.size = _getSizeData(sizeInfo);

    return result;
};

/**
 * 详情页数据格式化
 * @param origin Object 原始数据
 * @return result Object 格式化数据
 */
const _detailDataPkg = (origin) => {
    return co(function*() {
        if (_.isEmpty(origin) || _.isEmpty(origin)) {
            return {};
        }

        let result = {};
        let propOrigin = _.partial(_.get, origin);

        // 商品名称
        if (!propOrigin('product_name')) {
            return result;
        }

        result.name = propOrigin('product_name');
        result.skn = propOrigin('product_skn');
        result.productId = propOrigin('product_id');

        // 商品价格
        result.marketPrice = propOrigin('format_market_price');
        result.salePrice = propOrigin('format_sales_price');
        result.hasOtherPrice = true;

        if (result.salePrice === '0') {
            delete result.salePrice;
            result.hasOtherPrice = false;
        }

        // 上市期
        if (propOrigin('expect_arrival_time')) {
            result.arrivalDate = `${propOrigin('expect_arrival_time')}月`;
            result.presalePrice = propOrigin('format_sales_price');
            delete result.salePrice;
            result.hasOtherPrice = false;
        }

        // sku商品信息
        let skuData = _getSkuDataByProductBaseInfo(origin);

        // 商品购买状态
        let soldOut = !!(propOrigin('status') === 0 || skuData.totalStorageNum === 0);
        let virtualGoods = propOrigin('attribute') === 3; // 虚拟商品

        if (!soldOut && !virtualGoods) {
            result.addToCart = 1;
        }

        result.colors = skuData.skuGoods;

        return result;
    })();
};

/**
 *  获取某一个商品详情主页面
 */
const getProductInfoAsync = (pid) => {
    return co(function * () {
        if (!pid) {
            return {};
        }

        // 获取商品基本信息
        let productData = yield productAPI.getProductAsync(pid);

        if (_.isEmpty(productData.data)) {
            return Promise.reject({
                code: 404,
                message: 'app.product.data api wrong'
            });
        }

        let productSkn = _.get(productData, 'data.product_skn');
        let requestData = yield Promise.all([
            _getProductIntroAsync(productSkn),  // 商品详细介绍
            _detailDataPkg(productData.data)               // 商品详细价格
        ]);

        let productDescription = requestData[0];
        let productInfo = requestData[1];
        let intro = _getIntroInfo(productSkn, productDescription);

        return Object.assign(productInfo, intro);
    })();
};

const getCartData = (uid, shoppingKey, cartDelList) => {

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

    return co(function * () {
        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('/shopping/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');

        // 接口异常时,购物车置为空
        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),
            offShelves: chelper.formatOffShelves(_.get(advCartData, 'off_shelves_goods_list'), true, analysisData),
            soldOuts: chelper.formatSoldOuts(_.get(advCartData, 'sold_out_goods_list'), true, analysisData),
            stat: chelper.formatShoppingCartData(_.get(advCartData, 'shopping_cart_data'))
        };

        let giftsList = chelper.formatPriceGifts(_.get(ordCartData, 'gift_list'));
        let priceGifts = chelper.formatPriceGifts(_.get(ordCartData, 'price_gift'));
        let goodsList = chelper.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')),
            // 已选择的全场加价购和赠品
            goodsList: goodsList,

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

            offShelves: chelper.formatOffShelves(_.get(ordCartData, 'off_shelves_goods_list'), false, analysisData),
            soldOuts: chelper.formatSoldOuts(_.get(ordCartData, 'sold_out_goods_list'), false, analysisData),

            promotionInfos: chelper.formatPromotionInfos(_.get(ordCartData, 'promotion_info'), goodsList),
            stat: chelper.formatShoppingCartData(_.get(ordCartData, 'shopping_cart_data'))
        };

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

        // promotionInfos,  gifts, priceGifts 放一起展示
        let hasGifts = result.ordinaryCart.gifts && result.ordinaryCart.gifts.length;
        let hasPrices = result.ordinaryCart.priceGifts && result.ordinaryCart.priceGifts.length;
        let hasPromo = result.ordinaryCart.promotionInfos && result.ordinaryCart.promotionInfos.length;

        result.ordinaryCart.hasGlobalBlock = hasGifts || hasPrices || hasPromo;

        result.stat = {
            orderAmount: _.get(advStat, 'orderAmount', 0) + _.get(ordStat, 'orderAmount', 0),
            discountAmount: _.get(advStat, 'discountAmount', 0) + _.get(ordStat, 'discountAmount', 0),
            lastOrderAmount: _.get(advStat, 'lastOrderAmount', 0) + _.get(ordStat, 'lastOrderAmount', 0),
            gainYohoCoin: _.get(advStat, 'gainYohoCoin', 0) + _.get(ordStat, 'gainYohoCoin', 0),
            goodsCount: _.get(advStat, 'goodsCount', 0) + _.get(ordStat, 'goodsCount', 0),
            selectedGoodsCount: _.get(advStat, 'selectedGoodsCount', 0) + _.get(ordStat, 'selectedGoodsCount', 0)
        };

        /* 移除的商品列表 */
        if (cartDelList) {
            result.deleteShop = cartDelList;
        }

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

        return result;
    })().then(ret => {
        // 增加第三方分析用的数据
        // ret['ids'] = empty($analysisData['ids']) ? '' : implode(',', $analysisData['ids']);
        // $result['criteo'] = empty($analysisData['criteo']) ? "''" : json_encode($analysisData['criteo']);
        return Object.assign(ret, {
            ids: _.isArray(analysisData.ids) ? analysisData.ids.join(',') : '',
            criteo: analysisData.criteo || ''

            // empty($analysisData['criteo']) ? "''" : json_encode($analysisData['criteo']);
        });
    });
};

/**
 * 获取购物车总数
 *
 * @param int $uid 用户ID
 * @param string $shoppingKey 客户端购物标识
 * @return array
 */
const getCartCount = (uid, shoppingKey) => {
    return cartApi.cartCount(uid, shoppingKey);
};

/**
 * 加入购物车
 *
 * @param int $productSku 商品SKU
 * @param int $buyNumber 购买数量
 * @param int $goodsType 商品类型,0表示普通商品,1表示加价购商品
 * @param int $isEdit 是否是编辑商品SKU,0表示不是编辑
 * @param null|int $promotionId 促销id,默认null(加价购有关)
 * @param null|int $uid 用户UID,可以不传
 * @param string $shoppingKey 购物车在浏览器的唯一识别码,可以不传
 * @return array 加入购物车接口返回的数据
 */
const addToCart = (productSku, buyNumber, goodsType, isEdit, promotionId, uid, shoppingKey) => {

    return co(function * () {
        let result = {
            code: 400,
            message: ERROR_400_MESSAGE
        };

        if (!productSku) {
            return result;
        }

        let ret = yield cartApi.addToCart(productSku, buyNumber, goodsType, isEdit, promotionId, uid, shoppingKey);

        if (ret && ret.code) {
            result = ret;
        }

        /* if (empty($addCart) || (isset($addCart['code']) && $addCart['code'] !== 200) ) {
         UdpLog::info('【购物车】校验参数传递auth','productSku:'.$productSku.'buyNumber:'.$buyNumber.
         'goodsType:'.$goodsType,'isEdit:'.$isEdit.'promotionId:'.$promotionId.'uid:'.$uid.'shoppingKey:'.$shoppingKey);
         }*/

        return result;
    })();
};

/**
 * 购物车商品选择与取消接口返回的数据处理
 *
 * @param int $uid 用户ID
 * @param string $skuList 商品sku列表json格式, 如{"744403":1}
 * @param string $shoppingKey 未登录用户唯一识别码
 * @param bool hasPromotion 标识是不是有promotion_id参数, 后端会去调用不同的接口
 * @return array 处理之后的数据的数据
 */
const selectGoods = (uid, skuList, shoppingKey, hasPromotion) => {

    return co(function * () {
        let result = {
            code: 400,
            message: ERROR_400_MESSAGE
        };

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

        let select = yield cartApi.selectGoods(uid, skuList, shoppingKey, hasPromotion);

        if (select && select.code) {
            result = select;
        }/* else {
         UdpLog::info('【购物车】校验参数传递auth', 'uid:' . $uid . 'skuList:'
         . $skuList . 'shoppingKey:' . $shoppingKey . 'hasPromotion:' . $hasPromotion);
         }*/

        return result;
    })();
};

/**
 * 修改购物车商品数量
 *
 * @param int $uid 用户ID
 * @param string $sku 商品SKU
 * @param int $increaseNum 增加的数目
 * @param int $decreaseNum 减少的数目
 * @param string $shoppingKey 未登录用户唯一识别码
 * @return array 接口返回的数据
 */
const modifyProductNum = (uid, sku, increaseNum, decreaseNum, shoppingKey) => {

    return co(function * () {
        let result = {
            code: 400,
            message: ERROR_400_MESSAGE
        };

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

        let modify = yield cartApi.modifyProductNum(uid, sku, increaseNum, decreaseNum, shoppingKey);

        if (modify && modify.code) {
            result = modify;
        }/* else {
         UdpLog::info('【购物车】校验参数传递auth', 'uid:' . $uid . 'sku:' . $sku, 'increaseNum:'
         . $increaseNum . 'decreaseNum:' . $decreaseNum . 'shoppingKey:' . $shoppingKey);
         }*/

        return result;
    })();

};

/**
 * 移出购物车
 *
 * @param int $uid 用户ID
 * @param string $skuList 商品sku列表json格式, 如{"744403":1}
 * @param string $count 要删除的数目
 * @param string $shoppingKey 未登录用户唯一识别码
 * @param bool hasPromotion 标识是不是有promotion_id参数, 后端会去调用不同的接口
 * @return array 接口返回的数据
 */
const removeFromCart = (uid, shoppingKey, skuList, hasPromotion) => {

    return co(function * () {
        let result = {
            code: 400,
            message: ERROR_400_MESSAGE
        };

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

        let remove = yield cartApi.removeFromCart(uid, shoppingKey, skuList, hasPromotion);

        if (remove && remove.code) {
            result.code = remove.code;
            result.message = remove.message;
            if (remove.data && remove.data.goods_count) {
                result.totalGoodsNum = remove.data.goods_count;
            }
        }/* else {
         UdpLog::info('【购物车】校验参数传递auth', 'uid:' . $uid . 'skuList:' .
          $skuList . 'shoppingKey:' . $shoppingKey . 'hasPromotion:' . $hasPromotion);
         }*/

        return result;
    })();
};

/**
 * 移入收藏夹
 *
 * @param int $uid 用户ID
 * @param string $skuList 商品sku列表
 * @param bool hasPromotion 标识是不是有promotion_id参数, 后端会去调用不同的接口
 * @return array 接口返回的数据
 */
const addToFav = (uid, skuList, hasPromotion) => {

    return co(function * () {
        let result = {
            code: 400,
            message: ERROR_400_MESSAGE
        };

        if (!uid) {
            return {
                code: 403,
                message: '请先登录!',
                data: {
                    url: helpers.urlFormat('/signin.html', {
                        refer: helpers.urlFormat('/shopping/cart')
                    })
                }
            };
        }

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

        let add = yield cartApi.addToFav(uid, skuList, hasPromotion);

        if (add && add.code) {
            result = add;
        }/* else {
         UdpLog::info('【购物车】校验参数传递auth', 'uid:' . $uid . 'skuList:' . $skuList . 'hasPromotion:' . $hasPromotion);
         }*/

        return result;
    })();

};

/**
 * 检查用户是否收藏这一批商品
 *
 * @param int $uid 用户ID
 * @param array $skuList 商品SKU列表
 * @return array
 */
const checkUserIsFav = (uid, skuList) => {

    return co(function * () {
        let result = {};

        if (!skuList) {
            return result;
        }

        if (!uid || !_.isNumber(uid)) {

            _.forEach(skuList, it => {
                result[it] = false;
            });

            return result;
        }

        return cartApi.checkUserIsFavProductList(uid, skuList);
    })();
};

/**
 * 获取为你优选商品 待处理
 *
 * @param $channel 频道
 * @param $uid 用户id
 * @param $udid 设备id
 * @param int $page 分页页码
 * @return array
 * @internal param $rec_pos
 * @internal param $limit
 */
const getRecommendProduct = (channel, uid, udid, page) => {

    return co(function * () {

        let result = {
            code: 200,
            message: '',
            data: {
                header: '为您优选',
                hasPrev: false,
                hasNext: false,
                item: {}
            }
        };
        let channelNum = 1;

        if (!_.isNumber(page)) {
            return result;
        }

        switch (channel) {
            case 'boys':
                channelNum = 1;
                break;
            case 'girls':
                channelNum = 2;
                break;
            case 'kids':
                channelNum = 3;
                break;
            case 'lifestyle':
                channelNum = 3;
                break;
            default:
                break;
        }

        let together = yield cartApi.newPreference(channelNum, uid, udid, '100003', 30);
        let plist = _.get(together, 'data.product_list');

        if (!plist || !plist.length) {
            return result;
        }

        if (page > 5) {
            page = 1;
        }

        let begin = (page - 1) * 6;
        let end = begin + 7;
        let items = _.map(_.slice(plist, begin, end), it => {

            let item = {
                id: it.product_id,
                skn: it.product_skn,

                // href: Helpers::getUrlBySkc($value['product_id'],
                //                            $value['goods_list'][0]['product_skc'], $value['cn_alphabet']),
                title: it.product_name,
                img: it.default_images ? helpers.image(it.default_images, 100, 100) : '',
                alt: it.product_name,
                price: chelper.transPrice(it.sales_price)
            };

            // 商品链接
            let cnAlphaBet = it.cn_alphabet ? it.cn_alphabet : md5(it.product_name);
            let firstGoods = it.goods_list && it.goods_list[0];
            let productSkc = firstGoods && firstGoods.product_skc;

            item.href = helpers.url(`/product/pro_${it.product_id}_${productSkc}/${cnAlphaBet}.html`, null, 'item');

            if (it.sales_price !== it.market_price) {
                it.marketPrice = chelper.transPrice(it.market_price);
            }
            return item;
        });

        Object.assign(result.data, {
            hasPrev: page > 1,
            hasNext: plist.length >= end,
            item: items
        });

        return result;
    })();
};

const modifyProduct = (param) => {

    return cartApi.modifyProduct(param);
};

const swapGift = (uid, shoppingKey, promotionId, newSkn, newSku) => {
    return cartApi.swapGift(uid, shoppingKey, promotionId, newSkn, newSku);
};

const queryUserPromotionGift = (promotionId, uid, shoppingKey) => {

    return co(function * () {
        let promotionGifts = yield cartApi.queryPromotionGift(promotionId);
        let cartDataRet = yield cartApi.cartData(uid, shoppingKey);
        let selectedGift = chelper.formatCartGoods(_.get(cartDataRet, 'data.ordinary_cart_data.goods_list'));
        let currentProduct = null;  // 默认展示第一个商品

        if (promotionGifts && promotionGifts.code === 200) {
            promotionGifts.data = chelper.formatPriceGiftOne(promotionGifts.data);

            if (promotionGifts.data.goodsList && promotionGifts.data.goodsList.length) {
                currentProduct = promotionGifts.data.goodsList[0];
            }

            // 处理是否选中状态
            if (selectedGift && selectedGift.length) {
                _.forEach(promotionGifts.data.goodsList, (it) => {

                    let isSelected = false;

                    _.forEach(selectedGift, sg => {
                        if (it.skn === sg.skn) {
                            isSelected = true;
                            return true;
                        }
                    });

                    it.isSelected = isSelected;
                });
            }
        }

        // 获取选中商品的数据详情
        if (currentProduct && currentProduct.id) {
            promotionGifts.data.productInfo = yield getProductInfoAsync(currentProduct.id);
        }

        return promotionGifts;
    })();

};

module.exports = {
    getProductInfoAsync, // 获取某一个商品详情主页面
    getCartData,
    getCartCount,
    addToCart,
    selectGoods,
    modifyProductNum,
    removeFromCart,
    addToFav,
    checkUserIsFav,
    getRecommendProduct,
    modifyProduct,
    swapGift,
    queryUserPromotionGift
};