/**
 * 路由分发
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2016/4/27
 */

const _ = require('lodash');
const express = require('express');
const methods = require('methods');

const routerHold = (app) => {
    app.use = ((appUse) => {
        return (...args) => {
            let rootPath = '';
            const arg = args[0];

            if (typeof arg !== 'function') {
                rootPath = arg;
            }

            app.locals.rootPath = rootPath || '';

            return appUse.call(app, ...args);
        };
    })(app.use);

    express.Router = ((_router) => {
        const baseRouter = _router();

        return () => {
            let router = _router();

            methods.concat('all').forEach((method) => {
                router[method] = (path, ...args) => {
                    const arg = args[0];

                    if (typeof arg !== 'function') {
                        args = _.drop(args);

                        router.rootRouter = router.rootRouter || [];

                        router.rootRouter.push({
                            path: arg,
                            relatedPath: path,
                            method: method,
                            args: args
                        });
                    }

                    return baseRouter[method].call(router, path, ...args);
                };
            });

            return router;
        };
    })(express.Router);
};

module.exports = app => {
    routerHold(app); // 拦截app.use && router

    // 公共服务
    app.use('/common', require('./apps/common'));

    // 业务模块
    app.use(require('./apps/channel')); // 频道页
    app.use(require('./apps/activity')); // 专题活动等活动页面
    app.use('/product', require('./apps/product')); // 商品相关页面
    app.use(require('./apps/passport')); // 登录注册
    app.use('/home', require('./apps/home')); // 会员中心
    app.use(require('./apps/brands')); // 品牌一览
    app.use('/guang/news', require('./apps/news'));  // seo-潮流资讯页
    app.use('/guang', require('./apps/guang'));  // 逛
    app.use('/cart', require('./apps/cart'));// 购物车
    app.use('/help', require('./apps/help'));// 帮助中心
    app.use('/shop', require('./apps/shop'));// 店铺
    app.use(require('./apps/about')); // 关于有货
    app.use('/download', require('./apps/download')); // 下载
    app.use('/shopping', require('./apps/shopping')); // 支付中心

    // 第三方,如广告联盟
    app.use('/3party', require('./apps/3party'));
    app.use('/service', require('./apps/service')); // 客服
};