global.js 9.82 KB
/**
 * 商品促销 model
 * @author: yyq<yanqing.yang@yoho.cn>
 * @date: 2017/4/6
 */

'use strict';

const _ = require('lodash');

const helpers = global.yoho.helpers;

const homeService = require('./home-service');
const globalApi = require('./global-api');
const headerModel = require('../../../doraemon/models/header');
const searchHandler = require('./search-handler');
const pager = require(`${global.utils}/pager`).setPager;
const productProcess = require(`${global.utils}/product-process`);

const GLOBAL_LIST_URI = '/product/global/list';

const _handelGlobalPathNav = (data, channel, page) => {
    let rootName = '首页';

    if (channel && _.isString(channel)) {
        rootName = `${channel.toUpperCase()}首页`;
    }

    let pathNav = [{
        href: channel === 'boys' ? '/' : helpers.urlFormat(`/${channel}/`),
        name: rootName,
        pathTitle: rootName
    }, {
        href: helpers.urlFormat(GLOBAL_LIST_URI),
        name: '全球购',
        pathTitle: '全球购'
    }];

    if (data.sort) {
        pathNav.push({
            href: helpers.urlFormat(GLOBAL_LIST_URI, data.sort.params),
            name: data.sort.name,
            pathTitle: data.sort.name
        });
    }

    if (data.brand) {
        pathNav.push({
            name: data.brand.name,
            pathTitle: data.brand.name
        });
        page = 'global-brand';
    }

    return {
        pathNav: pathNav,
        listType: page
    };
};

const _checkSortEqual = (rp, params) => {
    let status = true;

    _.forEach(rp, (value, key) => {
        if (status && params[key] !== value) {
            status = false;
        }
    });

    return status;
};

const _handelGlobalSort = (origin, params, originParams) => {
    let all = [{
        name: '全部品类',
        href: `${searchHandler.handleFilterUrl(params, {}, {msort: true, misort: true, sort: true})}`
    }];
    let list = [];
    let selectSort = {};

    _.forEach(origin, value => {
        let equalCategory = _checkSortEqual(value.relation_parameter, originParams);
        let category = {
            name: value.category_name,
            num: value.node_count,
            childList: [
                {
                    name: `全部${value.category_name}`,
                    num: value.node_count,
                    href: `${searchHandler.handleFilterUrl(params, value.relation_parameter)}`,
                    childActive: _checkSortEqual(value.relation_parameter, originParams)
                }
            ]
        };

        if (equalCategory) {
            Object.assign(selectSort, {
                name: value.category_name,
                params: value.relation_parameter
            });
        }

        _.forEach(value.sub, subValue => {
            let child = {
                name: subValue.category_name,
                num: subValue.node_count,
                href: `${searchHandler.handleFilterUrl(params, subValue.relation_parameter)}`,
                childActive: _checkSortEqual(subValue.relation_parameter, originParams)
            };

            category.childList.push(child);

            if (child.childActive) {
                category.active = true;
                Object.assign(selectSort, {
                    name: subValue.category_name,
                    params: subValue.relation_parameter
                });
            }
        });

        list.push(category);
    });

    return {
        allSort: {
            all: all,
            list: list
        },
        selectSort: selectSort
    };
};

const getGlobalProductListData = (params, yoho) => {
    let dps = {};

    if (params.brand) {
        dps.brand = params.brand;
    }

    return Promise.props({
        header: headerModel.requestHeaderData(yoho.channel),
        fullList: globalApi.getGlobalProductListAsync(Object.assign({
            physical_channel: yoho.channelNum,
            limit: 1
        }, dps)),
        list: globalApi.getGlobalProductListAsync(Object.assign({
            physical_channel: yoho.channelNum
        }, params, {limit: params.limit ? params.limit - 1 : 59}))
    }).then(result => {
        let resData = {};

        Object.assign(resData, result.header);

        if (result.list.code === 200) {
            let listData = _.get(result.list, 'data', {});
            let totalNum = _.get(listData, 'total', 0);

            // opts 显示新品、折扣
            listData.filter = listData.filter || {};
            Object.assign(listData.filter, {
                new: 'Y',
                specialoffer: 'Y'
            });

            resData.list = {
                leftContent: _handelGlobalSort(_.get(result.fullList, 'data.filter.group_sort', []), dps, params),
                filters: searchHandler.handleFilterDataAll(listData, params),
                opts: searchHandler.handleOptsData(params, totalNum, listData.filter),
                totalCount: totalNum,
                footPager: pager(_.get(listData, 'page_total', 0), params),
                goods: productProcess.processProductList(_.get(listData, 'product_list', []),
                    Object.assign({showDiscount: false, isGlobal: true}, params)),
                hasNextPage: searchHandler.handleNextPage(params, totalNum),
                latestWalk: 6 // 最近浏览记录
            };

            if (resData.list.filters && resData.list.filters.brand) {
                _.set(resData.list, 'filters.brand.showAllBrands', true); // 设置首次展示品牌筛选所有品牌
            }

            // pathNav brand
            let pathInfo = {};

            if (dps.brand) {
                let bandInfo = _.find(_.get(result.fullList, 'data.filter.brand', []), o => {
                    return o.id * 1 === dps.brand * 1;
                });

                if (bandInfo) {
                    pathInfo.brand = {
                        name: bandInfo.brand_name
                    };
                }
            }

            // psthNav sort
            let selectedSort = _.get(resData.list, 'leftContent.selectSort', {});

            if (!_.isEmpty(selectedSort)) {
                pathInfo.sort = selectedSort;
            }

            Object.assign(resData.list, _handelGlobalPathNav(pathInfo, yoho.channel, 'global-list'));
        }

        return resData;
    });
};

const getGlobalProductDetailData = (skn, channelNum, channel) => {
    return Promise.props({
        header: headerModel.requestHeaderData(channel),
        detail: globalApi.getGlobalProductDetailAsync(skn, channelNum),
        html: globalApi.getGlobalProductHtmlAsync(skn, channelNum)
    }).then(result => {
        let resData = {};
        let detailInfo, html = '';

        if (+result.detail.code === 200) {
            detailInfo = _.get(result, 'detail.data', {});

            let brandInfo = detailInfo.brand_info || {};

            resData.banner = {
                bgColor: '#000',
                homeUrl: helpers.urlFormat(GLOBAL_LIST_URI, {brand: brandInfo.brand_id}),
                brandName: brandInfo.brand_name,
                logo: brandInfo.brand_ico
            };

            resData.pathNav = _.concat(
                homeService.getHomeChannelNav(channel),
                [
                    {name: '全球购', href: helpers.urlFormat(GLOBAL_LIST_URI)},
                    {name: detailInfo.product_name || ''}
                ]
            );

            if (detailInfo.orign_price - detailInfo.final_price === 0) {
                _.unset(detailInfo, 'formart_orign_price');
            } else {
                detailInfo.promotion = ((detailInfo.final_price / detailInfo.orign_price) * 10).toFixed(1);

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

            if (detailInfo.market_price - detailInfo.sales_price === 0) {
                _.unset(detailInfo, 'format_market_price');
            }

            if (!_.isEmpty(detailInfo.goods_list)) {
                let colors = [];

                _.forEach(detailInfo.goods_list, (value, index) => {
                    let size = [];


                    _.forEach(value.size_list || [], subVal => {
                        size.push({
                            sku: subVal.product_sku,
                            name: subVal.size_name,
                            soldOut: subVal.storage_number * 1 <= 0
                        });
                    });


                    if (_.isEmpty(value.images_list)) {
                        value.images_list = [{
                            image_url: value.color_image
                        }];
                    }

                    if (index === 0 && !detailInfo.mainThumb) {
                        value.focus = true;
                        detailInfo.mainThumb = _.get(value, 'images_list[0].image_url', value.color_image);
                    }

                    colors.push({
                        src: value.color_image,
                        name: value.color_name,
                        title: value.color_name,
                        imgList: value.images_list,
                        focus: value.focus,
                        size: size
                    });
                });

                detailInfo.colors = colors;
                _.set(detailInfo, 'bundle.count', 1); // 设置默认数量为1
            }
        }

        if (result.html && !_.get(result.html, 'code', '')) {
            let regContent = /<body[^>]*>([\s\S]*)<\/body>/.exec(result.html);

            html = regContent[1] || '';
            html = html.replace(/<script.*?>.*?<\/script>/ig, '');
        }

        Object.assign(resData, result.header, {
            goodsInfo: detailInfo,
            detailHtml: html || ''
        });

        return resData;
    });
};

module.exports = {
    getGlobalProductListData,
    getGlobalProductDetailData
};