detail-service.js 53.7 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 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
/**
 * 商品详情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 Fn = require('lodash/fp');
const helpers = global.yoho.helpers;
const config = global.yoho.config;
const crypto = global.yoho.crypto;
const logger = global.yoho.logger;

const detailHelper = require('./detail-helper');

const _cached = require('./cache-utils');
const ProductModel = require('./detail-product-api');
const ConsultServiceModel = require('./detail-consult-service');
const CommentServiceModel = require('./detail-comment-service');
const HotAreaServiceModel = require('./detail-hotarea-service');
const CouponServiceModel = require('./coupon-service');
const ShopServiceModel = require('./shop-service');
const BrandServiceModel = require('./brand-service');
const FavoriteProductServiceModel = require('./favorite-product-service');

const seoHandler = require('./seo-handler');

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

const BLANK_STR = ' ';
const BUNDLE_PRODUCE = 2; // 量贩
const BUNDLE_PACKAGE = 1; // 套餐

const tdk = require('../../../utils/getTDK');
const productProcess = require('../../../utils/product-process');


function _getProductIntroAsync(productId, productSkn) {
    return co(function* () {
        let result = yield Promise.props({
            sizeInfo: this.productAPI.sizeInfoAsync(productSkn),
            productComfort: this.productAPI.getProductComfortAsync(productId),
            productModelTry: this.productAPI.getProductModelTryAsync(productSkn),
            banner: this.productAPI.getProductBannerAsync(productId),
            specialDesc: this.productAPI.getSpecialDesc(productSkn)
        });

        return result;
    }).bind(this)();
}

/**
 * 获取商品的喜欢
 * pid : product id
 * bid : brand id
 */
function _getProductFavoriteDataAsync(uid, pid) {
    return co(function* () {
        let result = {
            product: false,
            brand: false
        };

        if (!uid) {
            return result;
        }

        let requestApi = {};

        if (pid) {
            requestApi.product = this.favoriteProductService.isFavoriteAsync(uid, pid);
        }

        let requestData = yield Promise.props(requestApi);

        let productData = requestData.product;

        if (productData) {
            result.product = productData.code === 200 && productData.data ? true : false;
        }

        return result;
    }).bind(this)();
}

// 商品标签
function _getTagsDataByProductInfo(data) {
    let tags = [];

    _.get(data, 'tags', []).forEach((value) => {
        let tag = {};

        switch (value) {
            case 'is_soon_sold_out': // 即将售磬
                tag.isFew = true;
                break;
            case 'is_new': // 新品NEW
                tag.isNew = true;
                break;
            case 'is_discount': // SALE
                tag.isSale = true;
                break;
            case 'is_limited': // 限量
                tag.isLimit = true;
                break;
            case 'is_yohood': // YOHOOD
                tag.isNewFestival = true;
                break;
            case 'is_advance': // 再到着
                tag.isReNew = true;
                break;
            case 'mid_year':// 年中热促
                tag.isYearMidPromotion = true;
                break;
            case 'year_end':// 年终大促
                tag.isYearEndPromotion = true;
                break;
            case 'is_presell':// 预售
                tag.isPresell = true;
                break;
            default:
                break;
        }

        tags.push(tag);
    });

    return tags;
}

// vip 价格
function _getVipDataByProductBaseInfo(data, vipLevel, uid) {
    vipLevel = vipLevel || 0;
    uid = uid || 0;

    if (_.isEmpty(_.get(data, 'vip', []))) {
        return null;
    }

    let isVip = (_v) => _v > 0;
    let isLogin = (_u) => _u > 0;
    let isNormalUser = () => isLogin(uid) && !isVip(vipLevel);
    let isVipUser = () => isLogin(uid) && isVip(vipLevel);

    let vipData = {};

    vipData.unLogin = isLogin(uid) ? false : helpers.urlFormat('/signin.html');
    vipData.normalUser = isNormalUser();

    if (isVipUser()) {
        vipData.prices = {};
        _.some(data.vip, (vip) => {
            if (detailHelper.vipLevel(vip.caption + '会员') === vipLevel) {
                vipData.prices = {
                    price: vip.price,
                    name: vip.caption,
                    vipLevel: vipLevel
                };
                return true;
            }
        });
    }

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

    return vipData;
}

// 活动
function _getProductActivityBanner(data) {
    if (_.isEmpty(data) ||
        _.get(data, 'code', 400) !== 200 ||
        !_.get(data, 'data.bannerImg')) {
        return false;
    }

    return {
        activityImg: helpers.getForceSourceUrl(data.data.bannerImg),
        url: data.data.promotionUrl
    };
}

function _getBundleAsync(result) {
    return {
        count: _.get(result, 'data[0].bundleInfo.bundleCount', 1),
        phrase: _.get(result, 'data[0].bundleInfo.promotionPhrase', ''),
        type: _.get(result, 'data[0].bundleInfo.discountType', 1),
        discount: _.get(result, 'data[0].bundleInfo.discount', null)
    };
}

function _getActivityDataByProductBaseInfo(data) {
    return _.get(data, 'data', []).map(value => {
        let des = value.promotionTitle.replace(/¥/g, '¥');

        return {
            type: value.promotionType.replace(/¥/g, '¥'),
            des: des,
            url: value.id && helpers.urlFormat('',
                {psp_id: value.id, phrase: encodeURIComponent('以下商品参加  ' + des)}, 'list'
            )
        };
    });
}

/**
 * 获得sku商品数据
 */
function _getSkuDataByProductBaseInfo(data) {
    let totalStorageNum = 0;
    let skuGoods = null;// sku商品
    let defaultImage = '';// 默认图
    let defaultSkuFlag = false; // 选中状态
    let marketPrice = _.get(data, 'market_price', 0.0);
    let imageAlt = _imageAlt(data);  // eslint-disable-line

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

    skuGoods = _.get(data, 'goods_list', []).reduce((goodsDetailList, goods) => {

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

        if (_.isEmpty(goods.color_image)) {
            return goodsDetailList;
        }

        if (goods.images_list) {
            // 商品列表
            goodsDetail.productSkc = goods.product_skc;
            goodsDetail.src = goods.color_image;
            goodsDetail.title = `${_.trim(data.product_name)} ${goods.factory_goods_name}`;
            goodsDetail.name = goods.factory_goods_name;
            goodsDetail.focus = false;
            goodsDetail.total = 0;
            goodsDetail.thumbs = [];
            goodsDetail.size = [];

            if (goodsDetail.title.length > 20) {
                goodsDetail.title = goodsDetail.title.substr(0, 20) + '...';
            }
        }

        _.get(goods, 'images_list', []).forEach((good) => {
            if (good.image_url) {
                goodsDetail.thumbs.push({
                    url: '',
                    shower: good.image_url,
                    img: good.image_url,
                    title: goodsDetail.title,
                    imageAlt
                });
            }
        });

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

        // 商品的尺码列表
        _.get(goods, 'size_list', []).forEach((size) => {
            if (data.attribute === 3) {
                // 虚拟商品,门票默认最大为4,
                size.storage_number = size.storage_number > 4 ? 4 : size.storage_number;
            } else {
                // 将(价格 > 500)并且(库存 > 5) 将库存变成 5 ,这里是为了防爬虫
                size.storage_number = marketPrice > 500.0 && size.storage_number > 5 ? 5 : size.storage_number;
            }

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

            // 是否显示到货通知
            size.notify = size.isSuppled === 'Y' && size.storage_number === 0 ? 'Y' : 'N';

            // 尺码信息
            goodsDetail.size.push({
                name: size.size_name,
                sku: size.product_sku,
                num: _.parseInt(size.storage_number),
                goodsId: size.size_id,
                notify: size.notify,
                soldOut: _.parseInt(size.storage_number) === 0,
                info: _.get(size, 'size_info', '').replace(/\//ig, '-').replace(/ /ig, '/').replace(/:/ig, ' '),
                helper: _.get(size, 'size_rec', ''),
                limitNum: _.get(size, 'limit_buy_num', 0)
            });

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

            if (goodsDetail.total > 0 && !defaultSkuFlag) { // 默认选中该sku商品
                goodsDetail.focus = true;
                defaultImage = goodsDetail.src; // 默认为选中的skc
                defaultSkuFlag = true;// 选中sku商品
            }

            goodsDetail.disable = !goodsDetail.total > 0;

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

        });

        if (goodsDetail.focus) {
            _.some(goodsDetail.size, function(value) {
                if (value.num !== 0) {
                    value.focus = true;
                    return true;
                }
                return false;
            });
        }

        goodsDetailList.push(goodsDetail);
        return goodsDetailList;
    }, []);

    if (!_.isEmpty(skuGoods) && !defaultSkuFlag) { // 没有选中一个sku商品,默认选中第一个sku商品
        // 所有商品都售罄
        _.head(skuGoods).focus = true;
        defaultImage = _.head(skuGoods).src;
    }

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

/**
 * 处理限购商品的有关按钮状态(或取现购买以及底部商品购买按钮)
 *
 * @param int $uid
 * @param int $showStatus 限购商品的关联状态
 * @param boolean $isBeginSale 限购商品是否已开售
 */
function _getFashionTopGoodsStatus(uid, showStatus, isBeginSale) {
    // 潮流尖货状态
    // getLimitedCode //限购码状态
    // hadLimitedCode //是否已经获取限购码
    // limitedCodeSoldOut //限购码是否已经抢光
    // openSoon//即将开售
    // dis //失效
    // buyNow  //是否立即购买
    let result = {
        getLimitedCode: false,
        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.getLimitedCode = true;
            break;
        case 2: // 开售后,限购码已抢光(用户未领取限购码)
            result.buyNow = true;
            result.dis = true;
            result.limitedCodeSoldOut = true;
            break;
        case 3: // 开售后,商品已经售罄
            result.soldOut = true;
            break;
        case 4:// 开售后,立即购买(用户已领取限购码)
            result.buyNow = true;
            result.hadLimitedCode = true;
            if (uid) { // 限购码失效
                result.getLimitedCodeDis = true;
            }
            break;
        case 5: // 开售前,限购码已被抢光(用户未领取限购码)
            result.openSoon = true;
            result.limitedCodeSoldOut = true;
            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;
            }
            break;
        default:
            break;
    }
    return result;
}

/**
 * 获取分类导航列表
 */
function _getSortNavAsync(productInfo, gender) {
    let data = [{
        sort_id: _.get(productInfo, 'data.maxSortId', ''),
        sort_name: _.get(productInfo, 'data.max_sort_name', '')
    }, {
        sort_id: _.get(productInfo, 'data.middleSortId', ''),
        sort_name: _.get(productInfo, 'data.middle_sort_name', '')
    }];

    let navs = [];
    let sort = data[0];

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

    // 二级分类
    let subSort = data[1];

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

    return navs;
}

// 保存在 gids 和 skns ,最近流览功能
function saveRecentGoodInCookies(oldSkns, res, addSkns) {
    oldSkns = oldSkns ? oldSkns.split(',') : [];
    oldSkns = _.reject(oldSkns, old => old === String(addSkns) ? true : false);
    oldSkns.unshift(addSkns);

    res.cookie('_browseskn', _.take(oldSkns, 30).join(','), {
        maxAge: 2000000000,
        domain: config.cookieDomain
    });
}

/**
 * 获取商品的舒适度
 */
function _getProductComfort(data) {
    let comfort = data.productComfort;

    if (_.isEmpty(comfort) || !comfort || !comfort.data) {
        return [];
    }

    return _.get(comfort, 'data', []).reduce((all, value) => {
        let blocks = [];
        let flag = false;

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

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

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

        return all;
    }, []);
}

/**
 * 基础商品描述
 */
function _getBasicDescription(productDescBo) {
    let sex = (function(gender) {
        if (gender === 1) {
            return '男款';
        } else if (gender === 2) {
            return '女款';
        } else {
            return '通用';
        }
    }(productDescBo.gender));

    const basic = [{
        key: '编号',
        value: productDescBo.erpProductId
    }, {
        key: '颜色',
        value: productDescBo.factoryGoodsName,
        dColor: true
    }, {
        key: '性别',
        value: sex
    }];

    if (productDescBo.guaranteeDay) {
        basic.push({key: '保质期', value: productDescBo.guaranteeDay});
    }

    if (productDescBo.productionTime) {
        basic.push({key: '生产日期', value: productDescBo.productionTime});
    }

    return _.get(productDescBo, 'standardBos', []).reduce((all, value) => {
        all.push({
            key: value.standardName,
            value: value.standardVal
        });

        return all;
    }, basic);
}

/**
 * 获得描述数据
 */
function _getDescriptionDataBySizeInfo(sizeInfo, additionalData) {
    if (!sizeInfo.productDescBo || !sizeInfo.productDescBo.erpProductId) {
        return false;
    }

    return {
        basic: _getBasicDescription(sizeInfo.productDescBo),
        comfort: _getProductComfort(additionalData)
    };
}

/**
 * 使sizeBoList id以 sizeAttributeBos id顺序一样
 * @param sizeInfoBo
 */
function _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 {{}}
 */
function _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', BLANK_STR));
        });

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

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

    // 测量方式
    if (sizeInfo.sizeImage) {
        size.sizeImg = sizeInfo.sizeImage.replace('http://', '//');
    }

    return size;
}

/**
 * 获取商品模特卡
 * @param productId
 */
function _getProductModelCard(sortId, sizeInfo) {
    if (!sortId || !_.includes([1, 3, 4], sortId)) {
        return [];
    }

    const modelData = _.get(sizeInfo, 'modelCardsBo', []);

    if (_.isEmpty(modelData)) {
        return [];
    }

    const TYPE_SORT = {
        1: ['height', 'weight', 'shoulderWidth', 'bust', 'waist', 'dressSize'], // 上衣
        3: ['height', 'weight', 'waist', 'hip', 'downDressSize'], // 裤子
        4: ['height', 'weight', 'waist', 'hip', 'downDressSize'] // 裙子
    };

    const local_ = {
        height: ['身高', 'cm'],
        weight: ['体重', 'kg'],
        shoulderWidth: ['肩宽', 'cm'],
        bust: ['胸围', 'cm'],
        waist: ['腰围', 'cm'],
        dressSize: ['日常尺码', ''],
        downDressSize: ['日常尺码', ''],
        hip: ['臀围', 'cm']
    };

    return _.map(modelData, (model) => {
        return {
            avatar: _.get(model, 'avatar'),
            name: _.get(model, 'modelName'),
            size: _.get(model, 'size'),
            desc: _.reduce(TYPE_SORT[sortId], (total, value) => {
                if (model[value]) {
                    total.push({
                        key: local_[value][0],
                        value: model[value] + local_[value][1]
                    });
                }

                return total;
            }, [])
        };
    });
}

/**
 *  获取模特数据
 * @param sizeInfo
 */
function getReferenceDataBySizeInfo(sizeInfo) {
    if (_.isEmpty(sizeInfo.modelBos)) {
        return false;
    }

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

    // 模特数据

    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 (_.get(value, 'fitModelBo.fit_remark')) {
            modelValue.push(value.fitModelBo.fit_remark);
            reference.thead[7] = {name: '备注', remarkCol: true};
        }

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

    return reference;
}

/**
 * 获取洗涤材质
 * @param sizeInfo
 */
function _getMaterialDataBySizeInfo(sizeInfo) {
    // 洗涤提示
    // 商品材质[洗涤说明]
    return {
        wash: _.get(sizeInfo, 'washTipsList', []).map((value) => ({
            name: value.caption,
            img: value.img
        })),
        materialDetail: _.get(sizeInfo, 'productMaterialList', []).map((value) => ({
            img: value.imageUrl.replace('http://', '//'),
            name: value.caption,
            enName: value.encaption,
            text: value.remark
        })),
        washTips: {
            tip: _.get(sizeInfo, 'washRemindTipsBo.remindTips', ''),
            img: _.replace(_.get(sizeInfo, 'washRemindTipsBo.img', ''), 'http:', '')
        }
    };
}

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

    if (_.has(sizeInfo, 'productDescBo.phrase')) {
        phrase = `<em class='details-word'>${sizeInfo.productDescBo.phrase}</em><br/>`;
    }

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

    return `<script id="details-intro"  type="text/x-handlebars-template">${phrase}${intro}</script>`;
}

/**
 * 获取模特试穿
 * @param productSkn
 */
function _getProductModelTry(data) {
    let result = data.productModelTry;

    if (_.isEmpty(result) || result.code !== 200 || _.isEmpty(result.data)) {
        return false;
    }

    let modelTry = {
        thead: ['模特', '身高', '体重', '三围', '试穿尺码', '试穿描述'],
        tbody: []
    };

    // 显示模特信息
    _.get(result, 'data.modelTryBoList', []).forEach((value) => {
        if (value.modelBo &&
            value.sizeBo &&
            value.modelBo.modelName &&
            value.sizeBo.sizeName) {

            modelTry.tbody.push([
                value.modelBo.modelName,
                value.modelBo.height,
                value.modelBo.weight,
                value.modelBo.vitalStatistics,
                value.sizeBo.sizeName,
                value.tryDesc
            ]);
        }
    });

    if (_.has(result, 'data.modelTryImgBoList')) {
        let tryImg = _.head(result.data.modelTryImgBoList);

        modelTry.frImg = helpers.getForceSourceUrl(_.get(tryImg, 'tryImg', '')) || '';
    }

    return modelTry;
}

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

    let sizeInfo = additionalData.sizeInfo;

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

    let result = {};

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

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

    // 试穿模特
    result.fittingReport = _getProductModelTry(additionalData);

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

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

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

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

    // 特别说明
    result.specialDesc = additionalData.specialDesc;

    return result;
}

function _genderHelper(gender) {
    gender = gender || '';

    switch (gender) {
        case '1':
        case '1,3': {
            return '男款';
        }
        case '2':
        case '2,3': {
            return '女款';
        }
        default: {
            return '';
        }
    }
}

function _imageAlt(goodsInfo) {
    let navs = _getSortNavAsync({data: goodsInfo}, null);
    let alt = '';

    if (_.get(goodsInfo, 'brand_info.brand_name_en')) {
        alt += _.get(goodsInfo, 'brand_info.brand_name_en') + '|';
    }

    if (_.get(goodsInfo, 'brand_info.brand_name_cn')) {
        alt += _.get(goodsInfo, 'brand_info.brand_name_cn') + '|';
    }

    if (_.get(goodsInfo, 'gender')) {
        alt += _genderHelper(_.get(goodsInfo, 'data.gender', '1,3')) + '|';
    }

    if (_.get(navs, '[1].name')) {
        alt += navs[1].name + '|';
    }

    if (_.get(goodsInfo, 'product_name', '')) {
        alt += _.get(goodsInfo, 'product_name', '');
    }

    return alt;
}

// 支持服务
function _handleService(service) {
    if (service.code !== 200) {
        return {};
    }

    return service.data;
}

// 优惠券
function _getCoupon(coupons) {
    if (coupons.code !== 200 || _.isEmpty(_.get(coupons, 'data', []))) {
        return false;
    }

    let couponList = _.get(coupons, 'data', []);

    let pickProp = Fn.pick(['couponName', 'amount', 'couponId', 'acquireStatus', 'rule4ShortName']);
    let encodeId = Fn.update('couponId', (cid) => crypto.encryption(null, cid + ''));
    let replace = Fn.update('rule4ShortName', (r) => (r ? r.replace(/¥/g, '¥') : ''));

    return Fn.map(Fn.pipe(pickProp, encodeId, replace))(couponList);
}

// 预上架商品
function _isPreShelves(product) {
    let isUnShelves = _.get(product, 'status', -1) === 0;
    let hasSetShelvesTime = _.get(product, 'advance_shelve_time', -1) > 0;

    return isUnShelves && hasSetShelvesTime;
}

// 商品线下店状态
const OFFLINE_STATUS = {
    syncOnline: [1, 2],
    onlyOffline: [3, 4]
};

function _isOfflineSell(status) {
    return _.includes(OFFLINE_STATUS.onlyOffline, status);
}

/**
 * 详情页数据格式化
 * @param origin Object 原始数据
 * @return result Object 格式化数据
 */
function _detailDataPkg(origin, uid, vipLevel, cookies) {
    return co(function* () {
        if (_.isEmpty(origin) || _.isEmpty(origin.data)) {
            return {};
        }

        let result = {};

        result.md5 = origin.md5;// 用于前端数据变化的对比

        origin = origin.data;

        if (uid) {
            origin.uid = uid;
        }

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

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

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

        result.name = propOrigin('product_name');
        result.skn = propOrigin('product_skn');
        result.productId = propOrigin('product_id');
        result.shopId = propOrigin('shop_id', 0);
        result.brandId = propOrigin('brand_info.brand_id', '');
        result.brandName = propOrigin('brand_info.brand_name', '');
        result.skuTitle = propOrigin('skuTitle', '尺码');

        result.maxSortId = propOrigin('maxSortId', '');
        result.smallSortId = propOrigin('smallSortId', '');
        result.middleSortId = propOrigin('middleSortId', '');

        result.goCartUrl = helpers.urlFormat('/cart/cart');

        // 普通预售
        result.presale = propOrigin('is_advance', 'N');

        // 定金预售
        result.deposit = propOrigin('is_deposit_advance', 'N');

        // 定金定时预售商品
        result.limitTime = propOrigin('is_limit_time_advance', 'N');

        // 秒杀商品
        result.secKill = propOrigin('is_secKill', 'N');

        // 量贩
        result.bundleType = propOrigin('bundle_type', 0);

        let requestApi = {
            fav: _getProductFavoriteDataAsync.call(this, uid, result.productId), // 处理收藏喜欢数据
            promotion: this.productAPI.getPromotionAsync(result.skn), // 打折信息
            coupon: this.couponService.listAsync(propOrigin('brand_info.brand_id'), result.skn, uid), // 优惠券
            service: this.productAPI.isSupportService(result.skn) // 支持服务
        };

        if (propOrigin('isLimitBuy', false) && propOrigin('limitProductCode', '')) {
            result.limitProductCode = propOrigin('limitProductCode');

            requestApi.limited = this.productAPI.getLimitedProductStatusAsync(
                propOrigin('limitProductCode'),
                uid,
                result.skn
            ); // 限购商品的状态
        }

        if (propOrigin('bundle_type') === BUNDLE_PRODUCE) {
            requestApi.bundle = this.productAPI.getBundleAsync(result.skn); // 量贩
        }

        // 找相似
        if (skuData.totalStorageNum === 0) {
            requestApi.alike = this.productAPI.getLikeAsync(result.skn);
        }

        // 相关推荐词
        requestApi.recommendKeywords = this.productAPI.getRecommendHotKeywords(result.middleSortId, result.skn);

        // 店铺推荐直出(seo需要)
        requestApi.shopRecommend = this.productAPI.getShopRecommendAsync(result.skn);

        // 新品推荐
        requestApi.newProduct = this.productAPI.getNewProduct(result.skn);

        // 文章推荐
        requestApi.articles = this.productAPI.getGuangArticles(result.skn);

        let requestData = yield Promise.props(requestApi);

        let favoriteData = requestData.fav;
        let promotionData = requestData.promotion;
        let coupon = requestData.coupon;
        let limitedInfo = requestData.limited;
        let bundle = requestData.bundle;
        let shopRecommend = requestData.shopRecommend;
        let alike = requestData.alike;
        let newProduct = requestData.newProduct;
        let articles = requestData.articles;
        let service = requestData.service;

        // 文章推荐
        result.recommendArticles = articles;

        // 推荐最新商品
        result.recommendNewProducts = newProduct;

        // 处理相似商品
        result.alike = productProcess.processProductList(
            _.get(alike, 'data.product_list', '')
        );

        // 推荐关键词页面
        result.recommendKeywords = requestData.recommendKeywords;

        // 处理店铺推荐
        result.shopRecommend = productProcess.processProductList(
            _.get(shopRecommend, 'data.product_list', '')
        );

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

        // 商品促销短语
        result.saleTip = propOrigin('sales_phrase', '');

        // 商品名促销短语
        result.marketTip = propOrigin('market_phrase', '');

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

        // 带人民币符号的商品价格
        result.marketPrice = propOrigin('format_market_price');
        result.salePrice = propOrigin('format_sales_price');
        result.hasOtherPrice = true;

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

        if (propOrigin('student_price', '')) {
            // 学生价
            result.studentsPrice = propOrigin('student_price');
        } else {
            // VIP数据
            result.vipPrice = _getVipDataByProductBaseInfo(origin, vipLevel, uid);
        }

        // 计算折扣比例
        let marketPriceNum = propOrigin('market_price', 0);
        let salePriceNum = propOrigin('sales_price', 0);

        if (marketPriceNum && salePriceNum && marketPriceNum !== salePriceNum) {
            result.promotion = ((salePriceNum / marketPriceNum) * 10).toFixed(1);

            // 只显示大于1折小于9折的折扣
            if (result.promotion <= 1.0 || result.promotion >= 9.0) {
                result.promotion = false;
            }
        }

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

        // 优惠券
        result.coupon = _getCoupon(coupon);

        // 有货币
        // if (!_.includes(['', '0'], propOrigin('yohoCoinNum'))) {
        //     const C_VALUE = {
        //         type: '返有货币',
        //         des: '每件返 ',
        //         rest: '个 有货币'
        //     };

        //     result.activity.push({
        //         type: C_VALUE.type,
        //         des: `${C_VALUE.des}${propOrigin('yohoCoinNum')}${C_VALUE.rest}`
        //     });
        // }

        // 上市期
        if (propOrigin('expect_arrival_time')) {
            result.arrivalDate = `${propOrigin('expect_arrival_time')}`;

            if (propOrigin('format_sales_price', '0') !== '0') {
                result.presalePrice = propOrigin('format_sales_price');
                delete result.salePrice;
                result.hasOtherPrice = true;
            } else {
                result.presalePrice = result.marketPrice;
                delete result.marketPrice;
            }
        }

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

        // 限购商品
        if (limitedInfo && limitedInfo.code === 200 && _.get(limitedInfo, 'data.isLimitBuy', false) === true) {
            // 是否开售
            let isBeginSale = _.get(limitedInfo, 'data.saleStatus', 0) === 1;

            // 限购商品有关的展示状态
            let showStatus = _.get(limitedInfo, 'data.showStatus', 1);

            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.buyNowBase = helpers.urlFormat('/cart/easypay'); // 购买链接

                if (fashTopGoods.buyNow) {
                    result.appBuy = true;
                }
            }

            // 限购商品
            result.limitedsale = 'Y';
        }

        // 非普通商品没有优惠券
        const isSpecialProduct = (pro) => {
            return pro.limitedsale === 'Y' || pro.secKill === 'Y' || pro.deposit === 'Y' || pro.presale === 'Y';
        };

        result.coupon = !isSpecialProduct(result) ? result.coupon : [];

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

        if (virtualGoods) {
            result.virtualGoods = virtualGoods;

            // 是否显示虚拟商品,立即购买按钮
            result.isVirtualBtn = soldOut ? false : true;
            result.hideCollect = true;
        }

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

            // 立即购买或者即将开售存在
            if (result.buyNow || result.openSoon || result.appBuy) {
                delete result.addToCart;
            }
        } else if (notForSale) {
            // 非卖品
            result.notForSale = true;
        } else if (soldOut) {
            // 已售磬
            result.soldOut = true;
            delete result.fashTopGoods;
        }

        // 普通预售商品
        if (result.presale === 'Y') {
            result.addToCart = false;
            result.hideCollect = true;
        }

        // 预上架普通商品
        let isPreShelve = _isPreShelves(origin); // 预上架普通商品

        if (isPreShelve) {
            result.soldOut = false;
            result.buyNow = false;
            result.openSoon = true;
            result.notForSale = false;
            result.addToCart = false;
        }

        // 量贩商品
        if (bundle && !_.isEmpty(_.get(bundle, 'data', []))) {
            result.bundle = _getBundleAsync(bundle);

            result.activity.unshift({
                type: '量贩销售',
                des: result.bundle.phrase
            });

            // 重新判断商品的默认图和选中状态

            const bundleCount = result.bundle.count;

            const isSelling = it => it.num >= bundleCount;

            // 判断是否该商品售罄,需要库存小于最低购买数
            const isBundleSelling = Fn.any(Fn.pipe(Fn.prop('size'), Fn.any(isSelling)));

            // 判断是否尺码有售罄
            const isHandleSize = Fn.each(Fn.pipe(Fn.prop('size'), Fn.each((it) => {
                it.soldOut = !isSelling(it);

                // NOTE: 这一块强制让量贩不支持到货通知
                it.notify = 'N';
            })));

            result.soldOut = !isBundleSelling(result.colors);
            isHandleSize(result.colors);

            // 判断是否有skc没有售罄
            // 如果有:focus= true
            // 左侧大图:result.img 同步修改
            // 取消原来的 focus = false

            const canFocusIndex = Fn.findIndex(Fn.pipe(Fn.prop('size'), Fn.any(isSelling)))(result.colors);
            const focusedIndex = Fn.findIndex(it => it.focus)(result.colors);

            if (canFocusIndex && focusedIndex) {
                result.colors[canFocusIndex].focus = true;
                result.img = result.colors[canFocusIndex].src;

                result.colors[focusedIndex].focus = false;
            }

            // 每一个skc 计算售罄状态
            _.each(result.colors, (color) => {
                color.disable = !Fn.any(isSelling)(color.size);
            });
        } else {
            // 普通商品
            result.bundle = {
                count: 1,
                type: result.bundleType
            };
        }

        // 虚拟商品目前只有电子票
        result.isTicket = virtualGoods;

        if (virtualGoods && result.isTicket) {
            // 虚拟商品
            result.buyNow = true; // 是否立即购买
            result.buyNowBase = helpers.urlFormat('/cart/ticketEnsure');
            if (result.salePrice) {
                result.advancePrice = result.salePrice; // 先行价格
                delete result.salePrice;
            }
        }

        // 定金预售
        if (result.deposit === 'Y') {
            result.addToCart = false;
        }

        // 定金定时预售商品
        if (result.limitTime === 'Y') {
            result.addToCart = false;
        }

        // 线下店商品类型
        result.storeStatus = propOrigin('store_show_status', 1);

        // 只在线下销售
        if (_isOfflineSell(result.storeStatus)) {
            result.addToCart = false;
        }

        // pc端不能购买商品
        if (propOrigin('canPcBuy', true) === false) {
            result.addToCart = false;
        }

        // 去掉即将售罄
        if (totalStorageNum || soldOut) {
            // 去掉即将售罄
            _.forEach(result.tags, function(value, key) {
                if (value.isFew) {
                    result.tags[key] = {};
                }
            });
        }

        // 支持服务
        result.service = _handleService(service);

        // 分享相关,产品的链接
        result.weixinUrl = propOrigin('product_url');
        result.shareTitle = result.name;
        result.shareImg = helpers.getForceSourceUrl(result.img);
        result.shareDesc = result.phrase;

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

        statGoodsInfo.uid = uid;
        statGoodsInfo.skn = propOrigin('product_skn');
        statGoodsInfo.productId = propOrigin('product_id');
        statGoodsInfo.productName = result.name.replace('\'', '’');
        statGoodsInfo.brandName = (result.brandName || '').replace('\'', '’');
        statGoodsInfo.marketPrice = (result.marketPrice ?
            result.marketPrice :
            result.presalePrice).replace('¥', ''); // 数字
        statGoodsInfo.salePrice = (result.salePrice ?
            result.salePrice :
            (result.marketPrice || result.presalePrice)).replace('¥', ''); // 数字
        statGoodsInfo.imageUrl = helpers.getForceSourceUrl(result.img);
        statGoodsInfo.productUrl = 'https:' + helpers.getUrlBySkc(propOrigin('product_skn'));
        statGoodsInfo.smallSortId = result.smallSortId;
        statGoodsInfo.soldOut = soldOut ? 1 : 0;

        result.productUrl = statGoodsInfo.productUrl;

        // 商品的店铺信息
        let shopInfo = {
            brandId: result.brandId,
            bgColor: '#000000',
            logo: '',
            alt: '',
            brandName: '',
            brandDomain: '',
            homeUrl: '',
            bgImg: '',
            isCollect: favoriteData.brand
        };

        if (result.shopId) {
            let shopData = yield Promise.props({
                bannerImg: this.shopService.getShopBannerAsync(result.shopId),
                shopInfo: this.shopService.queryShopByBrandIdAsync(result.shopId, result.brandId)
            });

            if (!_.isEmpty(shopData.shopInfo)) {
                shopInfo.alt = shopInfo.brandName = shopData.shopInfo.brand_name;
                shopInfo.brandDomain = shopData.shopInfo.brand_domain;
                shopInfo.logo = helpers.image(shopData.shopInfo.brand_ico, 45, 45);
                shopInfo.homeUrl = helpers.urlFormat(`/shop/${shopInfo.brandDomain}-${result.shopId}.html`, null);

                if (shopData.bannerImg) {
                    shopInfo.bgImg = shopData.bannerImg;
                }
            }
        }

        // 最近浏览功能 ,限量商品不加入到最近浏览
        if (!_.has(result, 'fashionTopGoods')) {
            cookies && cookies(_.get(result, 'skn', ''));
        }

        return {
            goodsInfo: result,
            banner: _.isEmpty(shopInfo) ? null : shopInfo,
            statGoodsInfo: statGoodsInfo

        };
    }).bind(this)();
}

/**
 * 获得商品价格,活动等数据
 */
function getDetailHeader(id, uid, isStudent, vipLevel, dataMd5, cookie) {
    let currentUserProductInfo = _.partial(_detailDataPkg.bind(this), _, uid, vipLevel, cookie);

    return this.productAPI.getProductAsync(id, uid, isStudent, vipLevel)
        .then(currentUserProductInfo)
        .then((result) => {
            return {
                code: 200, // 改变数据
                data: result
            };
        });
}

/**
 * 是否支持退换货,true 支持,false 不支持
 */
function saleReturn(skn) {
    return this.productAPI.isSupportReturnedSale(skn)
        .then(result => _.get(result, `data.${skn}`, 0));
}

/**
 * 第一次把售价隐藏,防爬虫的需要
 */
function _removeSalePrice(productInfo) {
    return _.omit(productInfo, ['goodsInfo.salePrice', 'goodsInfo.hasOtherPrice', 'goodsInfo.promotion']);
}

/**
 *  获取某一个商品详情主页面
 */
function showMainAsync(req, data) {
    let headerModelCtx = new HeaderModel(this.ctx);

    return co(function* () {
        // 获取商品基本信息
        let productData = yield this.productAPI.getProductAsync(
            {skn: data.skn}, data.uid, data.isStudent, data.vipLevel
        );

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

        let maxSortId = _.get(productData, 'data.maxSortId');
        let productId = _.get(productData, 'data.product_id');
        let productSkn = _.get(productData, 'data.product_skn');
        let curUserProduct = _.partial(
            _detailDataPkg.bind(this), _, data.uid, data.vipLevel, data.gid, data.saveInCookies
        );

        let requestData = yield Promise.all([
            headerModelCtx.requestHeaderData(data.channel), // 通用头部数据
            _getProductIntroAsync.call(this, productId, productSkn), // 商品详细介绍
            curUserProduct.call(this, productData), // 商品详细价格
            tdk('skn', data.skn, req) // seo
        ]);

        let navigatorHeader = requestData[0];
        let productDescription = requestData[1];
        let productInfo = requestData[2];
        let tdkData = requestData[3];
        let sortNavigator = _getSortNavAsync(productData, data.gender);

        if (tdkData[0]) {
            req.tdk = {
                title: tdkData[1],
                keywords: tdkData[2],
                description: tdkData[3]
            };
        }

        // 拼装数据
        let result = {};

        // 商品价格
        result.productDetailPage = true;
        result.detail = _removeSalePrice(productInfo);

        // 商品介绍
        let intro = _getIntroInfo(productSkn, maxSortId, productDescription);

        result.deatil = Object.assign(result.detail, intro);

        // 促销活动图片, 在页面最底部
        result.detail.goodsInfo.imageBanner = _getProductActivityBanner(productDescription.banner);

        // seo
        result.seo = Object.assign(seoHandler.getProductDetailSeo(productData, sortNavigator), {
            cononicalURL: helpers.getUrlBySkc(_.get(productData, 'data.product_skn'))
        });

        // 商品页面统计
        result.statGoodsInfo = Object.assign({fullSortName: sortNavigator.map(x => x.name).join('-')},
            productInfo.statGoodsInfo
        );

        // 面包屑导航
        result.detail.pathNav = _.concat(
            homeService.getHomeChannelNav(data.channel),
            sortNavigator,
            [{name: _.get(productInfo, 'goodsInfo.name')}]
        );

        // 统计代码中需要新的path
        result.statGoodsInfo.category = _.concat(
            homeService.getHomeChannelNav(data.channel),
            sortNavigator
        ).map(n => n.name).join('>');

        // 头部数据
        result.headerData = navigatorHeader.headerData;

        // 咨询和评论
        result.detail.comment = true;
        result.detail.consult = true;

        // 最近浏览,最多5条记录
        result.detail.latestWalk = 5;

        return result;
    }).bind(this)().catch(console.log);
}

/**
 *  获取某一个商品详情主页面
 */
function showMainBackAsync(data) {
    return co(function* () {

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

        return productData;
    }).bind(this)();
}


function recommendAsync(skn, page, limit) {
    return co(function* () {
        let recommendData = yield this.productAPI.getShopRecommendAsync(skn, page, limit);

        if (_.get(recommendData, 'code', 400) !== 200) {
            return {
                code: 200,
                data: {
                    products: []
                }
            };
        }

        const formatPrice = p => ${p}`;
        const productUrl = helpers.getUrlBySkc;
        const productImageUrl = Fn.pipe(Fn.prop('default_images'), _.partial(helpers.image, _, 280, 382, 2, 70));

        let products = _.get(recommendData, 'data.product_list', []).map((rp) => {
            let salePrice = rp.sales_price;
            let marketPrice = rp.market_price > rp.market_price ? rp.market_price : '';

            let defaultGoods = _.find(rp.goods_list, {is_default: 'Y'});

            // 无默认商品取商品列表第一个
            if (!defaultGoods) {
                defaultGoods = rp.goods_list[0] || {};
            }

            return {
                market_price: salePrice >= marketPrice ? '' : formatPrice(helpers.round(marketPrice, 2)),
                price: formatPrice(helpers.round(salePrice, 2)),
                product_name: rp.product_name,
                url: productUrl(rp.product_skn),
                pic_url: productImageUrl(rp),
                goods_id: defaultGoods.goods_id
            };
        });

        return {
            code: 200,
            data: {
                products: products
            }
        };
    }).bind(this)();
}

/**
 * 处理单个套餐
 */
function handlePackage(pack, index) {
    const isPackage = type => type === BUNDLE_PACKAGE;

    let bundleInfo = pack.bundleInfo || {};
    let productList = pack.productList || [];

    if (!isPackage(bundleInfo.discountType)) {
        return {};
    }

    let item = {
        index: index,
        name: bundleInfo.tabName,
        bundleId: bundleInfo.bundleId,
        salesPrice: bundleInfo.salesPriceStr,
        pkgPrice: bundleInfo.discountPriceStr,
        savePrice: bundleInfo.subPrice
    };

    item.productList = _.map(productList, function(value) {
        // sku商品信息
        let skuData = _getSkuDataByProductBaseInfo(value);

        return {
            id: value.product_id,
            skn: value.product_skn,
            url: helpers.getUrlBySkc(value.product_skn),
            src: value.default_images,
            productName: value.product_name,
            productPrice: value.format_sales_price,
            colors: skuData.skuGoods
        };
    });

    return item;
}

/**
 *  获取套餐
 */
function getPackage(skn) {
    return co(function* () {
        let reqData = yield this.productAPI.getBundleAsync(skn);
        let resData = {code: reqData.code};

        if (reqData.code === 200 && !_.isEmpty(reqData.data)) {
            resData.data = _.map(reqData.data, handlePackage);
        } else {
            resData.code = 400;
            resData.message = '没有数据';
        }

        return resData;
    }).bind(this)();
}

module.exports = class extends global.yoho.BaseModel {
    constructor(ctx) {
        super(ctx);

        this.commentService = new CommentServiceModel(ctx);
        this.consultService = new ConsultServiceModel(ctx);
        this.hotAreaService = new HotAreaServiceModel(ctx);
        this.productAPI = new ProductModel(ctx);
        this.couponService = new CouponServiceModel(ctx);
        this.shopService = new ShopServiceModel(ctx);
        this.brandService = new BrandServiceModel(ctx);
        this.favoriteProductService = new FavoriteProductServiceModel(ctx);

        // 获取评论列表
        this.getShareOrderListAsync = this.commentService.getShareOrderListAsync.bind(this.commentService);

        // 获取咨询列表
        this.indexConsultAsync = this.consultService.indexAsync.bind(this.consultService);

        // 添加咨询
        this.createConsultAsync = this.consultService.createAsync.bind(this.consultService);

        // 添加咨询
        this.createConsultAsync = this.consultService.createAsync.bind(this.consultService);

        // 咨询喜欢
        this.likeAsync = this.consultService.likeAsync.bind(this.consultService);

        // 咨询有用
        this.usefulAsync = this.consultService.usefulAsync.bind(this.consultService);

        // 获取某一个商品详情主页面
        this.showMainAsync = _cached(showMainAsync, function keyGen(req, {skn, channel, gender}) {
            return skn + (channel || '') + (gender || '');
        }, this);

        // 获取某一个商品详情主页面
        this.showMainBackAsync = showMainBackAsync.bind(this);

        // 获取某一个商品的热区数据
        this.indexHotAreaAsync = this.hotAreaService.indexAsync.bind(this.hotAreaService);

        // 保存最近的商品
        this.saveRecentGoodInCookies = saveRecentGoodInCookies;

        // 变化的价格部分
        this.getDetailHeader = getDetailHeader.bind(this);

        // 特殊商品退换货
        this.saleReturn = saleReturn.bind(this);

        // 推荐商品
        this.recommendAsync = recommendAsync.bind(this);

        // 套餐
        this.getPackage = getPackage.bind(this);
    }
};