favorite-service.js 11.4 KB
'use strict';

const Promise = require('bluebird');
const co = Promise.coroutine;
const _ = require('lodash');
const helpers = global.yoho.helpers;

const pager = require('./pager').handlePagerData;
const favoriteApi = require('./favorite-api');

const TABS = [
    {type: 'product', name: '商品收藏'},
    {type: 'brand', name: '品牌收藏'},
    {type: 'article', name: '文章收藏'}
];

const getFavoriteTabs = (type) => {
    type = type || 'product';

    return TABS.map((item) => {
        item.active = item.type === type;
        item.url = helpers.urlFormat('/home/favorite', {type: item.type});
        return item;
    });
};

const _getSortInfo = (categoryList, sort)=> {
    if (_.isEmpty(categoryList)) {
        return false;
    }

    let result = {};

    result.all = categoryList.map((category) => {
        return {
            name: category.category_name,
            url: helpers.urlFormat('/home/favorite', {sort_id: category.category_id}),
            count: category.num,
            focus: category.category_id === sort
        };
    });

    let defaultCategory = {
        name: '全部',
        url: helpers.urlFormat('/home/favorite'),
        count: _.sumBy(categoryList, category => category.num),
        focus: sort === 0
    };

    result.all.unshift(defaultCategory);
    result.default = result.all.slice(0, 7);
    return result;
};

const _getPager = (page, total, totalPage)=> {
    let result = {};

    if (page && total && totalPage) {
        result = {
            count: total,
            curPage: page,
            totalPages: totalPage,
            hasCheckAll: true
        };
    }
    return result;
};

const getGoodsInfo = (data, page, limit)=> {
    let result = data.slice((page - 1) * limit, page * limit).map((item) => {
        return {
            skn: item.product_id,
            img: helpers.image(item.image, 100, 100),
            name: item.product_name,
            url: helpers.getUrlBySkc(item.product_id, item.goodsId, item.cnAlphabet),
            price: item.sales_price,
            priceDown: item.price_down,
            buyNow: helpers.getUrlBySkc(item.product_id, item.goodsId, item.cnAlphabet),
            soldOut: item.storage === 0 ? true : '',
            hadNoticed: item.is_subscribe_reduction === 'Y' ? true : '',
            activites: {
                count: item.promotion_list ? item.promotion_list.length : 0,
                list: _.get(item, 'promotion_list', []).map((val) => {
                    return {
                        type: val.promotion_type,
                        name: val.promotion_title
                    };
                })
            }
        };
    });

    if (_.isEmpty(result)) {
        return {
            empty: '您没有收藏商品'
        };
    }

    return result;
};

/**
 * 降价提醒
 */
const _redutionCount = (uid)=> {
    return co(function*() {
        let data = yield favoriteApi.redutionCount(uid);
        let result = {
            count: 0,
            phone: '',
            url: '/home/favorite/reduction'
        };

        if (data.data.num) {
            result.count = +data.data.num;
            result.phone = data.data.mobile;
        }
        return result;
    })();
};


const favoriteProductListAsync = (uid, page, limit, selectedSort, subscribe, reduction, promotion, query) => {
    return co(function*() {
        let result = {
            sort: {},
            reduction: {},
            filter: {},
            goods: {},
            pager: {}
        };

        let product = yield favoriteApi.getFavoriteProductList(uid, 1, 500);

        result.sort = _getSortInfo(_.get(product, 'data.category_list'), selectedSort);
        result.reduction = yield _redutionCount(uid);

        let productList = (function() {
            let products = _.get(product, 'data.product_list', []);

            if (reduction === 'Y' && promotion === 'Y') {
                // 参加活动的降价商品
                return products.filter(pro => pro.is_price_down === 'Y' && pro.is_join_promotion === 'Y');
            } else if (selectedSort) {
                // 商品分类过滤
                return products.filter(pro => pro.category_id === selectedSort);
            } else if (subscribe === 'Y') {
                // 订阅降价通知过滤
                return products.filter(pro => pro.is_subscribe_reduction === 'Y');
            } else if (reduction === 'Y') {
                // 降价商品过滤
                return products.filter(pro => pro.is_price_down === 'Y');
            } else if (promotion === 'Y') {
                // 参加活动商品过滤
                return products.filter(pro => pro.is_join_promotion === 'Y');
            } else {
                return products;
            }
        }());

        result.filter = (function() {
            if (reduction === 'N' && promotion === 'N') {
                return {
                    reductionUrl: helpers.urlFormat('/home/favorite', {is_reduction: 'Y'}),
                    reductionChecked: '',
                    activityUrl: helpers.urlFormat('/home/favorite', {is_promotion: 'Y'}),
                    activityChecked: ''
                };
            } else if (reduction === 'N' && promotion === 'Y') {
                return {
                    reductionUrl: helpers.urlFormat('/home/favorite', {is_reduction: 'Y', is_promotion: 'Y'}),
                    reductionChecked: '',
                    activityUrl: helpers.urlFormat('/home/favorite'),
                    activityChecked: ''
                };
            } else if (reduction === 'Y' && promotion === 'N') {
                return {
                    reductionUrl: helpers.urlFormat('/home/favorite'),
                    reductionChecked: '',
                    activityUrl: helpers.urlFormat('/home/favorite', {is_reduction: 'Y', is_promotion: 'Y'}),
                    activityChecked: ''
                };
            } else {
                return {
                    reductionUrl: helpers.urlFormat('/home/favorite', {is_promotion: 'Y'}),
                    reductionChecked: '',
                    activityUrl: helpers.urlFormat('/home/favorite', {is_reduction: 'Y'}),
                    activityChecked: ''
                };
            }
        }());

        let total = productList.length;
        let pageTotal = Math.ceil(total / limit);

        page = page > pageTotal ? pageTotal : page;

        result.goods = getGoodsInfo(productList, page, limit);
        result.pager = pager(total, query);
        result.pager.hasCheckAll = true;

        return result;
    })();
};

const favoriteBrandListAsync = (uid, page, limit, type)=> {
    return co(function*() {
        let result = {
            brands: {
                empty: '您没有收藏品牌',
                pager: {}
            }
        };
        let brand = yield favoriteApi.favoriteBrandData(uid, page, limit);

        if (!brand.data || !brand.data.page_total) {
            return result;
        }

        if (!brand.data.brand_list) {
            return result;
        }

        result.brands = _.get(brand, 'data.brand_list', []).map((item) => {
            return {
                id: item.brand_id,
                brandOrShopType: item.brandOrShopType || '',
                shop_id: item.shop_id || '',
                img: helpers.image(item.brand_ico, 100, 100),
                url: helpers.urlFormat('', {shopId: item.shop_id || ''}, item.brand_domain),
                name: item.brand_name,
                naCount: item.new_product_num,
                colCount: item.brand_favorite_num
            };
        });

        let total = brand.data.total || 0;

        page = brand.data.page || 0;
        result.pager = pager(total, {page, limit, type});
        return result;
    })();
};

const favoriteArticleListAsync = (uid, udid, page, limit, type)=> {
    return co(function*() {
        let result = {};

        let articles = yield favoriteApi.favoriteArticleData(uid, udid, page, limit);

        result.articles = _.get(articles, 'data.data', []).map((item) => {
            return {
                id: item.id,
                name: item.title,
                img: helpers.image(item.src, 146, 96),
                desc: item.intro,
                url: helpers.urlFormat('/' + item.id + '.html', '', 'guang')
            };
        });

        let total = articles.data.total || 0;

        result.pager = pager(total, {page, limit, type});

        if (_.isEmpty(result.articles)) {
            result.articles = {
                empty: '你尚未收藏任何文章!'
            };
        }

        return result;
    })();
};

const newProductAsync = (uid, page, limit, id) => {
    return co(function * () {
        let products = yield favoriteApi.favoriteBrandData(uid, page, limit);

        return _.get(products, 'data.brand_list', []).reduce((total, cur) => {
            if (id !== cur.brand_id) {
                return total;
            }

            if (cur.new_product_num === 0) {
                return total;
            }

            total = _.concat(total, _.take(_.get(cur, 'new_product', []), 20).map((pro) => {
                return {
                    img: pro.default_images,
                    url: helpers.getUrlBySkc(pro.product_id, _.get(pro, 'goods[0].id', ''), _.get(pro, 'cnAlphabet')),
                    name: pro.product_name,
                    salePrice: pro.sales_price === pro.market_price ? '' : pro.sales_price,
                    marketPrice: pro.market_price
                };
            }));

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

const reductionAsync = (uid, page, limit) =>{
    let result = {};

    result.tabs = getFavoriteTabs('product');
    return favoriteProductListAsync(uid, page, limit, 0, 'Y').then((products) => {
        result.goods = products.goods;
        result.reductionUrl = helpers.urlFormat('/home/fovorite');
        return {
            meFavoritePage: true,
            meFavorite: result
        };
    });

};

const enableNoticeAsync = (uid, mobile, id) => {
    return co(function *() {
        let result = {
            code: 400,
            message: '订阅失败'
        };

        if (!uid || !mobile || !id) {
            return result;
        }

        let data = yield favoriteApi.redutionAdd(uid, mobile, id);

        if (data.code === 200) {
            result.code = 200;
            return data;
        }

        if (data.code === 500) {
            result.code = 500;
            switch (data.message) {
                case 'count must be  lt 5':
                    result.message = '您的订阅数已经到达上限';
                    break;
                case 'mobile must bu not null':
                    result.message = '请填写手机号';
                    break;
                default:
                    result.message = '订阅失败';
                    break;
            }
        }

        return result;
    })();
};

const disableNoticeAsync = (uid, id) => {
    return co(function * () {
        if (!uid || !id) {
            return {
                code: 400,
                message: '取消失败'
            };
        }

        return yield favoriteApi.redutionCancel(uid, id);
    })();
};

const cancelAsync = (uid, id, type) => {
    return favoriteApi.cancel[type](uid, id);
};

module.exports = {
    getFavoriteTabs,
    favoriteBrandListAsync,
    favoriteProductListAsync,
    favoriteArticleListAsync,
    newProductAsync,
    reductionAsync,
    enableNoticeAsync,
    disableNoticeAsync,
    cancelAsync
};