sale.js 10.1 KB
/**
 * 频道页面 model
 * @author: wsl<shuiling.wang@yoho.cn>
 * @date: 2016/05/17
 */
'use strict';
const library = '../../../library';
const utils = '../../../utils';
const API = require(`${library}/api`).API;
const ServiceAPI = require(`${library}/api`).ServiceAPI;
const sign = require(`${library}/sign`);
const logger = require(`${library}/logger`);
const helpers = require(`${library}/helpers`);
const camelCase = require(`${library}/camel-case`);
const resourcesProcess = require(`${utils}/resources-process`);
const productProcess = require(`${utils}/product-process`);
const _ = require('lodash');
const api = new API();
const serviceAPI = new ServiceAPI();
const anHour = 3600;
const aDay = anHour * 24;

/**
 * 需要格式化的时间格式
 */
const timeFormat = {
    d: '剩{d}天',
    h: '剩{h}小时',
    m: '剩{m}分钟',
    s: '剩{s}秒',
    dh: '剩{d}天{h}小时',
    dhms: '剩{d}天{h}小时{m}分钟{s}秒',
    hms: '剩{h}小时{m}分钟{s}秒',
    ms: '剩{m}分钟{s}秒'
};

/**
 * 排序转换
 */
const typeCont = {
    price: ['s_p_desc', 's_p_asc'],
    discount: ['p_d_desc', 'p_d_asc'],
    sale: ['s_n_desc', 's_n_asc'],
    newest: ['s_t_desc,s_s_desc', 's_t_asc,s_s_asc'],
    stock: ['s_s_desc', 's_s_asc']
};

const channelType = {
    boys: '1',
    girls: '2',
    kids: '3',
    lifeStyle: '4'
};

/**
 * 资源位code码
 */
const contentCode = {
    boys: {
        sale: '153180b9a88c0b565848850c523bb637',
        breakCode: 'd763e3f8d208cbed8f100253ea4f8946',
        vip: '6b9810a442efe1e6252b134154d36769'
    },
    girls: {
        sale: '0b2d133419a0f7c381306fd3522365e1',
        breakCode: '77258d0b526c7b6e243c1419877ead4a',
        vip: 'e83f3582df32b6753eed49fda236a755'
    },
    kids: {
        sale: 'de23648d28ee1e8a3f087a9dbac506f8',
        breakCode: '3f0898f1089b7bef5f3e071725c7a608',
        vip: '664935745012db6e2a96a7d57f75512f'
    },
    lifeStyle: {
        sale: '01269e498ff5b07756e0733ec0e88c75',
        breakCode: '0020a5762771aa16902a666c9491394e',
        vip: '647f1154d30b323ff46c787fc78aef65'
    }
};

class Sale {

    /**
     * 折扣专场专题列表过期时间处理
     * @param  {[string]} time
     * @return {[object]}
     */
    static processTime(time) {
        let data = {};
        let type = '';

        if (time < anHour) {
            data.warnColor = true;
            data.time = '低于1小时';
        } else {
            if (time > aDay) {
                type = 'dh';
            } else {
                type = 'h';
            }

            data.time = helpers.dateDiffFormat(timeFormat[type], time, 's');
        }

        return data;
    }

    /**
     * 折扣专场列表数据处理
     * @param  {[array]} list
     * @return {[array]}
     */
    static processDiscount(list, channel) {
        const formatData = [];
        let flag = true;

        list = list || [];
        list = camelCase(list);

        if (list.length === 1) {
            flag = false;
        }

        _.forEach(list, (data) => {
            if (flag === true) {
                data.specialUrl = `/product/sale/discount/detail?id=${data.id}&channel=${channel}`;
                _.merge(data, Sale.processTime(data.leftTime));
            }

            formatData.push(data);
        });

        return formatData;
    }

    /**
     * 折扣专场接口调用
     * @param  {[object]} params
     * @return {[array]}
     */
    static discount(params) {
        params = params || {};

        return api.get('', sign.apiSign(Object.assign({
            method: 'app.activity.get',
            sort: 2,
            plateform: 3
        }, params)));
    }

    /**
     * 断码区分类数据处理
     * @param  {[array]} list
     * @return {[array]}
     */
    static processBreakingSort(list) {
        const formatData = {};
        const sort = [];
        const sub = [];

        list = list || [];
        list = camelCase(list);

        _.forEach(list, (data, index) => {
            sort.push({
                sortName: data.sortName,
                sortId: data.sortId
            });
            data.sub.key = index;
            sub.push(data.sub);
        });

        formatData.sortData = sort;
        formatData.sub = sub;
        return formatData;
    }

    /**
     * 商品搜索接口请求
     * @param  {[object]} params
     * @return {[array]}
     */
    static searchSales(params) {

        // 排除基本筛选项默认值为0的对象
        for (let str in params) {
            if (str !== 'order' && params[str] === '0' || params[str] === null) {
                delete params[str];
            }
        }

        params.yh_channel = channelType[params.yh_channel];

        params = Object.assign({
            limit: '50'
        }, params);

        if (typeCont[params.type]) {
            params.order = typeCont[params.type][params.order];
        }

        return api.get('', sign.apiSign(Object.assign({
            method: 'app.search.sales'
        }, params)), true);
    }

    /**
     * 获取用户数据信息
     * @param  {[string]} uid
     * @return {[array]}
     */
    static getUserProfile(uid) {
        if (!uid) {
            return Promise.resolve({
                code: 200,
                data: {}
            });
        }
        return api.get('', sign.apiSign({
            method: 'app.passport.profile',
            uid: uid
        }), true);
    }

    /**
     * 获取资源位数据
     * @param  {[string]} page
     * @return {[array]}
     */
    static getResources(page, channel) {
        return serviceAPI.get('operations/api/v5/resource/get', sign.apiSign({
            content_code: contentCode[channel][page]
        })).then((result) => {
            if (result && result.code === 200) {
                return resourcesProcess(result.data);
            } else {
                logger.error('SALE 页面资源位返回 code 不是 200');
                return [];
            }
        });
    }

    /**
     * 获取断码区分类数据
     * @param  {[string]} yhChannel
     * @return {[object]}
     */
    static getBreakingSort(yhChannel) {
        return api.get('', sign.apiSign({
            method: 'app.sale.getBreakingSort',
            yh_channel: channelType[yhChannel] || '1'
        })).then((result) => {
            if (result && result.code === 200) {
                return Sale.processBreakingSort(result.data);
            } else {
                logger.error('断码区分类接口返回 code 不是 200');
                return {};
            }
        });
    }

    /**
     * 获取商品数据
     */
    static getSearchData(params, uid) {
        return Promise.all([
            Sale.searchSales(params).then((result) => {
                if (result && result.code === 200) {
                    return productProcess.processProductList(result.data.product_list || []);
                } else {
                    logger.error('SALE 商品搜索返回 code 不是 200');
                    return [];
                }
            }),
            Sale.getUserProfile(uid).then((result) => {
                if (result && result.code === 200) {
                    return result.data.vip_info ? camelCase(result.data.vip_info) : {};
                } else {
                    logger.error('获取用户信息返回 code 不是 200');
                    return {};
                }
            })
        ]);
    }

    /**
     * 获取筛选数据
     * @param  {[object]} params
     * @return {[array]}
     */
    static getFilterData(params) {
        return Sale.searchSales(params).then((result) => {
            if (result && result.code === 200) {
                return productProcess.processFilter(result.data.filter || [], {
                    hideSize: params.saleType === '1',
                    hideSort: params.saleType === '1'
                });
            } else {
                logger.error('SALE 商品搜索返回 code 不是 200');
                return [];
            }
        });
    }

    /**
     * 获取sale首页数据
     * @return {[array]}
     */
    static getSaleData(channel) {
        return Sale.getResources('sale', channel);
    }


    /**
     * 获取会员享数据
     * @return {[array]}
     */
    static getVipData(channel) {
        return Sale.getResources('vip', channel);
    }


    /**
     * 获取断码区数据
     * @param  {[object]} params
     * @return {[object]}
     */
    static getBreakCodeData(params) {
        params = params || {};
        return Promise.all([Sale.getResources('breakCode', params.yhChannel), Sale.getBreakingSort(params.yhChannel)])
        .then((result) => {
            return {
                content: result[0],
                nav: result[1]
            };
        });
    }

    /**
     * 获取折扣专场专题列表数据
     * @param  {[object]} params
     * @return {[object]}
     */
    static getDiscountData(params) {
        const discountData = {};

        return Sale.discount().then((result) => {
            if (result && result.code === 200) {
                discountData.data = Sale.processDiscount(result.data, params);
                return discountData;
            } else {
                logger.error('折扣专场专题列表返回 code 不是 200');
                return {};
            }
        });
    }

    /**
     * 获取折扣专场专题详情数据
     * @param  {[string]} id
     * @return {[object]}
     */
    static getDiscountDetailData(id) {
        let res = {};
        let param = {
            id: id
        };

        return Sale.discount(param).then((result) => {
            if (result && result.code === 200) {
                res = Sale.processDiscount(result.data);

                return {
                    title: res[0].title,
                    activity: {
                        coverUrl: res[0].coverUrl,
                        time: res[0].time,
                        leftTime: res[0].leftTime
                    }
                };
            } else {
                logger.error('折扣专场专题详情返回 code 不是 200');
                return {};
            }
        });
    }
}

module.exports = Sale;