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

'use strict';
const _ = require('lodash');
const helpers = global.yoho.helpers;
const crypto = global.yoho.crypto;
const queryString = require('querystring');
const logger = global.yoho.logger;
const indexUrl = {
    boys: helpers.urlFormat('/'),
    girls: helpers.urlFormat('/woman'),
    kids: helpers.urlFormat('/kids'),
    lifestyle: helpers.urlFormat('/lifestyle')
};
const utils = '../../../utils';
const stringCode = require(`${utils}/string-code`);

// 打折、新品、限量
const checksName = {
    new: '新品',
    specialoffer: '打折',
    limited: '限量'
};

const sortFilterParam = (param) => {
    let resData = [];

    _.forEach(param, (value, key) => {
        resData.push({
            key: key,
            value: value
        });
    });

    return _.sortBy(resData, [o => {
        return o.key;
    }]);
};

/**
 * 处理用于筛选的 URL , 拼接 URL 参数
 * @param originParam 当前 URL 中的参数
 * @param newParam 要拼接的 参数
 * @returns {string}
 */
const handleFilterUrl = (originParam, newParam, delParam) => {
    let dest = '?';
    let tempOriginParam = {};

    delParam = delParam || {};

    tempOriginParam = Object.assign(tempOriginParam, originParam, newParam);
    delete tempOriginParam.uid;

    _.forEach(sortFilterParam(tempOriginParam), info => {
        if (!delParam[info.key] && info.value) {
            // NOTE: 这里会对 query 进行编码,因为 query 有可以能是中文
            if (info.key === 'query') {
                info.value = encodeURIComponent(info.value);
            }
            dest += `${info.key}=${info.value}&`;
        }
    });

    return _.trim(dest, '&');
};

/**
 * 处理选中数据
 * @param  {[type]} params [description]
 * @param  {[type]} origin [description]
 * @param  {[type]} param  [description]
 * @return {[type]}        [description]
 */
const handleCheckedData = (params, origin, param) => {
    let dest = [];

    if (!_.isEmpty(origin)) {
        _.forEach(origin, value => {
            if (value.checked) {
                let tempPatam = _.cloneDeep(params);

                // 删除选中
                if (param === 'gender') {
                    // 某些特殊带频道信息页面,清除性别,需将gender设为1,2,3 (2017-3 配合SEO进行URL改造)
                    tempPatam[param] = '1,2,3';
                } else {
                    delete tempPatam[param];
                }

                dest.push({
                    name: value.name,
                    href: handleFilterUrl(tempPatam),
                    itemType: param
                });
            }
        });
    }
    return dest;
};

/**
 * 处理品牌筛选数据
 * @param params
 * @param origin
 * @returns {{}}
 */
const handleBrandCheckedData = (params, origin) => {
    let dest = [];

    // 分拆品牌参数
    let brands = _.split(params.brand, ',');
    let intBrands = [];

    _.forEach(brands, value => {
        intBrands.push(parseInt(value, 10));
    });

    let checkedCount = 0,
        brandsTotalName = '';

    // 遍历品牌数据,如果在参数中,那么加 checked,将此数据加入到 checked 数组中
    if (!_.isEmpty(origin)) {

        brandsTotalName = _.map(origin, 'name').join('、');
        _.forEach(origin, (value) => {
            if (typeof _.find(intBrands, o => {
                return _.isEqual(o, +value.id);
            }) !== 'undefined') {
                let checked = {
                    name: value.name
                }; // push 到已选择数组

                // 为了不污染原始数据
                let tempIntBrands = _.cloneDeep(intBrands);

                // 去掉当前选项
                _.remove(tempIntBrands, n => {
                    return n === value.id;
                });

                // 拼接参数
                let brand = '';

                // 建议保留,需要品牌可以单个删除时放开注释即可
                // _.forEach(tempIntBrands, subValue => {
                //     brand += subValue + ',';
                // });

                // 清除参数,保留没有去掉的参数
                let tempParam = {
                    brand: brand
                };

                checked.href = handleFilterUrl(params, tempParam);
                checked.itemType = 'brand';
                if (checkedCount === 0) {
                    dest[0] = checked;
                } else if (checkedCount === 1) {
                    dest[0].name += '、' + checked.name.substring(0, 3) + '...';
                }
                checkedCount++;

                // 建议保留,需要品牌可以单个删除时放开注释即可
                // dest.push(checked);
                dest[0].totalName = brandsTotalName;
            }
        });

    }
    return dest;
};

/**
 * 新品、折扣、限量
 */
const hadleChecks = (name, params, filter) => {
    let tempParam = _.cloneDeep(params),
        checked = false;

    if (!params[name] && !filter[name]) {
        return null;
    }

    if (params[name] && params[name] === 'Y') {
        checked = true;
        delete tempParam[name];
    } else {
        tempParam[name] = 'Y';
    }

    return {
        name: checksName[name],
        checked: checked,
        href: handleFilterUrl(tempParam)
    };
};

/**
 * 获取standard
 */
const getStandard = (qStandard, addOne, delOne) => {
    let s = [];

    qStandard = Object.assign({}, qStandard);
    if (addOne && addOne.k) {
        qStandard[addOne.k] = addOne.v;
    }

    if (delOne && delOne.k && qStandard[delOne.k]) {
        delete qStandard[delOne.k];
    }

    _.each(qStandard, (val, key) => {
        if (!delOne || !delOne.k || delOne.v !== val) {
            s.push([key, val].join('_'));
        }
    });

    return s.join(',');
};

const formatterFilterBrands = (source, paramBrand, params) => {

    let dbrand = {
        default: [],
        brandsShow: [],
        brandIndex: [{
            index: 'all',
            name: '全部'
        }, {
            index: '0-9',
            name: '0~9'
        }],
        selectedBrands: []
    };


    // 品牌索引数据处理
    for (let i = 65; i < 91; i++) {
        dbrand.brandIndex.push({
            index: String.fromCharCode(i).toLowerCase(),
            name: String.fromCharCode(i)
        });
    }

    // 品牌数据处理
    // 分拆品牌参数
    let brands = _.split(params.brand, ',');
    let intBrands = [];

    _.forEach(brands, value => {
        intBrands.push(parseInt(value, 10));
    });

    if (source) {
        let count = 0;
        let checkedBrand = [];

        _.forEach(source, function(value) {
            let brand = {
                checked: (typeof _.find(intBrands, o => {
                    return _.isEqual(o, +value.id);
                }) !== 'undefined'),
                href: handleFilterUrl(params, {brand: value.id}),
                name: value.brand_name,
                key: value.brand_domain,
                id: value.id
            };

            if (!_.isEmpty(value.brand_alif)) {
                if (!_.isNaN(parseInt(value.brand_alif, 10))) {
                    brand.index = '0-9';
                } else {
                    brand.index = value.brand_alif.toLowerCase();
                }
            }

            if (count < 10) {
                dbrand.default.push(brand);
            }

            if (brand.checked) {
                checkedBrand.push(brand);
            }

            dbrand.brandsShow.push(brand);
            count++;
        });

        if (dbrand.default.length > 9) {
            Object.assign(dbrand, {
                showMore: true,
                showMulti: true
            });
        }
        if (paramBrand) {
            _.forEach(paramBrand, value => {
                let brand = {
                    href: handleFilterUrl(params, {brand: value.id}),
                    name: value.brand_name,
                    key: value.brand_domain,
                    id: value.id
                };

                dbrand.selectedBrands.push(brand);
            });
        } else { // 当接口不返回paramBrand时,选中品牌设为遍历匹配出的品牌
            dbrand.selectedBrands = checkedBrand;
        }

        // 没有品牌的情况下将 brand 设置为 false,前端不显示 品牌
        if (_.size(dbrand.brandsShow) <= 0) {
            return false;
        } else {
            // 品牌排序
            dbrand.brandsShow = _.sortBy(dbrand.brandsShow, o => {
                return o.index;
            });
        }
    }

    return dbrand;
};


/**
 * 处理 opts 排序数据
 * @param params
 * @param total
 * @param extra 什么都可以传进来,多个参数传Object
 * @returns {{}}
 */
exports.handleOptsData = (params, total, extra) => {
    let dest = {
        sortType: [],
        checks: []
    };

    // 用来标记是否是折扣专场,折扣专场只需要前三个排序参数
    let count = (extra === 'discont') ? 4 : 5;

    for (let i = 0; i < count; i++) {
        let opt = {};

        switch (i) {
            case 0:
                opt.href = handleFilterUrl(params, {}, {page: true, order: true});
                if (extra === 'discont') { // 如果是折扣专场
                    opt.name = '全部';
                    if (_.isEmpty(params.order) || params.order === 's_t_desc') {
                        opt.active = true;
                    } else {
                        opt.active = false;
                    }
                } else {
                    opt.name = '默认';
                    if (_.isEmpty(params.order) || params.order === 's_n_desc') {
                        opt.active = true;
                    } else {
                        opt.active = false;
                    }
                }
                break;
            case 1:
                opt.name = '人气';
                opt.href = handleFilterUrl(params, {order: 'h_v_desc'}, {page: true});

                if (params.order === 'h_v_desc') {
                    opt.active = true;
                } else {
                    opt.active = false;
                }
                break;
            case 2:
                if (params.order !== 's_t_desc' && params.order !== 's_t_asc') {
                    opt.href = handleFilterUrl(params, {order: 's_t_desc'}, {page: true});
                    opt.hasSortOrient = true;
                } else {
                    opt.hasSortOrient = true;
                    opt.active = true;
                    if (params.order === 's_t_desc') {
                        opt.href = handleFilterUrl(params, {order: 's_t_asc'}, {page: true});
                        opt.desc = false;
                    } else {
                        opt.href = handleFilterUrl(params, {order: 's_t_desc'}, {page: true});
                        opt.desc = true;
                    }
                }

                opt.name = '新品';
                break;
            case 3:
                if (params.order !== 's_p_desc' && params.order !== 's_p_asc') {
                    opt.href = handleFilterUrl(params, {order: 's_p_desc'}, {page: true});
                    opt.hasSortOrient = true;
                } else {
                    opt.hasSortOrient = true;
                    opt.active = true;
                    if (params.order === 's_p_desc') {
                        opt.href = handleFilterUrl(params, {order: 's_p_asc'}, {page: true});
                        opt.desc = false;
                    } else {
                        opt.href = handleFilterUrl(params, {order: 's_p_desc'}, {page: true});
                        opt.desc = true;
                    }
                }

                opt.name = '价格';
                break;
            case 4:
                if (params.order !== 'p_d_desc' && params.order !== 'p_d_asc') {
                    opt.href = handleFilterUrl(params, {order: 'p_d_desc'}, {page: true});
                    opt.hasSortOrient = true;
                } else {
                    opt.hasSortOrient = true;
                    opt.active = true;
                    if (params.order === 'p_d_desc') {
                        opt.href = handleFilterUrl(params, {order: 'p_d_asc'}, {page: true});
                        opt.desc = false;
                    } else {
                        opt.href = handleFilterUrl(params, {order: 'p_d_desc'}, {page: true});
                        opt.desc = true;
                    }
                }

                opt.name = '折扣';
                break;
            default:
                break;
        }

        dest.sortType.push(opt);
    }

    // 上下翻页数据处理
    dest.pageCounts = [{
        href: handleFilterUrl(params, {limit: 40}, {page: true}),
        count: 60
    }, {
        href: handleFilterUrl(params, {limit: 100}, {page: true}),
        count: 100
    }, {
        href: handleFilterUrl(params, {limit: 200}, {page: true}),
        count: 200
    }];

    dest.curPage = _.isEmpty(params.page) ? 1 : params.page; // 当前页码数

    // 每页商品数量
    dest.countPerPage = _.isEmpty(params.limit) ? 40 : params.limit;

    // 全部页码数量
    dest.pageCount = _.ceil(total / (dest.countPerPage - 1));

    // 每页多少商品
    let paramsLimit = parseInt((_.isEmpty(params.limit) ? 60 : params.limit), 10);

    // 上一页下一页
    let preHref = (!_.isEmpty(params.page) && parseInt(params.page, 10) > 1) ?
        parseInt(params.page, 10) - 1 : 1;
    let nextHref = (!_.isEmpty(params.page)) ? parseInt(params.page, 10) + 1 : 2;

    params.page = _.isEmpty(params.page) ? 1 : params.page;

    if (dest.pageCount > 1 && (parseInt(params.page, 10) !== 1) &&
        (parseInt(params.page, 10) !== dest.pageCount)) {
        dest.preHref = handleFilterUrl(params, {page: preHref});
        dest.nextHref = handleFilterUrl(params, {page: nextHref});
    } else if (dest.pageCount > 1 && (parseInt(params.page, 10) === 1 || _.isEmpty(params.page))) {
        dest.nextHref = handleFilterUrl(params, {page: nextHref});
    } else if (dest.pageCount > 1 && (parseInt(params.page, 10) === dest.pageCount)) {
        dest.preHref = handleFilterUrl(params, {page: preHref});
    }

    // 全部商品数
    dest.totalCount = total;

    // 商品开始结束数
    dest.start = (!_.isEmpty(params.page) ? (params.page - 1) : 0) * paramsLimit + 1;
    if (total < paramsLimit) {
        dest.end = total;
    } else {
        dest.end = (dest.pageCount === parseInt(params.page, 10)) ?
            total : parseInt(dest.start, 10) + paramsLimit - 1;
    }

    if (extra) {
        // 新品
        dest.checks.push(hadleChecks('new', params, extra));

        // 打折
        dest.checks.push(hadleChecks('specialoffer', params, extra));

        // 限量
        dest.checks.push(hadleChecks('limited', params, extra));

        dest.checks = _.filter(dest.checks, chk => {
            return chk !== null;
        });
    }
    return dest;
};

/**
 * 处理页面左侧分类筛选数据
 * @param origin 分类原始数据,一般是接口返回数据中的 group_sort 字段
 * @param params 当前 URL 中已有的参数
 * @param extra 可以任意传值用来处理特殊情况
 * @param {string} [baseUrl] 需要跳转非当前页面传的相对路径(可不传,默认为空字符串)
 * @returns {{}}
 */
exports.handleSortData = (origin, params, originParams, baseUrl) => {
    let leftContent = {
        sort: {misort: []},
        checked: []
    };

    let list = [],
        allCount = 0;

    baseUrl = baseUrl || '';

    let all = [{
        name: '全部品类',
        num: allCount,
        href: `${baseUrl}${handleFilterUrl(params, {}, {msort: true, misort: true, sort: true, category_id: true})}`
    }];

    originParams = originParams || {};

    _.forEach(origin, value => {
        let equalCategory = `${originParams.category_id}` === `${value.category_id}`;
        let category = {
            categoryId: value.category_id,
            name: value.category_name,
            num: value.node_count,
            childList: [
                {
                    categoryId: value.category_id,
                    name: `全部${value.category_name}`,
                    num: value.node_count,
                    href: `${baseUrl}${handleFilterUrl(params, {category_id: value.category_id}, {
                        msort: true,
                        misort: true,
                        sort: true
                    })}`,
                    childActive: equalCategory
                }
            ]
        };

        allCount += parseInt(value.node_count, 10);

        if (equalCategory) {
            category.active = true;
        }

        _.forEach(value.sub, subValue => {
            let child = {
                categoryId: subValue.category_id,
                name: subValue.category_name,
                num: subValue.node_count,
                href: `${baseUrl}${handleFilterUrl(params, {category_id: subValue.category_id}, {
                    msort: true,
                    misort: true,
                    sort: true
                })}`,
                childActive: `${originParams.category_id}` === `${subValue.category_id}`
            };

            category.childList.push(child);

            if (child.childActive) {
                category.active = true;
            }
        });

        list.push(category);
    });

    leftContent.allSort = {all: all, list: list};

    return leftContent;
};

/**
 * 店铺品类聚合
 * @param data 分类数据
 * @returns {{}}
 */
exports.setShopSort = (data, params) => {
    let resData = {};

    if (!_.isEmpty(data)) {
        let list = [];

        _.forEach(data, value => {
            _.forEach(value.sub, subValue => {
                list.push({
                    name: subValue.category_name,
                    href: handleFilterUrl(params, {category_id: subValue.category_id}),
                    curMenu: `${params.category_id}` === `${subValue.category_id}`
                });
            });
        });

        if (list.length) {
            resData.goodsMenu = {
                menuList: list,
                url: `/product/shoplist?navBar=1&shopId=${params.shopId}`
            };
        }
    }

    return resData;
};

/**
 * 店铺性别筛选
 * @param params qs
 * @returns {{}}
 */
exports.setGenderFilter = (params) => {
    return {
        genderFilter: [
            {
                name: '全部',
                href: handleFilterUrl(params, {}, {gender: true}),
                checked: !params.gender || params.gender === '1,2,3'
            },
            {
                name: 'BOYS',
                href: handleFilterUrl(params, {gender: '1,3'}),
                checked: params.gender === '1,3'
            }, {
                name: 'GIRLS',
                href: handleFilterUrl(params, {gender: '2,3'}),
                checked: params.gender === '2,3'
            }
        ]
    };
};

/**
 * 处理一般筛选数据
 * @param origin 要处理的筛选数据 filter
 * @param params 当前 URL 中已有的参数,处理选中状态使用
 * @returns {{}}
 */
exports.handleFilterData = (origin, params, total) => {
    let dest = {
        ageLevel: [],
        price: [],
        gender: [],
        color: [],
        checkedConditions: {
            conditions: []
        }
    };

    if (origin.brand) {
        dest.brand = formatterFilterBrands(origin.brand, origin.paramBrand, params);
    }

    // 处理价格筛选数据
    let priceRangechecked = false;

    if (!_.isEmpty(origin.priceRange)) {
        let customPrice = _.split(params.price, ',');

        _.forEach(origin.priceRange, (value, key) => {
            if (params.price === key) {
                priceRangechecked = true;
            }
            if (_.isString(value)) {
                value = _.replace(value, '¥', '¥');
            }
            let price = {
                checked: params.price === key,
                href: handleFilterUrl(params, {price: key}),
                name: value,
                order: +key.split(',')[0]
            };

            dest.price.push(price);
        });

        // 价格排序
        dest.price = _.sortBy(dest.price, (item) => {
            return item.order;
        });

        dest.customPrice = {
            min: customPrice[0],
            max: customPrice[1]
        };
    }

    // 处理用户自主填写的价格区间
    if (!priceRangechecked && params.price) {
        let customPrice = _.split(params.price, ','),
            min = customPrice[0] || 0,
            name;

        customPrice[0] = customPrice[0];
        name =  ${min}-${customPrice[1]}`;

        if (!customPrice[1]) {
            customPrice[1] = '';
            name =  ${min}以上`;
        }

        dest.customPrice = {
            min: customPrice[0],
            max: customPrice[1]
        };
        dest.checkedConditions.conditions.push({
            name: name,
            itemType: 'price',
            href: handleFilterUrl(params, {}, {price: true})
        });
    }

    // 处理性别数据
    dest.gender = [{
        name: 'BOYS',
        href: handleFilterUrl(params, {gender: '1,3'}),
        checked: params.gender === '1,3'
    }, {
        name: 'GIRLS',
        href: handleFilterUrl(params, {gender: '2,3'}),
        checked: params.gender === '2,3'
    }];

    // 尺码处理
    if (!_.isEmpty(origin.size) && params.category_id) {

        dest.size = [];

        if (_.isArray(origin.size)) {
            _.forEach(origin.size, value => {
                dest.size.push({
                    checked: parseInt(params.size, 10) === parseInt(value.size_id, 10),
                    href: handleFilterUrl(params, {
                        size: value.size_id
                    }),
                    name: value.size_name
                });
            });
        } else {
            dest.size.push({
                checked: parseInt(params.size, 10) === parseInt(origin.size.size_id, 10),
                href: handleFilterUrl(params, {
                    size: origin.size.size_id
                }),
                name: origin.size.size_name
            });
        }

        dest.checkedConditions.conditions = _.union(dest.checkedConditions.conditions,
            handleCheckedData(params, dest.size, 'size'));
    }

    // 处理颜色筛选数据
    if (!_.isEmpty(origin.color)) {
        _.forEach(origin.color, (value) => {
            value.color_code = value.color_code.replace(/#/ig, '');

            let color = {
                checked: parseInt(params.color, 10) === parseInt(value.color_id, 10),
                href: handleFilterUrl(params, {color: value.color_id}),
                name: value.color_name,
                rgb: value.color_value ? 'url(' + value.color_value.replace('http://', '//') + ')' : '#' + value.color_code
            };

            // 处理颜色选中数据
            if (color.checked) {
                let href = handleFilterUrl(params, null, {color: value.color_id});

                dest.checkedConditions.conditions.push({
                    itemType: 'color',
                    name: value.color_name,
                    href: href,
                    color: color.rgb
                });
            }

            dest.color.push(color);
        });
    }

    // 处理年龄段
    if (!_.isEmpty(origin.ageLevel)) {

        // 只有一个默认选中
        let isChecked = origin.ageLevel.length === 1;

        do { // eslint-disable-line
            if (isChecked && origin.ageLevel[0].name === '成人' && +params.age_level !== 1) {
                break;
            }

            _.forEach(origin.ageLevel, (value) => {
                let ageLevel = {
                    checked: params.age_level === value.id || isChecked,
                    href: handleFilterUrl(params, {age_level: value.id}),
                    name: value.name
                };

                // 处理颜色年龄段数据
                if (ageLevel.checked || isChecked) {
                    ageLevel.href = handleFilterUrl(params, null, {age_level: value.id});
                    dest.checkedConditions.conditions.push(ageLevel);
                }

                dest.ageLevel.push(ageLevel);
            });
        } while (false);
    }

    // 清除所有选中数据
    // 某些特殊带频道信息页面,清除性别,需将gender设为1,2,3 (2017-3 配合SEO进行URL改造)
    let remainParams = {gender: '1,2,3'};

    if (params.id) {
        remainParams.id = params.id;
    }

    if (params.union_type) {
        remainParams.union_type = params.union_type;
    }

    dest.checkedConditions.clearUrl = '?' + queryString.stringify(remainParams);

    // 处理频道筛选数据
    dest.checkedConditions.conditions = _.union(dest.checkedConditions.conditions,
        handleCheckedData(params, dest.gender, 'gender'));

    // 处理品牌筛选数据
    if (dest.brand && dest.brand.brandsShow) {

        dest.checkedConditions.conditions = _.union(dest.checkedConditions.conditions,
            handleBrandCheckedData(params, dest.brand.selectedBrands));
    }

    // 处理价格筛选数据
    dest.checkedConditions.conditions = _.union(dest.checkedConditions.conditions,
        handleCheckedData(params, dest.price, 'price'));

    // 商品记录小于10,不显示价格区间
    if (total && total < 10) {
        dest.price = null;
    }

    return dest;
};

/**
 * 处理高级选项数据
 * @param origin 要处理的筛选数据 filter
 * @param params 当前 URL 中已有的参数,处理选中状态使用
 * @returns {{}}
 */
exports.handleSeniorFilterData = (data, params) => {
    let resData = {};

    if (data) {
        let chose = [];
        let conditions = [];

        if (!_.isEmpty(data.style)) {
            let sub = [],
                conName = [];
            let styles = _.split(_.get(params, 'style', ''), ',');

            _.forEach(data.style, value => {
                let ched = styles.indexOf(`${value.style_id}`) >= 0;

                if (ched && conName.length < 2) {
                    conName.push(value.style_name);
                }
                sub.push({
                    id: value.style_id,
                    checked: ched,
                    href: handleFilterUrl(params, {style: value.style_id}),
                    name: value.style_name
                });
            });

            if (conName.length) {
                conditions.push({
                    name: _.join(conName, '、'),
                    itemType: '风格',
                    href: handleFilterUrl(params, {}, {style: true})
                });
            }

            if (sub && sub.length > 1) {
                chose.push({
                    name: '风格',
                    showMulti: true,
                    sub: sub,
                    attr: 'style'
                });
            }
        }

        if (!_.isEmpty(data.standard)) {
            let qStandardStr = (params && params.standard) || '';
            let qStandard = {};

            _.forEach(qStandardStr.split(','), value => {
                let val = value.split('_');

                if (val && val.length >= 2) {
                    qStandard[parseInt(val[0], 10)] = parseInt(val[1], 10);
                }
            });

            _.forEach(data.standard, value => {
                if (!value) {
                    return;
                }

                let sub = [],
                    standardName = value.standard_name;

                _.forEach(value.sub, subValue => {
                    let ched = qStandard[value.standard_id] === parseInt(subValue.standard_id, 10);

                    if (ched) {
                        conditions.push({
                            name: subValue.standard_name,
                            itemType: standardName,
                            href: handleFilterUrl(params, {
                                standard: getStandard(qStandard, null, {
                                    k: value.standard_id,
                                    v: subValue.standard_id
                                })
                            })
                        });
                    }

                    sub.push({
                        id: value.standard_id,
                        checked: ched,
                        href: handleFilterUrl(params, {
                            standard: getStandard(qStandard, {
                                k: value.standard_id,
                                v: subValue.standard_id
                            })
                        }),
                        name: subValue.standard_name
                    });
                });

                // 只有一条不显示
                if (sub && sub.length > 1) {
                    chose.push({
                        name: value.standard_name,
                        sub: sub
                    });
                }
            });
        }

        if (!_.isEmpty(chose)) {
            resData.seniorChose = chose;
        }

        if (!_.isEmpty(conditions)) {
            _.set(resData, 'checkedConditions.conditions', conditions);
        }
    }

    return resData;
};

exports.handleFilterDataAll = (data, qs) => {
    let destFilter = {};
    let params = _.cloneDeep(qs);

    _.unset(params, 'page'); // 去除筛选项page

    let baseFilter = this.handleFilterData(_.get(data, 'filter', {}), params, data.total);
    let seniorFilter = this.handleSeniorFilterData({
        style: _.get(data, 'filter.style', []),
        standard: _.get(data, 'standard', [])
    }, params);

    let conditions = _.union(_.get(baseFilter, 'checkedConditions.conditions'),
        _.get(seniorFilter, 'checkedConditions.conditions'));

    Object.assign(destFilter, seniorFilter, baseFilter);

    _.set(destFilter, 'checkedConditions.conditions', conditions);
    return destFilter;
};

/**
 * 根据页面设置面包屑导航
 * @type {[type]}
 */
exports.handlePathNavData = (data, params, page, channel) => {

    let rootName = '首页';

    if (channel && _.isString(channel)) {
        rootName = channel.toUpperCase() + rootName;
    }

    let pathNav = [{
        href: indexUrl[channel],
        name: rootName, // '首页',
        pathTitle: rootName // '首页'
    }];

    switch (page) {
        case 'search':
            // 搜索结果提示
            if (params.query || params.keywords) {
                params.query = params.query || params.keywords;
                pathNav.push({
                    name: '“<span id="nav_keyword">' +
                    params.query + '</span>”&nbsp;&nbsp;共<span id="nav_keyword_count">' +
                    data.total + '</span>个结果'
                });
            } else {
                pathNav.push({
                    name: '所有商品'
                });
            }
            break;
        case 'brand':

            // 品牌
            pathNav.push(
                {
                    name: '品牌一览',
                    pathTitle: '品牌一览',
                    href: helpers.urlFormat('/brands')
                },
                {
                    name: data.brandNameEn + data.brandNameCn,
                    pathTitle: data.brandNameEn + data.brandNameCn
                }
            );
            break;
        case 'shop':

            // 店铺
            pathNav.push(
                {
                    name: data.brandName,
                    pathTitle: data.brandName
                }
            );
            break;
        case 'new':

            // 新品到着
            pathNav.push(
                {
                    name: '新品到着',
                    pathTitle: '新品到着'
                }
            );
            break;
        default :
            // 分类

            _.forEach(data, sort => {
                let navList = [];

                if (`${params.category_id}` === `${sort.category_id}`) {
                    navList = [{
                        name: sort.category_name,
                        pathTitle: sort.category_name
                    }];
                }

                if (!_.isEmpty(sort.sub)) {
                    _.forEach(sort.sub, misort => {
                        if (`${params.category_id}` === `${misort.category_id}`) {
                            navList = [{
                                name: sort.category_name,
                                href: handleFilterUrl(sort.relation_parameter),
                                pathTitle: sort.category_name
                            },
                            {
                                name: misort.category_name,
                                pathTitle: misort.category_name
                            }];
                        }
                    });
                }

                if (!_.isEmpty(navList)) {
                    pathNav = _.concat(pathNav, navList);
                }
            });
            break;
    }
    return {
        pathNav: pathNav,
        listType: page
    };
};

/**
 * 分页
 * @param  {[type]} total 总页数
 * @param  {[type]} params 筛选条件
 * @param  {[noNextBtn]} 列表是否有下一页的按钮,如果有则实际查询数比传递参数的少一个,入60 => 59
 * @return {[type]}        [description]
 */
exports.handlePagerData = (total, params, noNextBtn) => {
    let dest = {
        prePage: {
            url: ''
        },
        nextPage: {
            url: ''
        },
        pages: []
    };

    let currentPage = parseInt(_.get(params, 'page', 1), 10); // 当前页
    let perPageCount = parseInt(_.get(params, 'limit', noNextBtn === true ? 40 : 39), 10); // 每页商品数
    let totalPage = Math.ceil(total / perPageCount); // 总页数

    if (noNextBtn !== true) {
        switch (perPageCount) {
            case 200:
                perPageCount = 199;
                break;
            case 100:
                perPageCount = 99;
                break;
            default :
                perPageCount = 39;
                break;
        }
    }

    if (currentPage === 1) {
        // 当前页为 1,一定没有上一页
        delete dest.prePage;
    } else {
        dest.prePage.url = handleFilterUrl(params, {page: currentPage - 1});
    }

    if (currentPage === totalPage) {

        // 当前页为最后一页,一定没有下一页
        delete dest.nextPage;
    } else {
        dest.nextPage.url = handleFilterUrl(params, {page: currentPage + 1});
    }

    // 页码临时数据
    let pages = [];

    if (currentPage > 2 && currentPage <= totalPage - 2) {
        for (let i = currentPage - 2; i <= ((currentPage + 2) > totalPage ? totalPage : (currentPage + 2)); i++) {
            pages.push({
                url: handleFilterUrl(params, {page: i}),
                num: i,
                cur: currentPage === i
            });
        }

        // 处理页码小于等于 2 的情况
    } else if (currentPage <= 2) {
        for (let i = 1; i <= (totalPage < 5 ? totalPage : 5); i++) {
            pages.push({
                url: handleFilterUrl(params, {page: i}),
                num: i,
                cur: currentPage === i
            });
        }
    } else if (currentPage > totalPage - 2) {
        for (let i = totalPage; i >= totalPage - 4; i--) {

            if (i > 0) {
                pages.push({
                    url: handleFilterUrl(params, {page: i}),
                    num: i,
                    cur: currentPage === i
                });
            }
        }
        pages = _.sortBy(pages, ['num']);
    }

    let prevPages = [];
    let nextPages = [];

    if (_.size(pages) === 5) {
        if (currentPage > 4) {
            prevPages.push({
                url: handleFilterUrl(params, {page: 1}),
                num: 1
            });
            prevPages.push({
                num: '...'
            });
        }
        if (currentPage < totalPage - 2 && totalPage > 5) {
            nextPages.push({
                num: '...'
            });
            nextPages.push({
                url: handleFilterUrl(params, {page: totalPage}),
                num: totalPage
            });
        }
    }

    // 商品开始结束数
    dest.tip = {
        total: total,
        start: (currentPage ? currentPage - 1 : 0) * perPageCount + 1
    };

    let endPageNum = (totalPage === currentPage) ?
        total : parseInt(dest.tip.start, 10) + perPageCount - 1;

    dest.tip.end = (total < perPageCount) ? total : endPageNum;
    dest.pages = _.concat(prevPages, pages, nextPages);

    return dest;

};

/**
 * 处理分类介绍
 * @type {[type]}
 */
exports.handleSortIntro = (data) => {
    let sortIntro = {
        name: data.title,
        enName: data.subtitle,
        description: data.intro,
        img: data.logo,
        keyEntry: []
    };

    _.forEach(data.keyword, function(value) {
        sortIntro.keyEntry.push({
            name: value.word,
            url: value.url.replace(/(parameter_)(\d+)=(\d+)/, (match, p1, p2, p3) => `standard=${p2}_${p3}`)
        });
    });

    return sortIntro;
};

/**
 * 处理分类页左侧广告
 * @type {[type]}
 */
exports.handleSortAds = (data) => {
    let sortAds = {
        picLink: {
            picTitle: '',
            list: []
        }
    };

    _.forEach(data, function(value) {
        sortAds.picLink.list.push({
            href: value.ads_url,
            src: value.ads_image
        });
    });

    return sortAds;
};

/**
 * 热销品牌
 * @type {[type]}
 */
exports.hotBrands = (data, title) => {
    let hotBrands = {
        title: title || '热销品牌',
        list: []
    };

    _.forEach(data, function(value) {
        hotBrands.list.push({
            title: value.title,
            href: value.url,
            src: value.image
        });
    });

    return {hotBrands: hotBrands};
};

/**
 * 处理一周新品上架
 * @type {[type]}
 */
exports.handleWeekNew = (data, params) => {
    let list = [];
    let dest = {
        newSales: {
            name: '',
            list: []
        }
    };

    _.forEach(data.recent, function(value, key) {
        let t = _.split(key, '-'),
            dayStart = new Date(t[0], _.parseInt(t[1]) - 1, t[2]).getTime() / 1000,
            day = `${dayStart},${dayStart + 86400}`;

        list.push({
            name: `${t[1] || ''}${t[2] || ''}日`,
            href: handleFilterUrl(params, {shelveTime: day}),
            active: day === params.shelveTime,
            sort: +t.join('')
        });
    });

    _.set(dest, 'newSales.list', _.sortBy(list, function(o) {
        return -o.sort;
    }));

    return dest;
};

/**
 * 处理搜索提示
 * @type {[type]}
 */
exports.handleSuggest = (data) => {
    let suggest = [];

    _.forEach(data, function(value) {
        suggest.push({
            href: helpers.urlFormat('', {query: value.keyword}, 'search'),
            keyword: value.keyword,
            count: value.count
        });
    });

    return suggest;
};

/**
 * 处理品牌页banner
 * @type {[type]}
 */
exports.handleBrandBanner = (data) => {
    return {
        bannerHeight: 150,
        banner: helpers.getForceSourceUrl(data.brandBanner || ''),
        brandHome: data.url,
        brandIntro: helpers.urlFormat('/about', '', data.brandDomain),
        dataId: data.brandId
    };
};

/**
 * 处理品牌系列folder_id
 * @type {[type]}
 */
exports.handleFolderData = (data, params) => {
    params = params || {};

    let baseQs = params.shopId ? `&shopId=${params.shopId}` : '';
    let dest = [];

    _.forEach(data, (value) => {
        dest.push({
            href: `?folder_id=${value.id}${baseQs}`,
            src: value.brand_sort_ico
        });
    });

    return dest;
};

/**
 * 处理品牌系列series
 * @type {[type]}
 */
exports.handleSeriesData = (data, params) => {
    params = params || {};

    let baseQs = params.shopId ? `&shopId=${params.shopId}` : '';
    let dest = [];

    _.forEach(data, (value) => {
        dest.push({
            href: `?series=${value.id}${baseQs}`,
            src: value.series_banner
        });
    });

    return dest;
};

/**
 * 筛选类链接处理的对外接口
 * @type {[type]}
 */
exports.handleFilterUrl = handleFilterUrl;

/**
 * 处理选中数据的对外接口
 * @type {[type]}
 */
exports.handleCheckedData = handleCheckedData;

exports.handleNextPage = (params, total) => {
    let href;
    let currentPage = parseInt((params.page ? params.page : 1), 10); // 当前页
    let perPageCount = parseInt((params.limit ? params.limit : 40) - 1, 10); // 每页商品数
    let totalPage = _.ceil(total / perPageCount); // 总页数

    if (currentPage >= totalPage) {
        return null;
    } else {
        href = handleFilterUrl(params, {page: currentPage + 1});
    }

    return {
        href: href,
        src: '//img10.static.yhbimg.com/product/2014/01/15/11/01fa01614784f6239760f1b749663016f1.jpg?' +
        'imageMogr2/thumbnail/235x314/extent/235x314/background/d2hpdGU=/position/center/quality/90'
    };
};

const _getChannelName = channel => {

    let channelName = '';

    switch (channel) {
        case 'boys':
            channelName = '男生';
            break;
        case 'girls':
            channelName = '女生';
            break;
        case 'kids':
            channelName = '潮童';
            break;
        case 'lifestyle':
            channelName = '创意生活';
            break;
        default:
            channelName = '男生';
    }

    return channelName;
};

const _handelSeoParamsName = (channel, sorts, checked) => {
    let kd = {};

    _.forEach(sorts, val => {
        if (val.active) {
            kd.sort = val && val.name;
            _.forEach(val.childList, sub => {
                if (sub.childActive && sub.categoryId !== val.categoryId) {
                    kd.sort = sub && sub.name;
                }
            });
        }
    });

    checked = checked || [];
    _.forEach(checked, ck => {
        if (!(ck && ck.itemType)) {
            return false;
        }

        switch (ck && ck.itemType) {
            case 'brand':
            case 'color':
            case 'size':
            case 'price':
            case 'style':
                kd[ck.itemType] = ck.name;
                break;
            case 'gender':
                kd.channel = ck.name === 'GIRLS' ? '女生' : '男生';
                break;
            default:
                if (ck.itemType) {
                    if (!kd.senior) {
                        kd.senior = '';
                    } else {
                        kd.senior += '、';
                    }
                    kd.senior += ck.name;
                }
                break;
        }
    });

    return kd;
};

/**
 * 列表页seo
 * @param channel
 * @param sorts
 * @param checked
 * @returns {{title: string, keywords: string, description: string}}
 */
exports.getListSeo = (channel, sorts, checked) => {
    const defaultTdk = {
        title: '潮流服装配饰,创意生活用品_男生|女生|潮童服装,鞋履,配饰品牌正品-YOHO!BUY有货',
        keywords: '潮流服装配饰,创意生活用品,男生服装配饰,女生服装配饰,潮童服装配饰',
        description: '潮流服装配饰及创意生活正品网购!YOHO!BUY有货提供男生、女生、潮童服装配饰。100%品牌正品保证,支持货到付款。'
    };

    const kd = _handelSeoParamsName(channel, sorts, checked);

    // 无筛选参数时默认tdk
    if (_.isEmpty(kd)) {
        return defaultTdk;
    }

    _.forEach(['sort', 'brand', 'color', 'size', 'price', 'channel', 'style', 'senior'], val => {
        kd[val] = kd[val] || '';
    });

    return {
        title: `${kd.price ? '价格在' : ''}${kd.price}${kd.brand}${kd.channel}${kd.color}${kd.size}${kd.sort}|YOHO!BUY有货`, // eslint-disable-line
        keywords: `${kd.size}${kd.color}${kd.brand}${kd.channel}${kd.sort}${kd.style ? ',' : ''}${kd.style}` || defaultTdk.keywords, // eslint-disable-line
        description: `潮流网购${kd.brand}就上YOHO!BUY有货,有货网销售正品新款${kd.size}${kd.color}${kd.brand}${kd.channel}${kd.sort},全场低至4,100%品牌正品保证,支持货到付款。` // eslint-disable-line
    };
};

/**
 * 新品到页 seo
 * @param channel
 * @param sorts
 * @param checked
 * @returns {{title: string, keywords: string, description: string}}
 */
exports.getNewSeo = (channel, sorts, checked, shelveTime) => {
    const channelName = _getChannelName(channel);
    const defaultTdk = {
        title: `${channelName}新品上架,100%正品保证-YOHO!BUY 有货`,
        keywords: `${channelName}新品,潮流新品,潮流正品`,
        description: `${channelName}新品上架,正品网购,官方授权!100%品牌正品保证,支持货到付款。 想购买潮流商品就来YOHO! 有货中国最大的潮流商品购物网站。`
    };

    const kd = _handelSeoParamsName(channel, sorts, checked);

    shelveTime = parseInt(`0${(_.toString(shelveTime) || '').split(',')[0]}`, 10);

    if (shelveTime) {
        const data = new Date(shelveTime * 1000);

        kd.day = `${data.getFullYear()}${data.getMonth() + 1}${data.getDate()}日`;
        kd.year = `${data.getFullYear()}年`;
    }

    // 无筛选参数时默认tdk
    if (_.isEmpty(kd)) {
        return defaultTdk;
    }

    _.forEach(['year', 'day', 'sort', 'brand', 'color', 'size', 'price', 'channel', 'style', 'senior'], val => {
        kd[val] = kd[val] || '';
    });

    return {
        title: `新品到着|${kd.price ? '价格在' : ''}${kd.price}${kd.brand}${kd.channel}${kd.color}${kd.size}${kd.sort}|YOHO!BUY有货`, // eslint-disable-line
        keywords: `${kd.size}${kd.color}${kd.brand}${kd.channel}${kd.sort}${kd.style ? ',' : ''}${kd.style}` || defaultTdk.keywords, // eslint-disable-line
        description: `${kd.day}新品到着,潮流网购${kd.brand}就上YOHO!BUY有货,有货网销售正品${kd.year}新款${kd.size}${kd.color}${kd.brand}${kd.channel}${kd.sort},全场低至4,100%品牌正品保证,支持货到付款。` // eslint-disable-line
    };
};

/**
 * 品牌店铺页 seo
 * @param channel
 * @param info
 * @param qs
 * @returns {{title: (string|*|string), keywords: string, description: string}}
 */
exports.getBrandShopSeo = (channel, info, qs) => {
    let resData = {},
        ctype = {
            boys: {fashionType: '男装', brandType: '男生品牌'},
            girls: {fashionType: '女装', brandType: '女生品牌'},
            kids: {fashionType: '童装', brandType: '潮童品牌'},
            lifestyle: {fashionType: '创意生活', brandType: '创意生活品牌'}
        };
    let params = {
        nameEn: '',
        name: ''
    };

    if (info) {
        Object.assign(params, {
            nameEn: _.get(info, 'brandNameEn', ''),
            nameCn: _.get(info, 'brandNameCn', '')
        });

        params.name = `${params.nameEn} ${params.nameCn}`;

        if (info.shopName) {
            Object.assign(params, {
                nameEn: info.shopName,
                name: info.shopName
            });
        }
    }

    let description = `有货网${params.nameEn}旗舰店销售${params.name}正品商品,100%质量保证,支持货到付款,想了解${params.name}价格、图片、评价等信息,就上YOHO!BUY 有货中国最大的潮流商品购物网站!`; // eslint-disable-line

    if (qs && qs.gender) {
        if (qs.gender === '1,3') {
            channel = 'boys';
        } else if (qs.gender === '2,3') {
            channel = 'girls';
        }
        Object.assign(params, ctype[channel] || ctype.boys);
        Object.assign(resData, {
            title: `${params.nameEn} | ${params.name} ${params.brandType} | 正品保证, YOHO!BUY 有货`,
            keywords: `${params.nameEn}, ${params.name} ${params.fashionType},${params.nameEn} ${params.brandType}`,
            description: description
        });
    } else {
        Object.assign(resData, {
            title: `${params.nameEn} | ${params.name}品牌旗舰店 | 正品保证, YOHO!BUY 有货`,
            keywords: `${params.nameEn}, ${params.name}品牌旗舰店,${params.name}正品`,
            description: description
        });
    }

    return resData;
};

exports.getAboutSeo = (name, intro, shop) => {
    let type = shop ? '店铺' : '品牌';

    intro = intro || '';

    intro = _.truncate(_.replace(intro, /<\/?[^>]*>|\s*|(\n)|(\t)|(\r)/g, ''), {
        length: 156,
        omission: '...'
    });

    return {
        title: `${name}品牌 | ${name}${type}介绍 | YOHO!BUY有货 100%正品保证`,
        keywords: `${name}品牌, ${name}${type}介绍`,
        description: `${name}${type}介绍 ${intro}`
    };
};

/**
 * 获取商品的前三个skn 提供给第三方推广使用
 * @param glist
 * @returns {Array}
 */
exports.getCriteo = (glist) => {

    let sknArr = [];

    if (glist) {
        _.forEach(glist, (val) => {

            if (sknArr.length < 3) {
                if (val && val.product_skn) {
                    sknArr.push(val.product_skn);
                }
            } else {
                return false;
            }
        });
    }

    return sknArr;
};

// handlePagerData
exports.getSearchParams = params => {

    let mlimit = 39;

    if (params && params.limit) {

        let olimit = parseInt(params.limit, 10);

        switch (olimit) {
            case 100:
                mlimit = 99;
                break;
            case 200:
                mlimit = 199;
                break;
            default:
                mlimit = 39;
        }
    }

    /** 处理页面数据 **/
    let nparams = {
        limit: mlimit
    };

    if (params && params.price && typeof params.price === 'string') {
        let mp = params.price.split(',');
        let nmp = [];

        nmp[0] = (mp && mp[0]) || 0;
        nmp[1] = (mp && mp[1]) || 99999;
        nparams.price = nmp.join(',');
    }

    // 未登录状态uid传个性化推荐id(即上次登录cookie中存储的_PRID)
    if (_.has(params, 'prid')) {
        if (!params.uid && params.prid) {
            nparams.uid = params.prid;
        }

        _.unset(params, 'prid');
    }

    // 商品详情页促销跳转
    if (params && params.psp_id) {
        Object.assign(nparams, {
            promotion_id: params.psp_id,
            method: 'app.search.promotion'
        });
    }

    // 优惠券商品列表
    if (params && params.cpc_id && params.coupon_code) {
        Object.assign(nparams, {
            coupon_id: params.cpc_id,
            coupon_code: params.coupon_code,
            method: 'app.search.coupon'
        });
    }

    /** 查询参数再处理 **/
    // 对可能有中文的情况进行处理
    if (params.query) {
        try {
            params.query = decodeURIComponent(params.query);
        } catch (e) {
            logger.info(e);
        }

    }

    return Object.assign({}, params, nparams);
};

exports.handleFilterBrands = (brands, params) => {
    return formatterFilterBrands(brands, null, params);
};

exports.handleBrandShopCoupons = (data, params) => {
    let resData = {};
    let length;

    data = data || [];
    params = params || {};
    length = data.length || 0;

    if (length) {
        _.forEach(data, value => {
            Object.assign(value, {
                coupon_id: crypto.encryption('', `${value.coupon_id}`),
                money: +value.money
            });
        });

        if (length === 1) {
            data[0].showUnit = true;
        }

        Object.assign(resData, {
            list: data,
            length: length,
            showNextBtn: length > 3
        }, params);

        return resData;
    }

    return false;
};

/**
 * 处理页面左侧分类筛选数据
 * @param origin 分类原始数据,一般是接口返回数据中的 group_sort 字段
 * @param params 当前 URL 中已有的参数
 * @param extra 可以任意传值用来处理特殊情况
 * @param {string} [baseUrl] 需要跳转非当前页面传的相对路径(可不传,默认为空字符串)
 * @returns {{}}
 */
exports.handleSuggestData = (origin, query) => {
    let leftContent = {};

    let list = [];

    let all = [{
        name: '全部推荐'
    }];

    _.forEach(origin, value => {
        if (query === value.keyword || value.keyword.length <= 2) {
            return;
        }

        list.push({
            name: `${value.keyword}`,
            href: helpers.urlFormat(`/so/${stringCode.utf8ToHex(value.keyword)}.html`, null, 'www')
        });
    });

    leftContent.allSuggest = {
        all: all,
        title: '相关推荐',
        list: list
    };

    return leftContent;
};