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

const path = require('path');
const Promise = require('bluebird');
const moment = require('moment');
const imgUtils = require(path.join(global.utils, 'images'));
const api = global.yoho.API;
const searchApi = global.yoho.SearchAPI;
const helpers = global.yoho.helpers;
const co = Promise.coroutine;

// 分页 函数
const pagerPath = path.join(global.appRoot, '/apps/product/models/public-handler.js');
const pager = require(pagerPath).handlePagerData;


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

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

    return searchApi.get('/search.json', {
        data: {
            query: query
        }
    });
}

/**
 * 获取咨询列表
 */
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('', {
            method: 'web.personCen.buyConsult',
            data: 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.length) {
            origin.consult_list.forEach(consult => {
                skns.push(consult.skn);
            });

            let goodInfos = yield getProductGoodsInfo(skns);

            origin.consult_list.forEach(consult => {
                let goodInfo = goodInfos[consult.skn];

                if (!goodInfo) {
                    return;
                }

                let info = {
                    href: helpers.getUrlBySkc(goodInfo.productId, goodInfo.goodsId, goodInfo.cn_alphabet),
                    thumb: imgUtils.getImageUrl(goodInfo.images_url, 60, 60, 1),
                    name: consult.productName,
                    question: consult.ask || '',
                    consultTime: moment(consult.askTime).format('YYYY-MM-DD H:m:s')
                };


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

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

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

        }
        if (!result.consults.length) {
            result.empty = NO_CONSULT;
        }

        return result;
    });


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