/**
 * 路由重写
 * @author: chenfeng<feng.chen@yoho.cn>
 * @date: 2017/2/20
 */
'use strict';

const typeLib = require('../../config/type-lib');
const _ = require('lodash');
const utils = require('../../utils');
const helpers = global.yoho.helpers;
const listParamsProcess = require('../../utils/list-params-process');
const stringProcess = require('../../utils/string-process');

/**
 * 解析url规则中的参数
 */
const resolve = (req, res, next) => {
    let path,
        params = {
            channel: req.yoho.channel
        };

    path = _.join(_.map(req.params, v => {
        return v;
    }), '-');

    if (!path) {
        return next();
    }
    let conditions = path.split('-').filter(cond => cond);

    _.each(conditions, condition => {
        if (typeLib.channels[condition]) {
            params.channel = condition;
        } else if (condition.indexOf('_') >= 0) {
            let item = condition.split('_');

            if (item.length === 2) {
                params[item[0]] = item[1];
            }
        } else if (condition >= 0 && !params.id) {
            params.id = _.parseInt(condition);
        }
    });
    req.yoho.channel = params.channel;
    res.locals.channel = params.channel;
    res.locals.pageChannel = { [params.channel]: true };
    res.locals.setChannel = true;
    Object.assign(req.query, params);
    next();
};

/**
 * 简介channel参数
 */
const channel = (req, res, next) => {
    let channelName;

    if (req.query.channel) {
        if (req.query.channel >= 0) {
            channelName = typeLib.channelNames[req.query.channel];
        } else if (typeLib.channels[req.query.channel]) {
            channelName = req.query.channel;
        }
    } else if (req.query.gender) {
        let gender = req.query.gender;

        switch (gender) {
            case typeLib.gender.boys:
                gender = 1;
                break;
            case typeLib.gender.girls:
                gender = 2;
                break;
            case typeLib.gender.kids:
                gender = 3;
                break;
            case typeLib.gender.lifestyle:
                gender = 4;
                break;
            default:
                break;
        }
        channelName = typeLib.channelNames[gender];
    }
    channelName = channelName || req.yoho.channel;
    req.yoho.channel = channelName;
    delete req.query.channel;
    delete req.query.gender;
    next();
};

/**
 * 参数排序
 */
const sortParams = (req, res, next) => {
    let sorts = utils.mapSort(req.query);
    let queryKeys = _.keys(req.query);
    let index = 0;
    let matched = _.map(sorts, (val, key) => {
        return key === queryKeys[index++];
    });

    if (_.every(matched, match => match)) {
        return next();
    } else {
        let subdomain = 'list';

        if (req.hostname.indexOf('search') === 0) {
            subdomain = 'search';
        }

        return res.redirect(helpers.urlFormat('/', sorts, subdomain));
    }
};

/**
 * 解析 Path 类型泛商品列表 URL 的参数
 */
const resolvePathParams = (req, res, next) => {
    let queryParams = req.query;
    let pathParams = req.params.pathParams;

    // 1. 取 path 的参数
    req.query = listParamsProcess.getParams(pathParams);

    // 2. 取查询字符串参数
    _.assign(req.query, queryParams);

    // 3. 取 params 参数
    if (req.params) {
        if (req.params.pathParams) {
            delete req.params.pathParams;
        }
        _.assign(req.query, req.params);
    }

    if (req.query) {
        _.forEach(req.query, (perParam, index) => {
            req.query[index] = stringProcess.paramsFilter(perParam);
        });
    }
    return next();
};

/**
 * 解析 Path 类型泛商品列表异步请求中 URL 的参数
 */
const resolvePathParamsAjax = (req, res, next) => {
    let pathParams = _.last(_.split(req.query.currentUrl, '/'));
    let currentUrlParams = listParamsProcess.getParams(pathParams);

    delete req.query.currentUrl;

    _.assign(req.query, currentUrlParams);

    return next();
};

/**
 * 解析 Path 类型店铺商品列表异步请求中 URL 的参数
 */
const resolveShopPathParamsAjax = (req, res, next) => {
    let shopId;
    let currentUrlParams;
    let pathSplitArr = _.compact(_.split(req.query.currentUrl, '/'));
    let pathParams = _.last(pathSplitArr);

    if (pathSplitArr.length === 2) {
        shopId = _.last(_.split(pathParams, '-'));
    } else {
        currentUrlParams = listParamsProcess.getParams(pathParams);

        let shopInfoPath = _.replace(req.query.currentUrl, `/${pathParams}`, '');

        shopId = _.last(_.split(shopInfoPath, '-'));
    }

    delete req.query.currentUrl;

    _.assign(req.query, currentUrlParams, {shop_id: shopId});

    return next();
};

module.exports = {
    resolve,
    channel,
    sortParams,
    resolvePathParams,
    resolvePathParamsAjax,
    resolveShopPathParamsAjax
};