index.js 25.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
/**
 * 频道页 model
 * @author: 赵彪<bill.zhao@yoho.cn>
 * @date: 2016/05/17
 */
'use strict';

const _ = require('lodash');

const dataMap = require('../../../config/data-map');

const helpers = global.yoho.helpers;
const config = global.yoho.config;

const processProduct = require(`${global.utils}/product-process`).processProduct;
const searchApi = require('../../product/models/search-api');


const api = global.yoho.API;
const serviceApi = global.yoho.ServiceAPI;

const headerModel = require('../../../doraemon/models/header');

// 获取可用的标题
const _getText = data => {
    let text = data.split(' ')[0];
    const regResult = /\w+/.exec(text);
    const titleWithoutChinese = /^(?=.*[A-Za-z0-9])[A-Za-z0-9 _]*$/;

    // 对于不含中文的标题,直接返回
    if (titleWithoutChinese.test(data)) {
        return data;
    }

    if (regResult) {

        // 去掉标题中的英文部分
        text = text.replace(regResult[0], '');
    }

    return text;
};

const channelMap = dataMap.channel;

const sortMap = dataMap.sort;

/**
 * 新人专享
 * @param {[Object]} data 原始数据
 * @return {[Object]} 转换后的数据
 */
const _getNewUserFloorData = data => {
    let floorData = {
        newUserFloor: {
            name: _getText(data.title.name),
            navs: {},
            bannerImage: {
                url: data.banner_image[0].url,
                src: helpers.image(data.banner_image[0].src, 1150, 368),
                title: data.banner_image[0].title
            }
        }
    };

    if (data.title.more_name) {
        floorData.newUserFloor.navs.name = data.title.more_name;
    }
    if (data.title.more_url) {
        floorData.newUserFloor.navs.url = data.title.more_url;
    }
    if (data.list) {
        let proList = [];

        // 大于15就取前15个产品数
        proList = data.list.length > 15 ? data.list.slice(0, 15) : data.list;

        // 5个以内为false
        floorData.newUserFloor.hasSwitch = proList.length > 5 ? true : false;

        _.forEach(proList, value => {
            value.thumb = helpers.image(value.goods_list[0].images_url, 185, 247);
            value.for_newuser = true;
            value.url = helpers.getUrlBySkc(value.product_id, value.goods_list[0].goods_id, value.cn_alphabet);
        });
        floorData.newUserFloor.list = proList;
    }

    return floorData;
};

/**
 * 获取带小图的banner
 * @param {[Object]} data 原始数据
 * @return {[Object]} 转换后的数据
 */
const _getDebrisSlide = data => {
    let floorData = {
        debrisSlider: {
            left: [],
            center: [],
            right: []
        }
    };

    _.mapKeys(data, (value, key) => {
        _.forEach(value, slideData => {
            floorData.debrisSlider[key].push(slideData);
        });
    });

    return floorData;
};


/**
 * 获取广告位
 * @param {Object} data 原始数据
 * @return {Object} 转换后的数据
 */
const _getadbannerData = data => {

    return {
        adbanner: data
    };
};

/**
 * 生成banner模板数据
 * @param {Object} srcData 原始数据
 * @return {Object} 转换后的数据
 */
const _getSlideData = srcData => {
    const slideData = {
        slide: {
            list: [],
            pagination: []
        }
    };

    if (srcData.big_image) {
        slideData.slide.list = srcData.big_image;
    }

    if (srcData.list) {
        slideData.slide.pagination = srcData.list;
    }

    if (_.isArray(srcData)) {
        slideData.slide.list = srcData;
    }

    return slideData;
};


/**
 * 获取最新速报模板数据
 * @param {Object} srcData 原始数据
 * @return {Object} 转换后的数据
 */
const _getNewReportFloorData = args => {
    const title = args[0].data.text;
    let item = args[1].data;
    let secondItem = args[2].data;
    let thirdItem = args[3].data;
    let forthItem = args[4];

    let list = [];

    const data = {
        newReport: {
            name: title,
            list: []
        }
    };


    let adData;
    let floorDatas = [];


    list.push(item[0]);

    _.forEach(secondItem, (floorData) => {
        list.push(floorData);
    });

    list.push(thirdItem[0]);

    data.newReport.list = list;

    floorDatas.push(data);

    if (forthItem.template_name === 'single_image') {
        adData = _getadbannerData(forthItem.data[0]);
        floorDatas.push(adData);
    }

    return floorDatas;
};


/**
 * 给目标对象绑定频道属性
 * @param {Object} obj 需要绑定频道属性的对象
 * @param {String} type 需要设置的频道类型
 * @return undefined
 */
const _setChannelType = (obj, type) => {
    obj[type + 'Channel'] = true;
};

/**
 * 获取优选品牌模板数据
 * @param {[Object]} args 参数列表
 * @param {String} type 频道类型
 * @return {Object}
 */
const _getPreBrandTopData = (args, type) => {
    const title = args[0].data.text;
    let item = args[1].data;

    const data = {
        preferenceBrands: {
            name: title,
            imgBrand: [],
            brandUrl: '/getbrandFloorDataAjax?channelType=' + type
        }
    };

    data.preferenceBrands.imgBrand = item;
    if (type === 'kids') {
        data.preferenceBrands.sliderColor = '#7AD3F8';
    }

    _setChannelType(data.preferenceBrands, type);

    return data;
};

/**
 * 获取热门分类模板数据
 * @param {[Object]} args 参数列表
 * @param {String} type 频道类型
 * @return {Object}
 */
const _getHotGoodsFloorData = (args, type) => {
    let item = args[0];
    let nextItem = args[1];

    let list = [];

    let object = {},
        keyword = [],
        category = [],
        brands = [],
        types = [],
        products = [];

    const data = {
        recommend: {
            tplrecommend: []
        }
    };

    category = item.data.menuNav.list;

    keyword = item.data.menuNav.blocks;

    _.forEach(item.data.imgs, (it, idx) => {

        if (idx === 0 || (idx === 4 && type === 'boys')) {
            brands.push(it);
        } else {
            types.push(it);
        }
    });

    products = nextItem.data;

    object.name = item.data.name;
    object.keyword = keyword;
    object.category = category;
    object.brands = brands;
    object.types = types;
    object.navs = item.data.navs.list;
    object.products = products;
    list.push(object);

    data.recommend.tplrecommend = list;

    _setChannelType(data.recommend, type);


    return data;
};


/**
 * 获取boys人气单品模版数据
 * @param {[Object]} args 参数列表
 * @param {String} type 频道类型
 * @return {Object}
 */
const _getBoysSingleHot = (args, type) => {
    const len = 10;
    const data = {
        singlehot: {
            name: args[0].data.text,
            imgHot: []
        }
    };

    let list = [];
    let adData;
    let floorDatas = [];

    for (let i = 0; i < len; i++) {
        let pos = i;
        let val = {};

        if (i === 1) {
            val = args[1].data[0]; // 第二个是大图
        } else if (i === len - 1) {
            val = args[1].data[1]; // 最后一个是大图
        } else {
            if (pos > 1) { // 小图
                pos = pos - 1;
            }
            val = args[2].data[pos];
        }
        list.push(val);
    }

    _.forEach(list, (item, index) => {
        if (index === 1 || index === list.length - 1) {
            item.big = true;
        }
    });

    data.singlehot.imgHot = list;
    _setChannelType(data.singlehot, type);
    floorDatas.push(data);

    if (args[3].template_name === 'single_image') {
        adData = _getadbannerData(args[3].data[0]);
        floorDatas.push(adData);
    }

    return floorDatas;
};

/**
 * 获取girls人气单品模版数据
 * @param {[Object]} args 参数列表
 * @param {String} type 频道类型
 * @return {Object}
 */
const _getGirlsSingleHot = (args, type) => {
    let goods = args[2] && args[2].data;
    let skns = '';

    if (goods) {
        _.forEach(goods, good => {
            skns += good.id + ' ';
        });
    } else {
        return;
    }

    return searchApi.getProductList({
        client_type: 'web',
        query: skns,
        order: 'shelve_time:desc',
        status: 1,
        sales: 'Y',
        attribute_not: '2',
        stocknumber: 1,
        page: 1,
        gender: channelMap[type].gender,
        limit: 60
    }, config.apiCache);
};


/**
 * 人气单品入口
 * @param {[Object]} args 参数列表
 * @param {String} type 频道类型
 * @return {Object}
 */
const _getSingleHotFloorData = (args, type) => {
    if (type === 'boys') {
        return _getBoysSingleHot(args, type);
    } else {
        return _getGirlsSingleHot(args, type);
    }
};

/**
 * 处理异步获取的人气单品数据
 * @param {[Object]} args 参数列表
 * @param {String} originQuery 原始skns
 * @param {Object} queryResult 异步获取的数据
 * @param {String} type 频道类型
 * @return {Object}
 */
const _getSingehotViaResult = (args, originQuery, queryResult, type) => {
    let data = {
        singlehot: {
            name: args[0].data.text,
            navs: [],
            imgHot: [],
            brands: []
        }
    };

    let pos = 0;


    const getIndex = skn => {
        let index;


        if (originQuery) {
            const originQueryArr = originQuery.split(' ');
            let setFlag = false;

            _.forEach(originQueryArr, (query, idx) => {
                if (!setFlag && query.toString() === skn.toString()) {
                    index = idx;
                    setFlag = true;
                }
            });
        }

        return index;
    };

    if (args[3].template_name === 'app_icon_list') {
        data.singlehot.brands = args[3].data;
    }

    if (queryResult.data) {
        _.forEach(queryResult.data.product_list || [], it => {
            const formatData = processProduct(it, {
                width: 280,
                height: 373,
                gender: channelMap[type].gender
            });

            if (pos > 11) {
                return;
            }

            if (it.product_id) {
                formatData.idx = getIndex(it.product_skn);
                if (formatData.idx === 0 || formatData.idx) {
                    data.singlehot.imgHot.push(formatData);
                    pos += 1;
                }
            }
        });
    }

    data.singlehot.imgHot = _.sortBy(data.singlehot.imgHot, item => {
        return item.idx;
    });

    pos = 1;
    _.forEach(data.singlehot.imgHot, item => {
        if (pos < 4 && item) {
            item.tip = 'TOP' + pos;
            pos += 1;
        }
    });
    data.singlehot.navs = args[1].data;
    _setChannelType(data.singlehot, type);
    return data;
};

/**
 * 异步获取人气单品
 * @param {[Object]} rawData 接口返回的原始数据
 * @param {[Object]} floorData 已经经过处理的楼层数据
 * @param {String} originQuery 原始的query数据
 * @param {Object} queryResult 接口中用于请求人气单品的数据
 * @param {String} title 人气单品楼层的标题
 * @param {Type} type 人气单品楼层的类型
 * @return {Object}
 */
const _processFloorDataWithQueryReusult = (rawData, originQuery, queryResult, title, type) => {
    let data = {};

    _.forEach(rawData, (subData, index) => {
        if (subData.data) {
            const text = subData.data.text && _getText(subData.data.text);


            if (text === title) {
                data = _getSingehotViaResult(rawData.slice(index, index + 4), originQuery, queryResult, type);
            }
        }
    });

    return data;
};

/**
 * 组装最新上架楼层数据
 *
 * @param string data
 * return obj
 */
const _getNewGoodsFloorData = args => {
    const data = {
        newArrivls: {
            name: args[0].data.text,
            navs: []
        }
    };

    data.newArrivls.navs = args[1].data;

    return data;
};

const _getCategoryFloorData = args => {
    const data = {
        category: {
            name: args[0].data.text,
            navs: args[1].data,
            list: []
        }
    };

    _.forEach(args[2].data, (it, index) => {

        // 设置图片大小
        if (index === 1) {
            it.w = '377;';
            it.h = '504;';
        } else {
            it.w = '185';
            it.h = '510';
        }

        data.category.list.push(it);
    });

    return data;
};

const _getAccordionFloorData = args => {
    let data = {
        accordion: {
            name: args[0].data.text,
            navs: args[1].data,
            slide: []
        }
    };

    data.accordion.slide = args[2].data;

    return data;
};

const _requestContent = (type, params) => {
    let data = {
        client_type: 'web',
        content_code: channelMap[type || 'boys'].code,
        gender: channelMap[type || 'boys'].gender,
        page: 1,
        limit: 1000
    };

    Object.assign(data, params);

    return serviceApi.get('operations/api/v5/resource/home', data, {
        cache: true,
        code: 200
    }).then(result => {
        return result;
    });
};

const floorMap = {
    slide: _getSlideData,
    hot: _getHotGoodsFloorData,
    最新速报: _getNewReportFloorData,
    人气单品: _getSingleHotFloorData,
    'GIRL KIDS': _getSingleHotFloorData,
    'BOY KIDS': _getSingleHotFloorData,
    ACCESSORIES: _getSingleHotFloorData,
    优选品牌: _getPreBrandTopData,
    最新上架: _getNewGoodsFloorData,
    ad: _getadbannerData,
    category: _getCategoryFloorData,
    accordion: _getAccordionFloorData,
    debrisSlide: _getDebrisSlide,
    newuser: _getNewUserFloorData
};


const needQuery = {
    'GIRL KIDS': true,
    'BOY KIDS': true,
    人气单品: true,
    ACCESSORIES: true
};

const getQuery = args => {
    let goods = args[2] && args[2].data;
    let skns = '';

    if (goods) {
        _.forEach(goods, good => {
            skns += good.id + ' ';
        });
    }

    return skns;
};


const _processFloorData = (rawData, type) => {
    let floorList = [];
    let searchPromise = [];
    let singlehotFloorIndex = [];
    let singlehotFloorTitle = [];
    let params = [];
    let hasNewUser = false;

    // 定义各种楼层需要用到的接口返回的数组中元素的个数
    const bigFloorLength = 5;
    const normalFloorLength = 3;
    const hotCategoryLength = 2;


    _.forEach(rawData, (data, index) => {
        let floorData = null;
        let queryParam = '';

        if (data.template_name === 'recommend_content_three' ||
            (data.template_intro === '焦点图' && index === 0)) { // 处理banner
            floorData = floorMap.slide.call(null, data.data);
        } else if (data.template_intro === '热门品类') { // 处理热门品类
            floorData = floorMap.hot.call(null, rawData.slice(index, index + hotCategoryLength), type);
        } else if (data.data && data.data.text) { // 处理一般楼层
            let text = _getText(data.data.text);
            let lastIndex = index + bigFloorLength < rawData.length ?
            index + bigFloorLength : index + (rawData.length - index - 1);


            floorData = floorMap[text] &&
                floorMap[text].call(null, rawData.slice(index, lastIndex), type);

            if (needQuery[text]) {
                queryParam = getQuery(rawData.slice(index, lastIndex));
                if (queryParam.length > 0) {
                    params.push(queryParam);
                }
            }

        } else if (data.template_name === 'debrisSlider') { // 处理girls的banner
            floorData = floorMap.debrisSlide.call(null, data.data);
        } else if (data.template_name === 'new_user_floor' || data.template_intro === '新人专享') {
            if (!hasNewUser) {
                floorData = floorMap.newuser.call(null, data.data);
                hasNewUser = true;
            }

        }

        // 处理lifestyle分类楼层
        if (!floorData && index + normalFloorLength < rawData.length &&
            rawData[index + 1].template_name === 'textNav' &&
            rawData[index + 2].template_name === 'floor') {
            floorData = floorMap.category.call(null, rawData.slice(index, index + normalFloorLength));
        }

        // 处理手风琴楼层
        if (!floorData && index + normalFloorLength < rawData.length &&
            rawData[index + 1].template_name === 'textNav' &&
            rawData[index + 2].template_name === 'focus') {
            floorData = floorMap.accordion.call(null, rawData.slice(index, index + normalFloorLength));
        }


        // 处理promise
        if (floorData && floorData.then && typeof floorData.then === 'function') {
            searchPromise.push(floorData);

            // 记住楼层位置, 以便后面promise获取数据后插入楼层数据
            singlehotFloorIndex.push(floorList.length);

            // 记住楼层标题, 以便后面promise获取数据后插入楼层数据
            singlehotFloorTitle.push(_getText(data.data.text));
        } else if (!_.isNil(floorData)) {
            _.isArray(floorData) ?
                floorList = floorList.concat(floorData) :
                floorList.push(floorData);
        }
    });

    return {
        floors: floorList,
        promise: _.reverse(searchPromise),
        queryParams: _.reverse(params),
        singlehotFloorTitle: _.reverse(singlehotFloorTitle),
        singlehotFloorIndex: _.reverse(singlehotFloorIndex)
    };
};

const _formatResourceParams = (channel, code) => {
    return serviceApi.get('operations/api/v5/resource/get', {content_code: code}, config.apiCache).then(data => {
        let result = data && data.data[0] && data.data[0].data[0];

        if (result) {
            result.channel = channel;
        }

        return result || {};
    });
};

/**
 * 频道页首次登陆导航并行调接口数据
 * @param  {Object} data
 * @return {Object} formatData
 */
const _formatParams = (channel, data) => {
    let params = {};

    // 排序数据映射表
    let orderMaps = {
        s_t_desc: 'shelve_time:desc',
        s_t_asc: 'shelve_time:asc',
        s_p_asc: 'sales_price:asc',
        s_p_desc: 'sales_price:desc',
        p_d_desc: 'discount:desc',
        p_d_asc: 'discount:asc',
        skn_desc: 'product_skn:desc',
        skn_asc: 'product_skn:asc',
        activities_desc: 'activities.order_by:desc',
        activities_asc: 'activities.order_by:asc',
        s_n_asc: 'sales_num:asc',
        s_n_desc: 'sales_num:desc',
        activities_id_desc: 'activities.activity_id:desc',
        activities_id_asc: 'activities.activity_id:asc',
        brand_desc: 'brand_weight:desc'
    };

    params.status = 1; // 是否上架,1表示在架,2表示不在
    params.sales = 'Y'; // 只搜索销售的产品
    params.outlets = 2; // 非奥莱商品
    params.stocknumber = 1; // 过滤掉已售罄的商品
    params.attribute_not = 2; // 过滤掉赠品
    if (!data.order) {
        params.order = orderMaps.s_t_desc;
    } else {
        params.order = orderMaps[data.order] ? orderMaps[data.order] : '';
    }
    if (!data.page) {
        params.page = 1;
    }

    if (data.viewNum) {
        params.viewNum = data.viewNum;
    } else if (!data.limit) {
        params.viewNum = 60;
    } else {
        params.viewNum = data.limit;
        delete data.limit;
    }
    if (data) {
        params = Object.assign(data);
    }

    return searchApi.getProductList(params).then(result => {
        let ret = result.data;

        if (ret) {
            ret.channel = channel;
        }

        return ret;
    });
};

/**
 * 格式化频道页首次登陆导航数据
 * @param  {Object} data
 * @return {Object} formatData
 */
const formatIndexGuideData = data => {
    let channels = {
        boys: {gender: '1,3', limit: 1},
        girls: {gender: '2,3', limit: 1},
        lifestyle: {msort: 10, misort: '266,280,101,103,259', limit: 1},
        kids: {msort: 365, limit: 1}
    };
    let formatData = [];
    let promiseArr = [];

    _.forEach(data, item => {
        let channel = item.sort_name_en.toLowerCase().replace(' ', '');

        formatData.push({
            channel: channel,
            url: item.sort_url,
            sort_name: item.sort_name,
            sort_name_en: item.sort_name_en,
            content_code: item.content_code,
            src: '',
            num: 0
        });

        if (channels[channel]) {
            promiseArr.push(_formatParams(channel, channels[channel]));
        }
    });

    return Promise.all(promiseArr).then(result => {
        _.forEach(formatData, item => {
            _.forEach(result, it => {
                if (item && it && item.channel === it.channel) {
                    item.num = it.total;
                }
            });
        });

        return formatData;
    });
};

/**
 * 获取最新上架商品数据
 *
 * @param string $channel
 * @return array
 */
const getNewArrival = channel => {
    let rel = [],
        sortList = sortMap[channel],
        params = {
            order: 'shelve_time:desc',
            status: 1,
            sales: 'Y',
            attribute_not: 2,
            stocknumber: 3,
            dayLimit: 4
        };

    params.gender = channelMap[channel].gender;


    _.forEach(sortList, (item) => {
        let data = Object.assign(item, params, {limit: item.viewNum});

        rel.push(api.get('', Object.assign({
            method: 'web.search.newshelve'
        }, data), {cache: true}));
    });

    return Promise.all(rel).then(res => {
        let data = [],
            result = [];

        _.forEach(sortList, (it, index) => {
            let list = _.get(res[index], 'data.product_list', []);

            if (list.length === sortList[index].viewNum) {
                data = data.concat(list);
            }
        });

        _.forEach(data, (item) => {
            result.push(processProduct(item, {
                width: 280,
                height: 373,
                gender: params.gender
            }));
        });

        return result;
    });
};


/**
 * 获取频道页数据
 * @param  {String} type 传入频道页类型,值可以是: boys, girls, kids, lifestyle
 * @return {Object}
 */
const getContent = (type, req) => {
    let params = {};

    if (!req.user.uid) {
        params.new_device = 'Y';
    } else {
        params.uid = req.user.uid;
    }
    return Promise.all([headerModel.requestHeaderData(type), _requestContent(type, params)]).then(res => {

        let headerData = res[0].data || res[0],
            contentData = res[1].data ? res[1].data.list : res[1];

        let data = {};

        const processResult = _processFloorData(contentData, type);

        data = headerData;
        data.module = 'channel';
        data.page = 'channel';
        data.pageType = type;
        data.footerTop = true;
        data.channel = processResult.floors;


        return {
            rawData: contentData,
            floorData: data,
            searchPromise: processResult.promise,
            singlehotFloorIndex: processResult.singlehotFloorIndex,
            singlehotFloorTitle: processResult.singlehotFloorTitle,
            queryParams: processResult.queryParams,
            channelType: type
        };

    }).then(result => {

        // 如果有promise则做相应处理
        if (result.searchPromise.length) {
            return Promise.all(result.searchPromise).then(res => {
                _.forEach(res, (data, index) => {
                    result.floorData.channel
                        .splice(result.singlehotFloorIndex[index], 0,
                            _processFloorDataWithQueryReusult(
                                result.rawData,
                                result.queryParams[index],
                                data,
                                result.singlehotFloorTitle[index],
                                result.channelType
                            ));
                });

                return result.floorData;
            });
        } else {
            return result.floorData || result;
        }
    });
};


// 优选品牌楼层floorData-ajax
const getbrandFloorDataAjax = (type, req) => {
    let params = {};

    if (!req.user.uid) {
        params.new_device = 'Y';
    } else {
        params.uid = req.user.uid;
    }
    return _requestContent(type, params).then(res => {
        let contentData = res.data ? res.data.list : [];

        let data = {
            logoBrand: [],
            moreBrand: ''
        };

        _.forEach(contentData, (d, index) => {
            if (d.data && d.data.text && d.data.text.indexOf('优选品牌') >= 0) {
                _.forEach(contentData[index + 2].data, (floorData) => {
                    let o = {};

                    o.href = floorData.url;
                    o.img = helpers.image(floorData.src, 185, 86, 2);

                    data.logoBrand.push(o);
                });

                data.moreBrand = contentData[index + 3].data[0].url;
            }
        });

        return data;
    });
};

const getResourceData = (formatData) => {
    let promiseArr = [];

    _.forEach(formatData, item => {
        if (item.content_code) {
            promiseArr.push(_formatResourceParams(item.channel, item.content_code));
        }
    });
    return Promise.all(promiseArr).then(data => {
        _.forEach(formatData, (item, index) => {
            _.forEach(data, (it, idx) => {
                if (formatData[index].channel === data[idx].channel) {
                    formatData[index].src = data[idx].src;
                }
            });
        });

        return formatData;
    });
};

/**
 * 获取频道页首次登陆导航数据
 * @param  {String} type 传入频道页类型,值可以是: boys, girls, kids, lifestyle
 * @return {Object}
 */
const getIndexGuideData = () => {
    let params = {
        client_type: 'web',
        private_key: '0ed29744ed318fd28d2c07985d3ba633'
    };

    return serviceApi.get('operations/api/v6/category/getCategory', params, config.apiCache);
};

module.exports = {
    getNewArrival: getNewArrival,
    getContent: getContent,
    getbrandFloorDataAjax: getbrandFloorDataAjax,
    getIndexGuideData: getIndexGuideData,
    formatIndexGuideData: formatIndexGuideData,
    getResourceData: getResourceData

};