product_cache.js 5.77 KB
/**
 *
 * @author: chenfeng<feng.chen@yoho.cn>
 * @date: 16/10/20
 */
'use strict';
const Model = require('./model');
const rp = require('request-promise');
const ws = require('../../lib/ws');
const sign = require('../../lib/sign');
const _ = require('lodash');

class ProductCache extends Model{
    constructor() {
        super('product_cache');
    }
    async removePriceCache(list) {
        let self = this;
        let apis = await self.findAll();

        if (!apis.length) {
            return;
        }
        let url = apis[0].priceCacheApi;
        self._broadcast(`开始提交:批量变价`);
        await self._batchPost(list, url);
    }
    async removeProductCache(list) {
        let self = this;
        let apis = await self.findAll();

        if (!apis.length) {
            return;
        }
        let url = apis[0].productCacheApi;
        self._broadcast(`开始提交:其它批量`);
        await self._batchPost(list, url);
    }
    async generateProductUrl(list) {
        let self = this;
        let interval = 50;
        let tick = parseInt(list.length / interval, 10) + (list.length % interval > 0 ? 1 : 0);
        let result = [];
        self._broadcast(`获取商品信息中:`);
        for (var tickIndex = 0; tickIndex < tick; tickIndex++) {
            let datas = list.slice(tickIndex * interval, (tickIndex + 1) * interval > list.length ? list.length : (tickIndex + 1) * interval);
            try {
                let sknList = [];
                _.forEach(datas, data => {
                    sknList.push(data.skn)
                })
                let skns = sknList.join(',');
                self._broadcast(`进度:${tickIndex+1}/${tick}`)
                let res = await self._batchProductInfo(skns);
                _.forEach(res.data.product_list, (product) => {
                    result.push(self._joinProductUrl(product));
                });
            } catch(exp) {
            }
        }
        self._broadcast(`获取完成,正在生成文件`);
        return result;
    }
    async _batchProductInfo(skns) {
        let params = {
            productSkn: skns,
            method: 'h5.product.batch'
        }
        params = sign.apiSign(params, 'h5', '5.1.0', '');
        return new Promise((resolve, reject) => {
            rp({
                url: 'http://api.yoho.cn/',
                qs: params,
                json: true,
                timeout: 3000,
                gzip: true
            })
            .then(function (res) {
                res.code === 200 ? resolve(res) : reject(res);
            })
            .catch(function (err) {
                if (err.response) {
                    console.log(err.response.body);
                    reject(err.response.body)
                }
            });
        })
    }
    _joinProductUrl(product) {
        if (product && product.goods_list && product.goods_list.length) {
            return `/product/pro_${product.product_id}_${product.goods_list[0].goods_id}/${product.cn_alphabet}.html`;
        }
        return '';
    }
    rendExcel(sheets) {
        if (sheets.length) {
            let rows = sheets[0].data;
            if (rows.length > 1) {
                let data =  [];
                for (var i = 1; i < rows.length; i++) {
                    var row = rows[i];
                    if (row.length) {
                        data.push({skn: row[0]});
                    }
                }
                return data;
            }
        }
        return [];
    }
    async _batchPost(list, url) {
        let self = this;
        let interval = 50;
        return new Promise(async (resolve, reject) => {
            let tick = parseInt(list.length / interval, 10) + (list.length % interval > 0 ? 1 : 0);
            let post = async (i, len) => {
                if (i < len) {
                    let limit = list.length > (i + 1) * interval ? (i + 1) * interval : list.length;
                    let datas = list.slice(i * interval, limit);
                    try {
                        let skns = [];
                        _.forEach(datas, data => {
                            skns.push(data.skn)
                        })
                        await self._postApi(skns, url);
                        self._broadcast(`进度:${limit}/${list.length}`)
                    } catch(err) {
                        self._broadcast(`错误:${err.message}`)
                    }
                    setTimeout(async () => {
                        await post(++i, tick);
                    }, 500);
                } else {
                    self._broadcast(`提交完成!`);
                    resolve();
                }
            }
            await post(0, tick);
        });
    }
    async _postApi(data, url) {
        return new Promise((resolve, reject) => {
            rp({
                method: 'POST',
                uri: url,
                body: data,
                json: true
            })
            .then(function (res) {
                res.code === 200 ? resolve(res) : reject(res);
            })
            .catch(function (err) {
                if (err.response) {
                    console.log(err.response.body);
                    reject(err.response.body)
                }
            });
        })
        
    }
    _broadcast(message) {
        console.log(message)
        ws.broadcast(`/product_cache/log`, {
            message: message
        });
    }
    async init() {
        let count = await this.count({});

        if (count === 0) {
            await this.insert({
                priceCacheApi: 'http://service-test3.yohops.com:9999/erp/clear/batch/productPriceCache',
                productCacheApi: 'http://service-test3.yohops.com:9999/erp/clear/batch/productCache'
            });
        }
    }
}
module.exports = ProductCache;