search.js 8.53 KB
/**
 * search
 * @Author: sefon 2016-7-12 16:31:56
 */

'use strict';
const utils = '../../../utils';
const api = global.yoho.API;

const Promise = require('bluebird');
const co = Promise.coroutine;
const helpers = global.yoho.helpers;
const saleApi = require('./sale-api');
const searchApi = require('./search-api');
const headerModel = require('../../../doraemon/models/header');
const productProcess = require(`${utils}/product-process`);
const searchHandler = require('./search-handler');
const _ = require('lodash');
const needParams = ['query', 'msort', 'misort'];

exports.getKeyActivity = (query) => {
    return searchApi.getKeyActivityAsync(query).then(result => {
        return _.get(result, 'data.urlobj.pcUrl', '');
    });
};

/**
 * 转换价格
 *
 * @param float|string $price 价格
 * @return float|string 转换之后的价格
 */
const transPrice = (price) => {
    return price ? (price * 1).toFixed(2) : '0.00';
};

/**
 * 获取搜索数据
 * @param  {[type]} origin [description]
 * @return {[type]}        [description]
 */
exports.getSearchData = (params, channel) => {

    let searchParams = searchHandler.getSearchParams(params);

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

    // 调用接口
    let apiMethod = [
        headerModel.requestHeaderData(channel),
        searchApi.getSortList(Object.assign({}, searchParams, {msort: '', misort: '', sort: ''})),
        searchApi.getProductList(searchParams),
        searchApi.getShopList(params)
    ];

    return api.all(apiMethod).then(result => {
        let finalResult = {
            headerData: Object.assign(result[0].headerData, {
                header: true
            }),
            search: {}
        };

        // 获取左侧类目数据
        if (result[1].code === 200) {
            let dps = {};

            _.forEach(needParams, (value) => {
                if (params[value]) {
                    dps[value] = params[value];
                }
            });

            finalResult.search = {
                leftContent: searchHandler.handleSortData(result[1].data.sort, dps, params),
                isSearch: true
            };
        }

        // 获取商品数据和顶部筛选条件
        if (result[2].code === 200) {

            let filters = Object.assign(searchHandler.handleFilterDataAll(result[2].data, params),
                finalResult.search.leftContent.sort);
            let termsSuggestion = _.get(result[2], 'data.suggestion.terms_suggestion', []);

            filters.checkedConditions.conditions = _.concat(filters.checkedConditions.conditions,
                finalResult.search.leftContent.checked);

            Object.assign(finalResult.search,
                searchHandler.handlePathNavData({total: result[2].data.total }, params, 'search', channel),
                {
                    filters: filters,
                    opts: searchHandler.handleOptsData(params, result[2].data.total, result[2].data.filter),
                    totalCount: result[2].data.total,
                    footPager: searchHandler.handlePagerData(result[2].data.total, params),
                    goods: productProcess.processProductList(result[2].data.product_list,
                        Object.assign({showDiscount: false, from: {type: 'search', params: params}}, params)),
                    latestWalk: 6,
                    hasNextPage: searchHandler.handleNextPage(params, result[2].data.total),
                    shopEntry: result[3],
                    name: params.query,
                    suggest: (termsSuggestion.length !== 0) ? termsSuggestion.slice(0, 3) : false,
                    changedQuery: result[2].data.isChangedQuery === 'Y',
                    suggestFirst: finalResult.search.suggestFirst,
                    suggestSecond: finalResult.search.suggestSecond
                });

            if (finalResult.search.changedQuery) {

                finalResult.search.suggestFirst = finalResult.search.suggest[0];
                finalResult.search.suggestSecond = _.slice(termsSuggestion, 1, termsSuggestion.length).splice(0, 3);
            }

            finalResult.criteo = {skn: searchHandler.getCriteo(_.get(finalResult.search, 'goods'))};
        }
        return finalResult;
    });
};

/**
 * 搜索提示
 */
exports.getSuggest = (params) => {
    return searchApi.getSuggest(params).then(result => {
        let dest = [];

        if (result.code === 200) {
            dest = searchHandler.handleSuggest(result.data);
        }

        return dest;
    });
};

exports.getListBrandsFilter = (params, nparams) => {
    return searchApi.getBrands4Filter(Object.assign({}, params, nparams)).then(result => {
        let dest = [];

        if (result.code === 200) {
            dest = searchHandler.handleFilterBrands(result.data, params);
        }

        return dest;
    });
};

exports.getBrands4Filter = (params) => {

    let nparams = {};

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

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

    if (params && params.from) {
        nparams.from = params.from;
        delete params.from;
    }

    // 生成路径包含callback 导致多次调用多个 callback问题
    if (params && params.callback) {
        delete params.callback;
    }

    if (params.specialsale_id) {
        return saleApi.getSaleSpecialAsync(params.specialsale_id).then(special => {
            if (special && special.data) {
                let data = special.data;

                // 传品牌ID参数
                if (data.brand_id) {
                    nparams.brand = data.brand_id;
                }

                // 传促销id,促销id为空时传专区id
                if (data.ispromotion) {
                    nparams.promotion = data.ispromotion;
                }
            }

            return this.getListBrandsFilter(params, nparams);
        });
    }

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

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

    return this.getListBrandsFilter(params, nparams);
};


/**
 * 搜索少或无 可能喜欢
 * @param int $page 分页页码

 * @return array

 * */
exports.getSearchLessProduct = (channelNum, uid, udid, page) => {
    return co(function * () {

        let result = {

            code: 200,
            message: '',
            data: {

                header: '可能喜欢的商品',
                hasPrev: false,
                hasNext: false,
                item: null

            }
        };

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

        let together = yield searchApi.lessRecommend(channelNum, uid, udid, '100003', 20);

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

        if (!_.get(together, 'data.product_list')) {
            return result;
        }

        result.data.hasPrev = true;
        result.data.hasNext = true;

        result.data.item = _.map(together.data.product_list, it => {

            let item = {
                id: it.product_id,
                skn: it.product_skn,
                title: it.product_name,
                img: it.default_images ? helpers.image(it.default_images, 180, 240) : '',
                alt: it.product_name,
                price: '¥' + transPrice(it.sales_price),
                marketPrice: '¥' + transPrice(it.market_price)
            };

            let firstGoods = it.goods_list && it.goods_list[0];
            let productSkc = firstGoods && firstGoods.product_skc;

            item.href = helpers.getUrlBySkc(it.product_id, productSkc, it.cn_alphabet);

            return item;

        });


        // 当数据量不足6个时,判定为没有下一页

        if (page === 1) {
            result.data.hasPrev = false;
        }

        if (!result.data.item || result.data.item.length < 6) {
            result.data.hasNext = false;
        }

        return result;

    })();

};