hot-keywords.js 7.08 KB
/**
 *
 * @author: yyq<yanqing.yang@yoho.cn>
 * @date: 18/5/10
 */

const _ = require('lodash');
const fs = require('fs');
const Req = require('request-promise');
const moment = require('moment');
const Router = require('koa-router');
const r = new Router();
const Mysql = require('../../../lib/mysql-promise');
const pager = require('../utils/pager');
const xlsx = require('xlsx');

const config = require('../../../config/config');
const singleBrandKeyPre = config.singleBrandKeyPre;
const singleSortKeyPre = config.singleSortKeyPre;


//通过小分类同步中分类和大分类
const getMsort = async(ctx) => {
    let redis = ctx.redis;

    return redis.getAsync(`global:yoho:sorts`).then((sorts) => {
        let sData = {};
        sorts = JSON.parse(sorts) || [];

        _.forEach(_.get(sorts, 'data.sort'), (msort) => {
            _.forEach(_.get(msort, 'sub'), (misort) => {
                _.forEach(_.get(misort, 'sub'), (sort) => {
                    if (!sData[sort.sort_id]) {
                        sData[sort.sort_id] = {
                            msort: msort.sort_id,
                            msort_name: msort.sort_name,
                            misort: misort.sort_id,
                            misort_name: misort.sort_name,
                            sort_id: sort.sort_id,
                            sort_name: sort.sort_name,
                        };
                    }
                })
            })
        })

        return sData;
    });
};

r.get('/list', async(ctx) => {
    let resData = {};
    let q = ctx.request.query || {};
    let query = q.query || '';
    let page = parseInt(`0${q.page}`, 10) || 1;
    let limit = parseInt(`0${q.limit}`, 10) || 10;
    let mysql = new Mysql();
    let total = 0;
    let typeList = [
        {
            type: 'keyword',
            name: '关键词'
        },
        {
            type: 'wordroot',
            name: '词根ID'
        },
        {
            type: 'goodnum',
            name: '商品数'
        }
    ];
    let type = q.type || typeList[0].type;
    let typeName = _.result(_.find(typeList, {'type': type}), 'name') || typeList[0].name;
    let wheres = '';
    let conditions = [];

    if (q.hot) {
        wheres += ' AND is_hot = 1';
    }

    switch (query && type) {
        case 'keyword':
            wheres += ` AND keyword like '%%${query}%'`;
            break;
        case 'wordroot':
            wheres += ' AND root_id = ?'
            conditions.push(query);
            break;
        case 'brand':
            wheres += ' AND brand_id = ?'
            conditions.push(query);
            break;
        case 'sort':
            wheres += ' AND sort_id = ?'
            conditions.push(query);
            break;
        case 'goodnum':
            wheres += ' AND yoho_goods_num >= ?'
            conditions.push(query);
            break;
    }

    let d = await mysql.query(`SELECT COUNT(*) as total FROM seo_keywords WHERE status = 1 ${wheres}`, conditions);

    resData.total = d[0] && d[0].total || 0;
    conditions.push((page - 1) * limit, limit);

    d = await mysql.query(`SELECT * FROM seo_keywords WHERE status = 1 ${wheres} ORDER BY id DESC limit ?, ?`, conditions);

    let sortIds = [];

    sortIds = await getMsort(ctx);

    resData.keywords = _.map(d, (elem) => {
        const _sortId = sortIds[elem.sort_id];

        return Object.assign({}, elem, {
            sortName: _sortId && _sortId.sort_name,
            misortName: _sortId && _sortId.misort_name,
            msortName: _sortId && _sortId.msort_name,
            is_push: elem.is_push ? '是' : '否',
            add_time:  elem.add_time && moment(elem.add_time * 1000).format('YYYY-MM-DD HH:mm'),
        });
    });

    resData.typeList = typeList;
    resData.typeName = typeName;
    resData.type = type;
    resData.query = query;

    return ctx.body = {
        code: 200,
        message: 'success',
        data: resData
    };
});


r.post('/save', async (ctx) => {
    let mysql = new Mysql();
    let id = ctx.request.body.id || 0;
    let keyword = ctx.request.body.keywords;
    let brand = ctx.request.body.brand || 0;
    let msort = ctx.request.body.msort || 0;
    let misort = ctx.request.body.misort || 0;
    let sort = ctx.request.body.sort || 0;
    let describe = ctx.request.body.describe || '';
    let goods_img = ctx.request.body.goodsImg || '';
    let is_hot = ctx.request.body.isHot || 0;
    let addTime = Date.parse(new Date())/1000;

    if (id) {
        return mysql.query(`UPDATE seo_keywords SET \`describe\` = '${describe}', goods_img = '${goods_img}'  WHERE id = ${id}`).then(d => {
            return ctx.body = {
                code: 200,
                message: 'success',
                data: d
            };
        });
    }

    let result = {code: 400, message: ''};

    if (!keyword) {
        result.message = '关键词必填';
        return ctx.response.body = result;
    }

    let select = await mysql.query(`select id from seo_keywords where keyword='${keyword}' limit 1`);

    if (_.get(select, '[0].id', 0) > 0) {
        result.message = '关键词已经存在';
        return ctx.response.body = result;
    }

    await mysql.query(`insert into seo_keywords (keyword, brand_id, msort, misort, sort_id, add_time, \`describe\`, goods_img, is_hot) values ('${keyword}', ${brand}, ${msort}, ${misort}, ${sort}, ${addTime}, '${describe}', '${goods_img}', ${is_hot})`);

    result.code = 200;
    return ctx.response.body = result;
});

r.post('/upload', async(ctx) => { // 导入关键词EXCEL
    if (ctx.request.body._files) {
        let file = ctx.request.body._files.up_excel;
        const workbook = xlsx.readFile(file.path);
        const sheetNames = workbook.Props.SheetNames;
        const worksheet = workbook.Sheets[sheetNames[0]];

        let json_data = xlsx.utils.sheet_to_json(worksheet);
        console.log(json_data);
        let post_data = [];
        _.each(json_data, (obj, index) => {
            if (obj.keyword) {
                post_data.push({
                    id: index,
                    keyword: obj.keyword,
                    describe: obj.describe || ''
                })
            }
        });
        console.log(post_data);
        if (post_data.length > 0) {
            return Req({ // 传数据给爬虫接口
                method: 'POST',
                uri: 'http://spiderwebhook.yoho.cn/importApiHot', // 'http://172.16.6.84:9100/importApiHot',
                body: {
                    keywords: post_data
                },
                json: true,
                timeout: 5000
            }).then(res => {
                // console.log('res:', res);
                return ctx.response.body = res;
            }).catch(err => {
                // console.log(err);
                return ctx.response.body = {
                    code:  301,
                    message: '接口数据处理错误'
                }
            });

        } else {
            return ctx.response.body = {
                code:  400,
                data: post_data,
                message: 'excel无数据或数据格式不正确!'
            }
        }


    }
});

module.exports = r;