detail-service.js 39.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 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
/**
 * 商品详情models
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2016/5/6
 */

'use strict';

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

const productAPI = require('./detail-product-api');

const consultService = require('./detail-consult-service');
const commentService = require('./detail-comment-service');
const hotAreaService = require('./detail-hotarea-service');
const brandService = require('./brand-service');
const favoriteBrandService = require('./favorite-brand-service');
const favoriteProductService = require('./favorite-product-service');
const shopService = require('./shop-service');

const searchAPI = require('./search-api');
const homeService = require('./home-service');
const HeaderModel = require('../../../doraemon/models/header');

const BLANK_STR = ' ';

const cachedRequestData = {};

// 展览票
const EXHIBITION_TICKET = 51335912;

const _getProductAdditionInfoAsync = (data) => {
    return co(function * () {
        let productId = data.id || 0;
        let uid = data.uid ? data.uid : 0;
        let skn = data.erpProductId;
        let brandId = data.brand && data.brand.id ? data.brand.id : 0;
        let index = 0;

        // 获取相关数据
        let promiseData = [
            productAPI.getProductBannerAsync(productId, 'web'),
            productAPI.sizeInfoAsync(skn),
            productAPI.getProductComfortAsync(productId),
            productAPI.getProductModelCardAsync(productId),
            productAPI.getProductModelTryAsync(skn),
            brandService.getBannerInfoAsync(brandId)
        ];

        if (uid) {
            promiseData.push(favoriteBrandService.isFavoriteAsync(uid, productId));
        }

        let result = yield Promise.all(promiseData);

        [
            'ItemData::getProductBanner',
            'ItemData::sizeInfo',
            'ItemData::getProductComfort',
            'ItemData::getProductModelCard',
            'ItemData::getProductModelTry',
            'BrandData::getBannerInfo',
            'FavoriteData::getUidProductFav'
        ].forEach(key => {
            cachedRequestData[key] = result[index++];
        });


        return null;
    })();
};

const _getCacheDataByName = (resourceName) => {
    return cachedRequestData[resourceName] || false;
};

/**
 * 获取商品的喜欢
 */
const _getProductFavoriteDataAsync = (uid, pid, bid) => {
    return co(function*() {

        let result = {
            product: false,
            brand: false
        };

        if (uid) {
            if (pid) {
                let productData = yield favoriteProductService.isFavoriteAsync(uid, pid);

                result.product = productData.code === 200 && productData.data ? true : false;
            }

            if (bid) {
                let brandData = yield favoriteBrandService.isFavoriteAsync(uid, bid);

                result.brand = brandData.code && brandData.code === 200 ? true : false;
            }
        }

        return result;

    })();
};

const _getTagsDataByProductInfo = (data) => {
    let tags = {};

    _.get(data, 'productTagBoList', []).forEach((value) => {
        switch (value.tagLabel) {
            case 'is_soon_sold_out': // 即将售磬
                tags.isFew = true;
                break;
            case 'is_new': // 新品NEW
                tags.isNew = true;
                break;
            case 'is_discount': // SALE
                tags.isSale = true;
                break;
            case 'is_limited': // 限量
                tags.isLimit = true;
                break;
            case 'is_yohood': // YOHOOD
                tags.isNewFestival = true;
                break;
            case 'is_advance': // 再到着
                tags.isReNew = true;
                break;
            case 'midYear':// 年中热促
                tags.isYearMidPromotion = true;
                break;
            case 'yearEnd':// 年终大促
                tags.isYearEndPromotion = true;
                break;
        }
    });
    return tags;
};

const _getVipDataByProductBaseInfo = (data, vipLevel, uid) => {
    vipLevel = vipLevel || 0;
    uid = uid || 0;

    let vipData = {};

    vipData.prices = [];

    if (data.productPriceBo.vipPrices) {
        if (vipLevel) {
            data.productPriceBo.vipPrices.forEach(value => {
                vipData.prices.push({
                    level: value.vipLevel,
                    price: value.vipPrice,
                    name: value.vipTitle,
                    cur: value.vipLevel === vipLevel
                });
            });
        }

        vipData.unLogin = false;

        if (!uid) {
            vipData.unLogin = helpers.urlFormat('/signin.html');
        }

        if (!vipLevel && uid) {
            vipData.normalUser = true;
        }

        vipData.vipSchedualUrl = helpers.urlFormat('/home/vip', {
            t: _.random(10000, 9999999)
        });
    }
    return vipData;
};

const _getProductActivityBanner = () => {

    let result = {};

    let data = _getCacheDataByName('ItemData::getProductBanner');

    if (!data) {
        return result;
    }

    if (data.code && data.code === 200 && data.data && data.data.bannerImg) {
        result.activityImg = helpers.image(data.data.bannerImg, 260, 64);
        result.url = data.data.promotionUrl;
    }

    return result;
};

const _getActivityDataByProductBaseInfo = (data) => {
    let result = [];

    let activityBanner = _getProductActivityBanner();

    if (!_.isEmpty(activityBanner)) {
        result.push(activityBanner);
    }

    if (!data.promotionBoList) {
        return result;
    }

    data.promotionBoList.forEach(value => {
        result.push({
            type: value.promotionType,
            des: value.promotionTitle
        });
    });

    return result;
};

/**
 * 获取商品咨询和评论数据
 * @param data
 */
const _getConsultCommentDataByProductInfo = (data) => {

    // 商品咨询
    let consultComment = {};

    consultComment.consultNum = 0;
    consultComment.captchaUrl = helpers.urlFormat('/passport/images', {
        t: moment().unix()
    });

    if (data.consultBoWrapper) {
        consultComment.consults = [];
    }

    // 商品评价
    consultComment.commentNum = 0;
    if (data.commentBoWrapper) {
        consultComment.comments = [];
        consultComment.commentUrl = helpers.urlFormat('/home/comment');
    }

    return consultComment;
};

/**
 * 获取品牌数据
 */
const _getBrandDataByProductBaseInfo = (data) => {
    if (!data.brand) {
        return {};
    }

    let brandId = data.brand.id;

    let bgImg = '';

    let logo = '';

    let bannerInfo = null;

    let result = _getCacheDataByName('BrandData::getBannerInfo');

    if (!result) {
        return {};
    }

    if (data.brand.brandIco) {
        logo = helpers.getForceSourceUrl(data.brand.brandIco);
    }

    if (result.code && result.code === 200 && result.data) {
        bannerInfo = result.data;
        if (bannerInfo.bannerUrl) {
            bgImg = helpers.getForceSourceUrl(bannerInfo.bannerUrl);
        }
    }

    // banner的logo
    if (bannerInfo && bannerInfo.logo) {
        logo = helpers.getForceSourceUrl(bannerInfo.logo);
    }

    let homeUrl = 'javascript:void(0)';

    if (data.brand.brandDomain) {
        homeUrl = helpers.urlFormat('', {}, data.brand.brandDomain);
    }

    // 导航的品牌banner
    return {
        brandId: brandId,
        bgColor: bannerInfo && bannerInfo.colorValue ? bannerInfo.colorValue : '#000000',
        bgImg: bgImg,
        logo: logo,
        alt: data.brand.brandName,
        brandName: data.brand.brandName,
        brandDomain: data.brand.brandDomain,
        homeUrl: homeUrl,
        isCollect: false
    };
};

/**
 * 获得sku商品数据
 */
const _getSkuDataByProductBaseInfo = (data) => {
    let totalStorageNum = 0;

    let skuGoods = null;// sku商品

    let defaultImage = '';// 默认图

    let chooseSkuFlag = false; // 选中状态

    if (data.goodsList) {
        skuGoods = data.goodsList.reduce((acc, cur, pos)=> {

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

            if (_.isUndefined(cur.colorImage)) {
                return acc;
            }

            if (cur.goodsImagesList) {
                // 商品列表
                goodsGroup.productSkc = cur.productSkc;
                goodsGroup.src = helpers.image(cur.colorImage, 40, 40);
                goodsGroup.title = `${_.trim(data.productName)} ${cur.colorName}`;
                goodsGroup.name = cur.colorName;
                goodsGroup.focus = false;
                goodsGroup.total = 0;
                goodsGroup.thumbs = [];
                goodsGroup.size = [];
            }

            cur.goodsImagesList.forEach(good => {
                if (good.imageUrl) {
                    goodsGroup.thumbs.push({
                        url: '',
                        shower: helpers.image(good.imageUrl, 420, 560),
                        img: helpers.image(good.imageUrl, 75, 100)
                    });
                }
            });

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

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

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

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

                goodsGroup.size.push({
                    name: size.sizeName,
                    sku: size.goodsSizeSkuId,
                    num: parseInt(size.goodsSizeStorageNum),
                    goodsId: size.goodsId
                });

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

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

                totalStorageNum += parseInt(size.goodsSizeStorageNum);

            });

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

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

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

/**
 * 处理限购商品的有关按钮状态(或取现购买以及底部商品购买按钮)
 *
 * @param int $uid
 * @param int $showStatus 限购商品的关联状态
 * @param boolean $isBeginSale 限购商品是否已开售
 */
const _getFashionTopGoodsStatus = (uid, showStatus, isBeginSale) => {
    // 潮流尖货状态
    // getLimitedCode //限购码状态
    // hadLimitedCode //是否已经获取限购码
    // limitedCodeSoldOut //限购码是否已经抢光
    // openSoon//即将开售
    // dis //失效
    // buyNow  //是否立即购买
    let result = {
        getLimitedCode: true,
        hadLimitedCode: false,
        limitedCodeSoldOut: false,
        openSoon: false,
        dis: false,
        buyNow: false,
        soldOut: false,
        getLimitedCodeDis: false
    };

    // 显示获取限购码按钮
    switch (showStatus) {
        case 1: // 开售前/后,立即分享获得限购码(用户未领取限购码)
            if (isBeginSale) {
                result.buyNow = true;
                result.dis = true;
            } else {
                result.openSoon = true;
                result.hadLimitedCode = false;
            }
            break;
        case 2: // 开售后,限购码已抢光(用户未领取限购码)
            result.buyNow = true;
            result.dis = true;
            result.limitedCodeSoldOut = true;
            result.getLimitedCode = false;
            result.hadLimitedCode = false;
            break;
        case 3: // 开售后,商品已经售罄
            result.soldOut = true;
            result.getLimitedCode = false;
            break;
        case 4:// 开售后,立即购买(用户已领取限购码)
            result.buyNow = true;
            result.dis = false;
            result.hadLimitedCode = true;
            if (uid) { // 限购码失效
                result.getLimitedCodeDis = true;
            }
            break;
        case 5: // 开售前,限购码已被抢光(用户未领取限购码)
            result.openSoon = true;
            result.hadLimitedCode = true;
            result.limitedCodeSoldOut = true;
            result.getLimitedCode = false;
            break;
        case 6: // 开售前,即将开售(用户已领取限购码)
            result.openSoon = true;
            result.hadLimitedCode = true;
            if (uid) { // 限购码失效
                result.getLimitedCodeDis = true;
            }
            break;
        case 7: // 开售后,用户已经用获得的限购码购买过商品
            result.buyNow = true;
            result.dis = true;
            result.hadLimitedCode = true;
            if (uid) { // 限购码失效
                result.getLimitedCodeDis = true;
            }
    }


    return result;
};

/**
 * 获取分类导航列表
 */
function _getSortNavAsync(smallSortId, gender) {
    return co(function*() {

        let navs = [];

        let data = yield searchAPI.getSortByConditionAsync({sort: smallSortId});

        if (data.data) {
            let sort = _.head(data.data.sort) || {};

            // 一级分类
            navs.push({
                href: helpers.urlFormat('', {msort: sort.sort_id, gender: gender}, 'list'),
                name: sort.sort_name,
                pathTitle: sort.sort_name
            });

            if (sort.sub) {
                // 二级分类
                let subSort = _.head(sort.sub) || {};

                navs.push({
                    href: helpers.urlFormat('', {msort: sort.sort_id, misort: subSort.sort_id, gender: gender}, 'list'),
                    name: subSort.sort_name,
                    pathTitle: subSort.sort_name
                });
            }
        }

        return navs;
    })();
}

// 保存在 gids 和 skns ,最近流览功能
const saveRecentGoodInCookies = (oldGids, oldSkns, res, addGids, addSkns) => {
    oldGids = (oldGids || '').split(',');
    oldSkns = (oldSkns || '').split(',');
    addSkns = `${addSkns}-${addGids}`;

    _.remove(oldGids, addGids);
    _.remove(oldSkns, addSkns);

    oldGids.unshift(addGids);
    oldSkns.unshift(addSkns);

    res.cookie('_browse', oldGids.splice(0, 30).join(','), {
        maxAge: 2000000000,
        domain: 'yohobuy.com'
    });

    res.cookie('_browseskn', oldSkns.splice(0, 30).join(','), {
        maxAge: 2000000000,
        domain: 'yohobuy.com'
    });
};

/**
 * 详情页数据格式化
 * @param origin Object 原始数据
 * @return result Object 格式化数据
 */
const _detailDataPkg = (origin, uid, vipLevel) => {
    return co(function*() {
        let result = {}; // 结果输出

        // 商品名称
        if (!origin.productName) {
            return result;
        }

        origin.uid = uid;
        result.name = origin.productName;
        result.skn = origin.erpProductId;
        result.productId = origin.id;
        result.maxSortId = origin.maxSortId;
        result.smallSortId = origin.smallSortId;
        result.promotionId = origin.isPromotion;
        result.goCartUrl = helpers.urlFormat('/shopping/cart');

        let brandId = 0;

        if (origin.brand && origin.brand.id) {
            brandId = origin.brand.id;
        }

        let requestData = yield Promise.all([
            _getProductAdditionInfoAsync(origin), // 接口处理数据,设置并发请求数据
            _getProductFavoriteDataAsync(uid, result.productId, brandId) // 处理收藏喜欢数据
        ]);

        let favoriteData = requestData[1];

        // 商品标签
        result.tags = _getTagsDataByProductInfo(origin);

        //  商品促销短语
        if (origin.salesPhrase) {
            result.saleTip = origin.salesPhrase;
        }

        // 商品价格
        if (origin.productPriceBo) {
            result.marketPrice = origin.productPriceBo.formatMarketPrice;
            result.hasOtherPrice = true;
            result.salePrice = origin.productPriceBo.formatSalesPrice;
            if (result.marketPrice === result.salePrice) {
                delete result.salePrice;
                result.hasOtherPrice = false;
            }
        }

        //  VIP数据
        result.vipPrice = _getVipDataByProductBaseInfo(origin, vipLevel, uid);

        //  促销活动banner,虚拟商品无促销
        if (origin.attribute !== 3) {
            result.activity = _getActivityDataByProductBaseInfo(origin);
        }

        const C_VALUE = {
            type: '返YOHO币',
            des: '每件返 ',
            rest: '个 YOHO币'
        };

        if (origin.productPriceBo.yohoCoinNum && origin.productPriceBo.yohoCoinNum !== 0) {
            result.activity.push({
                type: C_VALUE.type,
                des: `${C_VALUE.des}${origin.productPriceBo.yohoCoinNum}${C_VALUE.rest}`
            });
        }

        // 上市期
        if (origin.expectArrivalTime) {
            result.arrivalDate = `${origin.expectArrivalTime}月`;
            result.presalePrice = origin.productPriceBo.formatSalesPrice;
            delete result.salePrice;
            result.hasOtherPrice = false;
        }

        // 商品咨询和评论数据,当前为空
        let consultComment = _getConsultCommentDataByProductInfo(origin);

        // 品牌信息
        let banner = {};

        if (origin.brand) {
            result.brandImg = helpers.image(origin.brand.brandIco, 47, 47);
            result.brandName = origin.brand.brandName;
            result.brandUrl = helpers.urlFormat('', {}, origin.brand.brandDomain);
            banner = _getBrandDataByProductBaseInfo(origin);
            if (banner.isCollect && favoriteData.brand) {
                banner.isCollect = favoriteData.brand;
            }
        }

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

        result.img = skuData.defaultImage;
        result.colors = skuData.skuGoods;
        let totalStorageNum = skuData.totalStorageNum;

        // 是否收藏
        result.isCollect = favoriteData.product;

        if (origin.isLimitBuy === 'Y') {
            // 是否开售
            let isBeginSale = !!(origin.saleStatus && origin.saleStatus === 1);

            // 限购商品有关的展示状态
            let showStatus = 1;

            if (origin.showStatus) {
                showStatus = _.parseInt(origin.showStatus);
            }

            let fashTopGoods = _getFashionTopGoodsStatus(uid, showStatus, isBeginSale);

            result.fashionTopGoods = {
                getLimitedCode: fashTopGoods.getLimitedCode, // 限购码状态
                hadLimitedCode: fashTopGoods.hadLimitedCode, // 是否已经获取限购码
                limitedCodeSoldOut: fashTopGoods.limitedCodeSoldOut, // 限购码是否已经抢光
                getLimitedCodeDis: fashTopGoods.getLimitedCodeDis // 限购码是否失效
            };

            if (fashTopGoods.soldOut) {
                result.soldOut = fashTopGoods.soldOut;
                totalStorageNum = 0; // 改总数为已售磬
            } else {
                result.openSoon = fashTopGoods.openSoon; // 即将开售
                result.dis = fashTopGoods.dis; // 是否失效
                result.buyNow = fashTopGoods.buyNow; // 是否立即购买
            }
        }

        let soldOut = !!(origin.status === 0 || totalStorageNum === 0);

        let notForSale = origin.attribute === 2; // 非卖品

        let virtualGoods = origin.attribute === 3; // 虚拟商品

        if (!soldOut && !notForSale && !virtualGoods) {
            result.addToCart = true;

            // 立即购买或者即将开售存在
            if (result.buyNow || result.openSoon) {
                delete result.addToCart;
            }
        } else if (notForSale) {
            // 非卖品
            result.notForSale = true;
        } else if (soldOut) {
            // 已售磬
            result.soldOut = true;
            delete result.fashTopGoods;
        } else if (virtualGoods) {
            // 虚拟商品
            result.buyNow = true; // 是否立即购买
            result.buyNowBase = helpers.urlFormat('ticket', {}, 'shopping');
            result.virtualGoods = virtualGoods;
            if (result.salePrice) {
                result.advancePrice = result.salePrice; // 先行价格
                delete result.salePrice;
            }

            // 是否展览票
            result.isTicket = origin.erpProductId * 1 === EXHIBITION_TICKET;
        }

        // 去掉即将售罄
        if (totalStorageNum || soldOut) {
            if (result.tags.isFew) {
                delete result.tags.isFew; // 去掉即将售罄
            }
        }

        // 分享相关,产品的链接
        result.weixinUrl = helpers.urlFormat(origin.productUrl, {}, 'item');
        result.shareTitle = result.name;
        result.shareImg = 'http:' + result.img;
        result.shareDesc = result.phrase;

        // 统计需要的商品信息
        let statGoodsInfo = {};

        statGoodsInfo.uid = uid;
        statGoodsInfo.skn = origin.erpProductId;
        statGoodsInfo.productId = origin.id;
        statGoodsInfo.productName = result.name.replace('\'', '’');
        statGoodsInfo.brandName = (result.brandName || '').replace('\'', '’');
        statGoodsInfo.marketPrice = result.marketPrice.replace('¥', '');
        if (result.salePrice) {
            statGoodsInfo.salePrice = result.salePrice.replace('¥', '');
        } else {
            statGoodsInfo.salePrice = result.marketPrice.replace('¥', '');
        }

        if (banner.brandId) {
            let domainBrand = yield brandService.getBrandByDomainAsync(banner.brandDomain);

            if (domainBrand.type && domainBrand.shopId) {
                switch (parseInt(domainBrand.type, 10)) {
                    case 1:
                        {
                        // 多品店不显示
                            banner = [];
                            break;
                        }
                    case 2:
                        {
                        // 单品店显示新版的店铺banner
                            let basisData = yield shopService.basisTemplateAsync(domainBrand.shopId);

                            banner.bgImg = basisData.shopTopBanner.banner || banner.bgImg;
                            break;
                        }
                    default:
                        {
                            break;
                        }
                }
            }
        }

        statGoodsInfo.imageUrl = result.img;
        statGoodsInfo.productUrl = result.weixinUrl;
        statGoodsInfo.smallSortId = result.smallSortId;
        statGoodsInfo.soldOut = parseInt(soldOut);

        return {
            goodsInfo: result,
            consultComment: consultComment,
            banner: _.isEmpty(banner) ? null : banner,
            statGoodsInfo: statGoodsInfo
        };
    })();
};

/**
 * 获取商品的舒适度
 */
const _getProductComfort = () => {
    let result = [];
    let comfort = _getCacheDataByName('ItemData::getProductComfort');

    if (!comfort || !comfort.data) {
        return result;
    }

    comfort.data.forEach(value => {
        let blocks = [];
        let flag = false;

        _.range(1, 6).forEach(i => {
            if (i === value.wearSense.value) {
                flag = true;
                blocks.push({
                    cur: true
                });
            } else {
                blocks.push({});
            }
        });

        // 不存在
        if (!flag) {
            return;
        }

        // 存在,添加
        result.push({
            name: value.caption.caption,
            minDes: value.caption.low,
            blocks: blocks,
            maxDes: value.caption.high
        });
    });

    return result;
};

/**
 * 基础商品描述
 */
const _getBasicDescription = (productDescBo) => {
    let sex = '';

    switch (productDescBo.gender) {
        case 1:
            sex = '男款';
            break;
        case 2:
            sex = '女款';
            break;
        default:
            sex = '通用';
    }

    let basic = [];

    basic.push({
        key: '编号',
        value: productDescBo.erpProductId
    });

    basic.push({
        key: '颜色',
        value: productDescBo.colorName,
        dColor: true
    });

    basic.push({
        key: '性别',
        value: sex
    });

    if (!productDescBo.standardBos) {
        return basic;
    }

    productDescBo.standardBos.forEach(value => {
        basic.push({
            key: value.standardName,
            value: value.standardVal
        });
    });

    return basic;
};

/**
 * 获得描述数据
 */
const _getDescriptionDataBySizeInfo = (sizeInfo) => {
    let description = {};

    if (!sizeInfo.productDescBo || !sizeInfo.productDescBo.erpProductId) {
        return description;
    }

    description.basic = _getBasicDescription(sizeInfo.productDescBo);
    description.comfort = _getProductComfort();

    return description;
};

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

    // TODO: 这里的排序代码很乱

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

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

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


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

        sizeInfoBo.sizeAttributeBos.forEach(val => {
            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(attr => {
        size.thead.push({
            name: attr.attributeName || ' ',
            id: attr.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', BLANK_STR));
        });

        // 尺码信息
        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 productId
 */
const _getProductModelCard = () => {

    let result = [];

    let data = _getCacheDataByName('ItemData::getProductModelCard');

    if (!data) {
        return result;
    }

    if (data.code && data.code === 200) {
        _(data.data).forEach(val => {
            result.push({
                url: helpers.getForceSourceUrl(val.modelImg),
                size: val.size,
                name: val.modelName
            });
        });
    }

    return result;
};

/**
 *  获取模特数据
 * @param sizeInfo
 */
const getReferenceDataBySizeInfo = (sizeInfo) => {
    let reference = {};

    if (!_.isEmpty(sizeInfo.modelBos)) {
        // 模特试穿, 竖着输出排列显示
        // 模特信息
        reference.tbody = [];
        reference.thead = [
            {name: ''},
            {name: '模特', modelCol: true},
            {name: '身高'},
            {name: '体重'},
            {name: '三围'},
            {name: '吊牌尺码'},
            {name: '试穿描述'}
        ];

        // 模特数据

        sizeInfo.modelBos.forEach(value => {
            let modelValue = [
                helpers.getForceSourceUrl(value.avatar),
                value.modelName,
                value.height,
                value.weight,
                value.vitalStatistics,
                value.fitModelBo.fit_size,
                value.fitModelBo.feel
            ];

            // 是否有备注
            if (value.fitModelBo.fit_remark) {
                modelValue.push(value.fitModelBo.fit_remark);
                reference.thead[7] = {name: '备注', remarkCol: true};
            }

            reference.tbody.push(modelValue);
        });
    }

    return reference;
};

/**
 * 获取洗涤材质
 * @param sizeInfo
 */
const _getMaterialDataBySizeInfo = (sizeInfo) => {
    let material = {};

    // 洗涤提示
    if (sizeInfo.washTipsBoList) {
        material.wash = [];
        sizeInfo.washTipsBoList.forEach(value => {
            material.wash.push({
                name: value.caption,
                img: value.img
            });
        });
    }

    if (sizeInfo.productMaterialList) {
        // 商品材质[洗涤说明]
        material.materialDetail = [];
        sizeInfo.productMaterialList.forEach(value => {
            material.materialDetail.push({
                img: value.imageUrl,
                name: value.caption,
                enName: value.encaption,
                text: value.remark
            });
        });
    }

    return material;
};

/**
 * 获取商品详情页介绍
 * @param sizeInfo
 */
const _getDetailDataBySizeInfo = (sizeInfo) => {
    let details = '';

    // 详情配图
    if (_.get(sizeInfo, 'productIntroBo.productIntro', null)) {
        if (_.get(sizeInfo, 'productIntroBo.phrase', null)) {
            details += `${sizeInfo.productDescBo.phrase}<br/>`;
        }
    }

    // 图片换成懒加载方式
    const replacePairs = {
        '<img src=': '<img class="lazy" src="data:image/gif;base64,R0lGODlhAQABAJEAAAAAAP///93d3f' +
        '///yH5BAEAAAMALAAAAAABAAEAAAICVAEAOw==" data-original=',
        '<img border="0" src=': '<img border="0" class="lazy" src="data:image/gif;base64,R0lGODlhAQABAJEAAAAAAP' +
        '///93d3f///yH5BAEAAAMALAAAAAABAAEAAAICVAEAOw==" data-original='
    };

    let intro = _.get(sizeInfo, 'productIntroBo.productIntro', '');

    _(replacePairs).forEach((value, key)=> {
        intro = _.replace(intro, key, value);
    });

    details += intro;

    return details;
};

/**
 * 获取模特试穿
 * @param productSkn
 */
const _getProductModelTry = () => {
    let modelTry = {};

    let result = _getCacheDataByName('ItemData::getProductModelTry');

    if (!result) {
        return modelTry;
    }

    if (result.code && result.code === 200 && result.data) {
        // 先显示模特信息
        if (result.data.modelTryBoList) {
            modelTry.thead = ['模特', '身高', '体重', '三围', '试穿尺码', '试穿描述'];
            modelTry.tbody = [];

            result.data.modelTryBoList.forEach(val => {
                if (val.modelBo &&
                    val.sizeBo &&
                    val.modelBo.modelName &&
                    val.sizeBo.sizeName) {

                    modelTry.tbody.push([
                        val.modelBo.modelName,
                        val.modelBo.height,
                        val.modelBo.weight,
                        val.modelBo.vitalStatistics,
                        val.sizeBo.sizeName,
                        val.tryDesc
                    ]);
                }
            });
        } else if (result.data.modelTryImgBoList) {
            let tryImg = _.head(result.data.modelTryImgBoList);

            modelTry.frImg = helpers.getForceSourceUrl(tryImg.tryImg);
        }

    }
    return modelTry;
};

/**
 * 根据最大分类ID获取尺寸属性
 * @param maxSortId
 * @param sizeInfoBo
 */
const _getSizeAttrByMaxSortId = (maxSortId, sizeList) => {
    let attributeIds = null;

    // 不同分类,取得属性值不同
    switch (maxSortId) {
        case 1:
        case 2:
            attributeIds = [3, 4];
            break;

        case 3:
            attributeIds = [6, 10];
            break;
        case 6:
            attributeIds = [13];
            break;
        default:
            attributeIds = [];
    }

    let sizeInfos = [];

    let attributeNames = {};

    if (_.isEmpty(sizeList)) {
        return sizeInfos;
    }

    // 获取属性名称
    sizeList.sizeAttributeBos.forEach(size => {
        attributeNames[size.id] = size.attributeName;
    });

    sizeList.sizeBoList.forEach(size => {
        let sizeValues = [];

        size.sortAttributes.forEach(sort => {
            if (_.includes(attributeIds, sort.id)) {
                if (sort.sizeValue) {
                    sizeValues.push(
                        `${attributeNames[sort.id]} ${sort.sizeValue}cm`
                    );
                }
            }
        });

        // 获取尺寸属性
        if (!_.isEmpty(sizeValues)) {
            sizeInfos[size.sizeName] = sizeValues.join(' / ');
        }
    });

    return sizeInfos;

};

/**
 * 商品尺码信息
 *
 * @param productSkn
 * @param maxSortId
 * @return object
 */
const _getSizeInfo = (productSkn, maxSortId)=> {
    let result = {};

    if (productSkn) {
        // 并发资源中是否存在数据
        let sizeInfo = _getCacheDataByName('ItemData::sizeInfo');

        if (!sizeInfo) {
            return result;
        }

        // 描述数据
        result.description = _getDescriptionDataBySizeInfo(sizeInfo);

        // 模特卡
        result.modelCards = _getProductModelCard();

        // 试穿模特
        let fittingReport = _getProductModelTry();

        if (!_.isEmpty(fittingReport)) {
            result.fittingReport = fittingReport;
        }

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

        // 模特数据
        let reference = getReferenceDataBySizeInfo(sizeInfo);

        if (!_.isEmpty(reference)) {
            result.reference = reference;
        }

        // 洗涤材质
        result.material = _getMaterialDataBySizeInfo(sizeInfo);

        // 商品详情页介绍
        result.details = _getDetailDataBySizeInfo(sizeInfo);

        // 获取尺寸说明
        result.sizeTitleJson =
            sizeInfo.sizeInfoBo ? JSON.stringify(_getSizeAttrByMaxSortId(maxSortId, sizeInfo.sizeInfoBo)) : '';
    }

    return result;
};

/**
 * 获取seo信息
 *
 * @param array $goodsInfo
 * @param array $navs
 * @return array
 */
const _getSeoByGoodsInfo = function(goodsInfo, navs) {
    let title = '';
    let keywords = '';
    let brandName = '';
    let sortName = '';
    let description = '';

    goodsInfo = goodsInfo || {};
    navs = navs || [];

    if (!_.isEmpty(goodsInfo.brandName)) {
        title = goodsInfo.brandName + ' ';
        brandName = goodsInfo.brandName;
    }

    if (!_.isEmpty(navs) && navs[1] && navs[1].name) {
        sortName = navs[1].name;
        title += navs[1].name + '|';
    }

    title += goodsInfo.name + '正品 ';
    keywords = brandName + sortName + ',' + brandName + '官网专卖店,' + brandName + '官方授权店,' +
        brandName + '正品,' + brandName + '打折,' + brandName + '折扣店,' + brandName + '真品,' + brandName + '代购';
    description = !goodsInfo.shareDesc ? goodsInfo.name : goodsInfo.shareDesc;

    return {
        title: title,
        keywords: keywords,
        description: description
    };
};

/**
 *  获取某一个商品详情主页面
 */
const showMainAsync = (data) => {
    return co(function * () {
        let result = {};
        let currentUserProductInfo = _.partial(_detailDataPkg, data.uid, data.vipLevel);

        // 获取商品信息
        let productInfo = yield productAPI.getProductAsync(data.pid, data.uid).then(currentUserProductInfo);

        if (!productInfo || _.isEmpty(productInfo)) {
            return Promise.reject({
                code: 404
            });
        }
        let requestData = yield Promise.all([
            _getSortNavAsync(productInfo.goodsInfo.smallSortId, data.gender),
            HeaderModel.requestHeaderData(data.channel)
        ]);

        // 分类导航 ,seo
        let navs = requestData[0];
        const seo = _getSeoByGoodsInfo(productInfo.goodsInfo, navs);

        result.seo = seo;

        // 最近浏览功能 ,限量商品不能使用这个功能
        if (!_.has(productInfo, 'goodsInfo.fashionTopGoods')) {
            data.saveInCookies(data.gid, _.get(productInfo, 'goodsInfo.skn', ''));
        }

        // 获取商品尺寸相关
        let sizeInfo = _getSizeInfo(productInfo.goodsInfo, productInfo.goodsInfo.maxSortId);

        result.headerData = requestData[1].headerData;
        result.productDetailPage = true;
        result.detail = Object.assign(productInfo, sizeInfo);
        result.statGoodsInfo = Object.assign({fullSortName: navs.map(x => x.name).join('-')},
            productInfo.statGoodsInfo
        );

        // 导航
        result.detail.pathNav = _.concat(
            homeService.getHomeChannelNav(data.channel),
            navs,
            [{name: productInfo.goodsInfo.name}]
        );

        result.detail.latestWalk = 5;
        return result;
    })();
};


module.exports = {
    indexCommentAsync: commentService.indexAsync, // 获取评论列表
    getShareOrderListAsync: commentService.getShareOrderListAsync, // 获取评论列表
    indexConsultAsync: consultService.indexAsync, // 获取咨询列表
    createConsultAsync: consultService.createAsync, // 添加咨询
    showMainAsync: showMainAsync, // 获取某一个商品详情主页面
    indexHotAreaAsync: hotAreaService.indexAsync, // 获取某一个商品的热区数据
    saveRecentGoodInCookies // 保存最近的商品
};