/*
 * @Author: Targaryen
 * @Date:   2016-06-02 15:50:47
 * @Last Modified by:   Targaryen
 * @Last Modified time: 2016-06-22 18:36:26
 */



'use strict';
const _ = require('lodash');
const helpers = global.yoho.helpers;

const parameter = require(`${global.utils}/parameter`);

const handleStaticFilterUrl = parameter.fullParamToMinPath;


/**
 * 处理用于筛选的 URL , 拼接 URL 参数
 * @param originParam 当前 URL 中的参数
 * @param newParam 要拼接的 参数
 * @returns {string}
 */
const handleFilterUrl = (originParam, newParam) => {
    let dest = '?';
    let tempOriginParam = {};

    tempOriginParam = Object.assign(tempOriginParam, originParam, newParam);
    delete tempOriginParam.uid;

    _.forEach(tempOriginParam, function(value, key) {
        dest = dest + key + '=' + value + '&';
    });

    return _.trim(dest, '&');
};

/**
 * 处理最新降价折扣信息
 * @param params 当前 URL 的参数
 * @returns {Array|*[]}
 */
const handleSaleNewSaleSortData = (params) => {
    return [{
        name: '1~3折',
        href: handleFilterUrl(params, {p_d: '0.1,0.3'}),
        checked: params.p_d === '0.1,0.3'
    }, {
        name: '4~6折',
        href: handleFilterUrl(params, {p_d: '0.4,0.6'}),
        checked: params.p_d === '0.4,0.6'
    }, {
        name: '7折以上',
        href: handleFilterUrl(params, {p_d: '0.7,1'}),
        checked: params.p_d === '0.7,1'
    }];
};

/**
 * 处理断码区分类筛选数据
 * @return {[type]} [description]
 */
const handleSalebreakingYardsSortData = (origin, params, seatUrl) => {
    let dest = [];

    if (!_.isEmpty(params.sort)) {
        seatUrl = seatUrl || '';

        // 是否有分类筛选参数,如果有
        _.forEach(params.sort.split(','), sortParam => {
            _.forEach(origin, value => {

                // 判断是否在这组数据里面
                if (!_.isEmpty(_.find(value.sort_id.split(','), o => {
                    return o === sortParam;
                }))) {

                    // 如果在某组数据里面,组合数据退出循环
                    _.forEach(value.sub, subValue => {
                        dest.push({
                            checked: +params.size === +subValue.size_id,
                            href: seatUrl.replace('{size}', subValue.size_id),
                            name: subValue.size_name
                        });
                    });
                    return false;
                }
            });
        });
    } else { // 如果没有筛选参数,返回所有分类
        _.forEach(origin, value => {
            _.forEach(value.sub, subValue => {
                dest.push({
                    checked: +params.size === +subValue.size_id,
                    href: seatUrl.replace('{size}', subValue.size_id),
                    name: subValue.size_name
                });
            });
        });
    }

    return _.uniqWith(dest, _.isEqual);
};

/**
 * 处理选中数据
 * @param  {[type]} params [description]
 * @param  {[type]} origin [description]
 * @param  {[type]} param  [description]
 * @return {[type]}        [description]
 */
const handleCheckedData = (params, origin, param, baseUrl) => {
    let dest = [];

    // 品牌选中数据
    if (!_.isEmpty(origin)) {
        _.forEach(origin, value => {
            if (value.checked) {
                let tempPatam = {};

                tempPatam[param] = '';

                dest.push({
                    name: value.name,
                    href: handleStaticFilterUrl(baseUrl, params, tempPatam),
                    itemType: param
                });
            }
        });
    }

    return dest;
};

/**
 * 处理品牌筛选数据
 * @param params
 * @param origin
 * @returns {{}}
 */
const handleBrandCheckedData = (params, origin, baseUrl) => {
    let dest = [];

    // 分拆品牌参数
    let brands = _.split(params.brand, ',');
    let intBrands = [];

    _.forEach(brands, value => {
        intBrands.push(parseInt(value, 10));
    });

    let checkedCount = 0;

    // 遍历品牌数据,如果在参数中,那么加 checked,将此数据加入到 checked 数组中
    if (!_.isEmpty(origin)) {
        _.forEach(origin, (value) => {
            if (typeof _.find(intBrands, o => {
                return _.isEqual(o, value.id);
            }) !== 'undefined') {

                let checked = {
                    name: value.name,
                    itemType: 'brand'
                }; // push 到已选择数组

                // 为了不污染原始数据
                let tempIntBrands = _.cloneDeep(intBrands);

                // 去掉当前选项
                _.remove(tempIntBrands, n => {
                    return n === value.id;
                });

                // 拼接参数
                let brand = '';

                // 建议保留,需要品牌可以单个删除时放开注释即可
                // _.forEach(tempIntBrands, subValue => {
                //     brand += subValue + ',';
                // });

                // 清除参数,保留没有去掉的参数
                let tempParam = {
                    brand: brand
                };

                checked.href = handleStaticFilterUrl(baseUrl, params, tempParam);
                if (checkedCount === 0) {
                    dest[0] = checked;
                } else if (checkedCount === 1) {
                    dest[0].name += '、' + checked.name.substring(0, 3) + '...';
                }
                checkedCount++;

                // 建议保留,需要品牌可以单个删除时放开注释即可
                // dest.push(checked);
            }
        });
    }
    return dest;
};

/**
 * 处理 opts 排序数据
 * @param params
 * @param total
 * @param extra 什么都可以传进来,多个参数传Object
 * @returns {{}}
 */
exports.handleSaleOptsData = (params, total, extra, baseUrl) => {
    let dest = {
        sortType: []
    };

    // 用来标记是否是折扣专场,折扣专场只需要前三个排序参数
    let count = (extra === 'discont') ? 3 : 4;

    if (extra === 'default') {
        let defaultOpt = {};

        defaultOpt.href = handleStaticFilterUrl(baseUrl, params, {}, {order: true});
        defaultOpt.name = '默认';
        defaultOpt.hasSortOrient = true;
        if (_.isEmpty(params.order)) {
            defaultOpt.active = true;
        } else {
            defaultOpt.active = false;
        }
        defaultOpt.desc = true;
        dest.sortType.push(defaultOpt);
    }

    const orderHref = handleStaticFilterUrl(baseUrl, params, {order: '{order}'});

    for (let i = 0; i < count; i++) {
        let opt = {};

        switch (i) {
            case 0:
                opt.href = orderHref.replace('{order}', 's_t_desc');
                if (extra === 'discont') { // 如果是折扣专场
                    opt.name = '全部';
                    if (_.isEmpty(params.order) || params.order === 's_t_desc') {
                        opt.active = true;
                    } else {
                        opt.active = false;
                    }
                } else {
                    opt.name = '新品';
                    if (params.order === 's_t_desc') {
                        opt.active = true;
                    } else {
                        opt.active = false;
                    }
                    opt.desc = true;
                }
                break;
            case 1:
                if (params.order !== 's_p_desc' && params.order !== 's_p_asc') {
                    opt.href = orderHref.replace('{order}', 's_p_desc');
                    opt.hasSortOrient = true;
                } else {
                    opt.hasSortOrient = true;
                    opt.active = true;
                    if (params.order === 's_p_desc') {
                        opt.href = orderHref.replace('{order}', 's_p_asc');
                        opt.desc = false;
                    } else {
                        opt.href = orderHref.replace('{order}', 's_p_desc');
                        opt.desc = true;
                    }
                }

                opt.name = '价格';
                break;
            case 2:
                if (params.order !== 'p_d_desc' && params.order !== 'p_d_asc') {
                    opt.href = orderHref.replace('{order}', 'p_d_desc');
                    opt.hasSortOrient = true;
                } else {
                    opt.hasSortOrient = true;
                    opt.active = true;
                    if (params.order === 'p_d_desc') {
                        opt.href = orderHref.replace('{order}', 'p_d_asc');
                        opt.desc = false;
                    } else {
                        opt.href = orderHref.replace('{order}', 'p_d_desc');
                        opt.desc = true;
                    }
                }

                opt.name = '折扣';
                break;
            case 3:
                if (params.order !== 's_n_desc' && params.order !== 's_n_asc') {
                    opt.href = orderHref.replace('{order}', 's_n_desc');
                    opt.hasSortOrient = true;
                } else {
                    opt.hasSortOrient = true;
                    opt.active = true;
                    if (params.order === 's_n_desc') {
                        opt.href = orderHref.replace('{order}', 's_n_asc');
                        opt.desc = false;
                    } else {
                        opt.href = orderHref.replace('{order}', 's_n_desc');
                        opt.desc = true;
                    }
                }

                opt.name = '销量';
                break;
            default:
                break;
        }

        dest.sortType.push(opt);
    }

    const limitHref = handleStaticFilterUrl(baseUrl, params, {limit: '{limit}'});

    // 上下翻页数据处理
    dest.pageCounts = [{
        href: limitHref.replace('{limit}', 200),
        count: 200
    }, {
        href: limitHref.replace('{limit}', 100),
        count: 100
    }, {
        href: limitHref.replace('{limit}', 60),
        count: 60
    }];

    dest.curPage = _.isEmpty(params.page) ? 1 : params.page; // 当前页码数

    // 每页商品数量
    dest.countPerPage = _.isEmpty(params.limit) ? 60 : params.limit;

    // 全部页码数量
    dest.pageCount = parseInt(total / (_.isEmpty(params.limit) ? 60 : params.limit), 10) + 1;

    // 每页多少商品
    let paramsLimit = parseInt((_.isEmpty(params.limit) ? 60 : params.limit), 10);

    // 上一页下一页
    let preHref = (!_.isEmpty(params.page) && parseInt(params.page, 10) > 1) ?
    parseInt(params.page, 10) - 1 : 1;
    let nextHref = (!_.isEmpty(params.page)) ? parseInt(params.page, 10) + 1 : 2;

    const pageHref = handleStaticFilterUrl(baseUrl, params, {page: '{page}'});

    if (dest.pageCount > 1 && (parseInt(params.page, 10) !== 1) &&
        (parseInt(params.page, 10) !== dest.pageCount)) {
        dest.preHref = pageHref.replace('{page}', preHref);
        dest.nextHref = pageHref.replace('{page}', nextHref);
    } else if (dest.pageCount > 1 && (parseInt(params.page, 10) === 1)) {
        dest.nextHref = pageHref.replace('{page}', nextHref);
    } else if (dest.pageCount > 1 && (parseInt(params.page, 10) === dest.pageCount)) {
        dest.preHref = pageHref.replace('{page}', preHref);
    }

    // 全部商品数
    dest.totalCount = total;

    // 商品开始结束数
    dest.start = (!_.isEmpty(params.page) ? (params.page - 1) : 0) * paramsLimit + 1;
    if (total < paramsLimit) {
        dest.end = total;
    } else {
        dest.end = (dest.pageCount === parseInt(params.page, 10)) ?
            total : parseInt(dest.start, 10) + paramsLimit - 1;
    }

    return dest;
};

/**
 * 处理页面左侧分类筛选数据
 * @param origin 分类原始数据,一般是接口返回数据中的 group_sort 字段
 * @param params 当前 URL 中已有的参数
 * @param extra 可以任意传值用来处理特殊情况
 * @returns {{}}
 */
exports.handleSaleSortData = (origin, params, extra, baseUrl) => {
    let leftContent = {};

    leftContent.allSort = {};
    leftContent.allSort.list = [];

    // 删除 msort misort
    // delete params.msort;
    // delete params.misort;

    if (extra === 'discount') {
        let tempParams = _.cloneDeep(params);

        delete tempParams.sort;

        leftContent.allSort.all = {
            name: '全部品类',
            href: handleStaticFilterUrl(baseUrl, tempParams, {}, {sort: true}),
            active: _.isEmpty(params.sort)
        };
    } else {
        leftContent.allSort.all = {
            name: '全部品类',
            href: handleStaticFilterUrl(baseUrl, params, {}, {sort: true})
        };
    }

    const sortHref = handleStaticFilterUrl(baseUrl, params, {sort: '{sort}'});

    _.forEach(origin, value => {
        let category = {
            name: value.category_name,
            num: value.node_count,
            childList: [],
            href: sortHref.replace('{sort}', value.relation_parameter.sort),
            active: params.sort === value.relation_parameter.sort
        };

        _.forEach(value.sub, subValue => {
            category.childList.push({
                name: subValue.category_name,
                num: subValue.node_count,
                href: sortHref.replace('{sort}', subValue.relation_parameter.sort),
                childActive: params.sort === subValue.relation_parameter.sort
            });

            if (params.sort === subValue.relation_parameter.sort) {
                category.active = true;
            }
        });

        leftContent.allSort.list.push(category);
    });

    return leftContent;
};

/**
 * 处理一般筛选数据
 * @param origin 要处理的筛选数据 filter
 * @param params 当前 URL 中已有的参数,处理选中状态使用
 * @returns {{}}
 */
exports.handleSaleFilterData = (origin, params, baseUrl) => {
    let dest = {
        brand: {
            default: [],
            brandsShow: [],
            brandIndex: [{
                index: 'all',
                name: '全部'
            }, {
                index: '0-9',
                name: '0~9'
            }],
            showMore: true,
            showMulti: true,
            seatUrl: handleStaticFilterUrl(baseUrl, params, {brand: '{seat}'})
        },
        price: [],
        priceSeatUrl: handleFilterUrl(baseUrl, params, {price: '{seat}'}),
        gender: [],
        checkedConditions: {
            conditions: []
        }
    };

    // 品牌索引数据处理
    for (let i = 65; i < 91; i++) {
        dest.brand.brandIndex.push({
            index: String.fromCharCode(i).toLowerCase(),
            name: String.fromCharCode(i)
        });
    }

    // 品牌数据处理
    // 分拆品牌参数
    let brands = _.split(params.brand, ',');
    let intBrands = [];

    _.forEach(brands, value => {
        intBrands.push(parseInt(value, 10));
    });

    if (origin.brand) {
        let count = 0;
        const brandHref = handleStaticFilterUrl(baseUrl, params, {brand: '{brand}'});

        _.forEach(origin.brand, function(value) {
            let brand = {
                checked: (typeof _.find(intBrands, o => {
                    return _.isEqual(o, value.id);
                }) !== 'undefined'),
                href: brandHref.replace('{brand}', value.id),
                name: value.brand_name,
                key: value.brand_domain,
                id: value.id
            };

            if (!_.isEmpty(value.brand_alif)) {
                if (!_.isNaN(parseInt(value.brand_alif, 10))) {
                    brand.index = '0-9';
                } else {
                    brand.index = value.brand_alif.toLowerCase();
                }
            }

            if (count < 10) {
                dest.brand.default.push(brand);
            }

            dest.brand.brandsShow.push(brand);
            count++;
        });

        // 没有品牌的情况下将 brand 设置为 false,前端不显示 品牌
        if (_.size(dest.brand.brandsShow) <= 0) {
            dest.brand = false;
        } else {
            // 品牌排序
            dest.brand.brandsShow = _.sortBy(dest.brand.brandsShow, o => {
                return o.index;
            });
        }
    }

    // 处理价格筛选数据
    let priceRangechecked = false;

    if (!_.isEmpty(origin.priceRange)) {
        const priceHref = handleStaticFilterUrl(baseUrl, params, {price: '{price}'});

        _.forEach(origin.priceRange, (value, key) => {
            if (params.price === key) {
                priceRangechecked = true;
            }
            let price = {
                checked: params.price === key,
                href: priceHref.replace('{price}', key),
                name: value
            };

            dest.price.push(price);
        });

        dest.priceSeatUrl = priceHref.replace('{price}', '{seat}');
    }

    // 处理用户自主填写的价格区间
    if (!priceRangechecked && params.price) {
        let customPrice = _.split(params.price, ',');

        if (customPrice[1] !== '99999') {
            dest.customPrice = {
                min: customPrice[0],
                max: customPrice[1]
            };
            dest.checkedConditions.conditions.push({
                itemType: 'price',
                name: '¥ ' + customPrice[0] + '-' + customPrice[1],
                href: handleStaticFilterUrl(baseUrl, params, {price: ''})
            });
        }
    }

    const genderHref = handleStaticFilterUrl(baseUrl, params, {gender: '{gender}'});

    // 处理性别数据
    dest.gender = [{
        name: 'BOYS',
        href: genderHref.replace('{gender}', '1,3'),
        checked: params.gender === '1,3'
    }, {
        name: 'GIRLS',
        href: genderHref.replace('{gender}', '2,3'),
        checked: params.gender === '2,3'
    }];

    // 最新降价数据处理
    if (parseInt(params.saleType, 10) === 3) {
        dest.discount = handleSaleNewSaleSortData(params);

        // 最新降价筛选数据处理
        dest.checkedConditions.conditions = _.union(dest.checkedConditions.conditions,
            handleCheckedData(params, dest.discount, 'p_d', baseUrl));
    }

    // 尺码处理
    if (!_.isEmpty(origin.size)) {
        const sizeHref = handleStaticFilterUrl(baseUrl, params, {size: '{size}'});

        if (params.saleType === '5') {

            // 断码区尺码处理
            dest.size = handleSalebreakingYardsSortData(origin.size, params, sizeHref);
        } else {
            dest.size = [];
            if (_.isArray(origin.size)) {
                _.forEach(origin.size, value => {
                    dest.size.push({
                        checked: parseInt(params.size, 10) === parseInt(value.size_id, 10),
                        href: sizeHref.replace('{size}', value.size_id),
                        name: value.size_name
                    });
                });
            } else {
                dest.size.push({
                    checked: parseInt(params.size, 10) === parseInt(origin.size.size_id, 10),
                    href: sizeHref.replace('{size}', origin.size.size_id),
                    name: origin.size.size_name
                });
            }
        }

        dest.checkedConditions.conditions = _.union(dest.checkedConditions.conditions,
            handleCheckedData(params, dest.size, 'size', baseUrl));
    }

    // 年龄处理

    dest.ageLevel = origin.ageLevel;

    const ageHref = handleStaticFilterUrl(baseUrl, params, {age_level: '{age}'});

    _.forEach(dest.ageLevel, item => {
        item.href = ageHref.replace('{age}', item.id);
        item.checked = params.age_level === item.id;
    });

    // 如果年龄就一个,默认选中
    if (dest.ageLevel && dest.ageLevel.length === 1) {
        _.set(dest, 'ageLevel[0].checked', true);
    }

    // 清除所有选中数据
    let remainParams = {};

    if (params.id) {
        remainParams.id = params.id;
    }
    dest.checkedConditions.clearUrl = handleStaticFilterUrl(baseUrl, remainParams);

    // 处理频道筛选数据
    dest.checkedConditions.conditions = _.union(dest.checkedConditions.conditions,
        handleCheckedData(params, dest.gender, 'gender', baseUrl));

    // 处理品牌筛选数据
    if (dest.brand.brandsShow) {
        dest.checkedConditions.conditions = _.union(dest.checkedConditions.conditions,
            handleBrandCheckedData(params, dest.brand.brandsShow, baseUrl));
    }

    // 处理价格筛选数据
    dest.checkedConditions.conditions = _.union(dest.checkedConditions.conditions,
        handleCheckedData(params, dest.price, 'price', baseUrl));

    // 处理价格筛选数据
    dest.checkedConditions.conditions = _.union(dest.checkedConditions.conditions,
        handleCheckedData(params, dest.ageLevel, 'age_level', baseUrl));

    return dest;
};

/**
 * 处理首页 banner 数据
 * @param  {[type]} origin [description]
 * @return {[type]}        [description]
 */
exports.handleBannerData = (origin) => {
    let dest = {};

    dest.list = [];
    _.forEach(origin, function(value) {
        if (value.template_name === 'focus') {
            _.forEach(value.data, subValue => {

                dest.list.push({
                    bannerHeight: 450,
                    href: subValue.url,
                    img: subValue.src
                });
            });
        }

    });

    return dest;
};

/**
 * 面包屑导航
 * @type {[type]}
 */
exports.handlePathNavData = (data, params) => {
    let pathNav = [{
        href: '/product/outlets',
        name: 'OUTLET',
        pathTitle: 'OUTLET'
    }];

    _.forEach(data, (sort) => {
        if (sort.relation_parameter.sort === params.sort) {
            pathNav.push({
                name: sort.category_name,
                pathTitle: sort.category_name
            });
        }
        if (!_.isEmpty(sort.sub)) {
            _.forEach(sort.sub, misort => {
                if (misort.relation_parameter.sort === params.sort) {
                    pathNav.push({
                        href: helpers.urlFormat('/product/outlets/list', {sort: sort.relation_parameter.sort}),
                        name: sort.category_name,
                        pathTitle: sort.category_name
                    }, {
                        name: misort.category_name,
                        pathTitle: misort.category_name
                    });
                }
            });
        }
    });

    return {
        pathNav: pathNav
    };
};

/**
 * 分页
 * @param  {[type]} total 总页数
 * @param  {[type]} params 筛选条件
 * @return {[type]}        [description]
 */
exports.handlePagerData = (total, params) => {
    let dest = {
        prePage: {
            url: ''
        },
        nextPage: {
            url: ''
        },
        pages: []
    };

    let currentPage = parseInt(_.get(params, 'page', 1), 10); // 当前页
    let perPageCount = parseInt(_.get(params, 'limit', 60), 10); // 每页商品数
    let totalPage = Math.ceil(total / perPageCount); // 总页数

    if (currentPage === 1) {
        // 当前页为 1,一定没有上一页
        delete dest.prePage;
    } else {
        dest.prePage.url = handleFilterUrl(params, {page: currentPage - 1});
    }

    if (currentPage === totalPage) {

        // 当前页为最后一页,一定没有下一页
        delete dest.nextPage;
    } else {
        dest.nextPage.url = handleFilterUrl(params, {page: currentPage + 1});
    }

    // 页码临时数据
    let pages = [];

    if (currentPage > 2 && currentPage <= totalPage - 2) {
        for (let i = currentPage - 2; i <= ((currentPage + 2) > totalPage ? totalPage : (currentPage + 2)); i++) {
            pages.push({
                url: handleFilterUrl(params, {page: i}),
                num: i,
                cur: currentPage === i
            });
        }

        // 处理页码小于等于 2 的情况
    } else if (currentPage <= 2) {
        for (let i = 1; i <= (totalPage < 5 ? totalPage : 5); i++) {
            pages.push({
                url: handleFilterUrl(params, {page: i}),
                num: i,
                cur: currentPage === i
            });
        }
    } else if (currentPage > totalPage - 2) {
        for (let i = totalPage; i >= totalPage - 4; i--) {

            if (i > 0) {
                pages.push({
                    url: handleFilterUrl(params, {page: i}),
                    num: i,
                    cur: currentPage === i
                });
            }
        }
        pages = _.sortBy(pages, ['num']);
    }

    let prevPages = [];
    let nextPages = [];

    if (_.size(pages) === 5) {
        if (currentPage > 4) {
            prevPages.push({
                url: handleFilterUrl(params, {page: 1}),
                num: 1
            });
            prevPages.push({
                num: '...'
            });
        }
        if (currentPage < totalPage - 2 && totalPage > 5) {
            nextPages.push({
                num: '...'
            });
            nextPages.push({
                url: handleFilterUrl(params, {page: totalPage}),
                num: totalPage
            });
        }
    }

    // 商品开始结束数
    dest.tip = {
        total: total,
        start: (currentPage ? currentPage - 1 : 0) * perPageCount + 1
    };

    let endPageNum = (totalPage === currentPage) ?
        total : parseInt(dest.tip.start, 10) + perPageCount - 1;

    dest.tip.end = (total < perPageCount) ? total : endPageNum;
    dest.pages = _.concat(prevPages, pages, nextPages);

    return dest;

};

/**
 * 筛选类链接处理的对外接口
 * @type {[type]}
 */
exports.handleFilterUrl = handleFilterUrl;

/**
 * 处理选中数据的对外接口
 * @type {[type]}
 */
exports.handleCheckedData = handleCheckedData;