consult.js 3.01 KB
/**
 * home-我的咨询 业务逻辑
 * @author 陈轩 <xuan.chen@yoho.cn>
 */
'use strict';

const Promise = require('bluebird');
const moment = require('moment');
const _ = require('lodash');

const api = global.yoho.API;
const helpers = global.yoho.helpers;
const co = Promise.coroutine;

// 分页 函数
const pager = require(`${global.utils}/pager`).setPager;
const imgUtils = require(`${global.utils}/images`);


const NO_CONSULT = '您尚未咨询任何内容';

/**
 * 查询多个skn的默认商品
 * @param skns array
 * @return array
 */
function getProductGoodsInfo(skns) {
    const query = _.join(_.uniq(skns), ',');

    return api.get('', {
        method: 'h5.product.batch',
        limit: skns.length,
        productSkn: query,
        contain_all: 'Y'
    }).then(result => {
        let resData = {};

        _.forEach(_.get(result, 'data.product_list', []), good => {
            resData[good.product_skn] = good;
        });

        return resData;
    });
}

/**
 * 获取咨询列表
 */
exports.consultList = (uid, page, limit) => {
    page = Number.parseInt(page, 10) || 1;
    limit = Number.parseInt(limit, 10) || 10;

    const data = {
        uid: uid,
        page: page,
        limit: limit
    };

    const fetchConsults = co(function*(params) {
        let res = yield api.get('', Object.assign({
            method: 'web.personCen.buyConsult'
        }, params));

        return res;
    });

    // 处理fetchConsults的数据
    const processData = co(function*(res) {
        // 处理结果
        const result = {
            consults: [],
            pager: {}
        };
        let origin = res.data; // 原始数据
        const skns = [];


        if (res.code === 200 && origin && origin.consult_list && origin.consult_list.length) {
            origin.consult_list.forEach(consult => {
                skns.push(consult.skn);
            });

            let goodInfos = yield getProductGoodsInfo(skns);

            origin.consult_list.forEach(consult => {
                let info = {
                    href: helpers.getUrlBySkc(consult.skn),
                    name: consult.productName,
                    question: consult.ask || '',
                    consultTime: moment(consult.askTime * 1000).format('YYYY-MM-DD HH:mm:ss')
                };

                let goodInfo = goodInfos[consult.skn];

                if (goodInfo) {
                    info.thumb = imgUtils.getImageUrl(goodInfo.default_images, 60, 60);
                }

                if (consult.answer) {
                    info.reply = consult.answer;
                }

                result.consults.push(info);
            });

            result.pager = Object.assign({
                count: origin.total,
                curPage: page,
                totalPages: origin.page_total
            }, pager(origin.page_total, {page: page}));
        }
        if (!result.consults.length) {
            result.empty = NO_CONSULT;
        }

        return result;
    });

    return fetchConsults(data).then(processData);
};