'use strict';
const _ = require('lodash');

const camelCase = global.yoho.camelCase;
const helpers = global.yoho.helpers;

// TODO 删除from参数,暂时保留注释
// const itemFromBase = {
//    search: {domain: 'search', module: 's'}, // 搜索页search.yohobuy.com
//    list: {domain: 'list', module: 'c'}, // list.yohobuy.com
//    listSale: {domain: 'list', module: 's'}, // list.yohobuy.com/sale
//    listNew: {domain: 'list', module: 'n'}, // list.yohobuy.com/new
//    brand: {domain: 'brand', module: 'b'}, // xxx.yohobuy.com[品牌域名]
//    saleSpecial: {domain: 'sale', module: 's'}// sale.yohobuy.com
// };

/**
 * 根据性别来决定  默认图片获取字段   如果是 2、3
 *
 * 则优先从cover2 --》 cover1 -- 》 images_url
 * 否则优先从cover1 --》 cover2 -- 》 images_url
 *
 */
const procProductImg = (product, gender, newSort) => {
    if (gender === '2,3') {
        return product.cover_2 || product.images_url || '';
    }

    if (newSort && gender === '1,2,3') {
        return product.images_url || '';
    }

    return product.cover_1 || product.images_url || '';
};

/**
 * 处理列表大图周边小图数据,拼接添加 href
 * @param origin goods 原始数据
 * @returns {{}} goods 输出数据,结构不变
 */
const handleGoodsListData = (origin) => {
    _.forEach(origin, (value, key) => {
        if (!_.isEmpty(value.goods_list)) {
            _.forEach(value.goods_list, (subValue, subKey) => {
                origin[key].goods_list[subKey].url =
                    helpers.getUrlBySkc(value.product_skn);
            });
        }
    });
    return origin;
};

/**
 * 处理搜索返回同一skc分男女封分别返回问题
 * @param array $images
 * @return string 商品图片
 */
const procGoodsList = (goodsList) => { // eslint-disable-line
    let list = {};

    if (!_.isEmpty(goodsList)) {
        let goods = _.cloneDeep(goodsList);

        _.forEach(goods, value => {
            if (!list[value.productSkc]) {
                list[value.productSkc] = value;
            } else {
                if (value.cover1) {
                    list[value.productSkc].cover1 = value.cover1;
                }
                if (value.cover2) {
                    list[value.productSkc].cover2 = value.cover2;
                }
            }
        });
    }

    return _.toArray(list);
};

/**
 * 处理
 *
 * 2、3: cover2 --> images_url  -> cover1
 * 1,3 :cover1 --> images_url  -> cover2
 * 其他: cover1 --> cover2 --> images_url
 *
 * @param array $images
 * @return string 商品图片
 */
const procProductImgs = (item, gender) => {
    let imgUrl = item.images_url ? item.images_url : '',
        cover1 = item.cover_1 ? item.cover_1 : '',
        cover2 = item.cover_2 ? item.cover_2 : '';

    if (gender === '2,3') {
        return cover2 ? cover2 : (imgUrl ? imgUrl : cover1);// eslint-disable-line
    } else if (gender === '1,3') {
        return cover1 ? cover1 : (imgUrl ? imgUrl : cover2);// eslint-disable-line
    } else {
        return cover1 ? cover1 : (cover2 ? cover2 : imgUrl);// eslint-disable-line
    }
};

/**
 * 商品搜索商品数据处理
 */
exports.processProductList = (list, options) => {
    const pruductList = [];

    // TODO 删除from参数,暂时保留注释
    // let itemNum = 0,
    //    itemFrom;

    options = Object.assign({
        showTags: true,
        showNew: true,
        showSale: true,
        showFew: true,
        showLimit: true,
        showDiscount: true, // 显示折扣
        newCoverSort: false, // 新封面排序
        width: 290,
        height: 388,
        isApp: false,
        showPoint: true,
        gender: '2,3',
        from: {} // 来源
    }, options);

    // TODO 删除from参数,暂时保留注释
    // 处理item from
    // if (!_.isEmpty(options.from) && itemFromBase[options.from.type]) {
    //    let f = {domain: '', module: '', key: ''};
    //    let params = options.from.params || {};
    //
    //    f.page = params.page || 1;
    //
    //    Object.assign(f, itemFromBase[options.from.type], {
    //        page: params.page || 1,
    //        key: params.misort || params.msort || ''
    //    });
    //
    //    if (options.from.type === 'search') {
    //        f.key = params.query || '';
    //    }
    //
    //    itemFrom = `from=${f.domain}-${f.module}-${f.key}_${f.page}_`;
    // }

    _.forEach(list, (product) => {
        // 全球购接口与普通接口返回商品差异属性预处理
        if (options.isGlobal && product) {
            Object.assign(product, {
                goods_list: [{
                    images_url: product.default_images,
                    status: 1
                }],
                sales_price: product.final_price || product.orign_price,
                market_price: null,
                tbl_country_name: product.country_name,
                tbl_brand_id: product.brand_id
            });
        }

        // 商品信息有问题,则不显示
        if (!product || !product.product_skn || !_.get(product, 'goods_list.length', 0)) {
            return;
        }

        // 市场价和售价一样,则不显示市场价, 不显示折扣信息
        if (product.market_price <= product.sales_price) {
            delete product.market_price;
        } else if (options.showDiscount) {
            product.discount = (product.sales_price / product.market_price * 10).toFixed(1);
        }

        // 判别默认的商品是否将默认的图片URL赋值到skn
        let flag = false;

        _.remove(product.goods_list, function(n) {
            return !+n.status;
        });

        // skc图片排序
        product.goods_list = _.orderBy(product.goods_list, ['is_default'], ['desc']);

        if (!product.default_images) {
            // 如果设置了默认图片,就取默认的图片
            _.forEach(product.goods_list, (goods) => {
                if (flag) {
                    return;
                }
                if (goods.is_default === 'Y') {
                    product.default_images = procProductImg(goods);
                    flag = true;
                }
            });

            // 如果还未赋值,则取第一个skc产品的默认图片
            if (!flag) {
                product.default_images = procProductImg(product.goods_list[0]);
            }
        }
        product = Object.assign(product, {
            id: product.product_skn,
            thumb: product.default_images
        });

        product.is_few = product.is_soon_sold_out === 'Y';

        if (product.is_global === 'Y') {
            product.url = helpers.urlFormat(`/product/global/${product.product_skn}.html`, null);
        } else {
            if (product.product_skn) {
                product.url = helpers.getUrlBySkc(product.product_skn);
            }
        }

        // 4.6需求 商品列表显示店铺名
        // is_global = Y & tbl_brand_id!= 0 则跳全球购品牌否则走品牌,因为全球购的商品有可能融进了有货的牌子
        if (product.is_global === 'Y' && product.tbl_brand_id) {
            product.brandUrl = helpers.urlFormat('/product/global/list', {brand: product.tbl_brand_id});
        } else if (product.shop_id * 1) {
            product.brand_name = product.shop_name;
            product.brandUrl = helpers.urlFormat('', {
                shopId: product.shop_id
            }, product.shop_domain || 'default-domain');
        } else {
            // 5.6商品列表未关联店铺不显示品牌
            _.unset(product, 'brand_name');

            // product.brandUrl = helpers.urlFormat('', '', product.brand_domain);
        }

        // TODO 删除from参数,暂时保留注释
        // if (itemFrom) {
        //    // 累加商品数量
        //    itemNum++;
        //    product.url += `?${itemFrom}${itemNum}`;
        // }

        if (options.showTags) {
            let tags = [],
                isfew = false;

            if (product.is_global === 'Y') {
                tags.push({
                    is_global: true,
                    name: product.tbl_country_name
                });
            }

            _.get(product, 'tags', []).forEach((value) => {
                let tag = {};

                switch (value) {
                    case 'is_soon_sold_out': // 即将售磬
                        options.showFew && (tag.is_few = true, isfew = true);
                        break;
                    case 'is_solded': // 已售磬
                        product.is_solded = true;
                        break;
                    case 'is_new': // 新品NEW
                        options.showNew && (tag.is_new = true);
                        break;
                    case 'is_discount': // SALE
                        options.showSale && (tag.is_sale = true);
                        break;
                    case 'is_limited': // 限量
                        options.showLimit && (tag.is_limit = true);
                        break;
                    case 'is_yohood': // YOHOOD
                        tag.is_new_festival = true;
                        break;
                    case 'is_advance': // 再到着
                        tag.is_re_new = true;
                        break;
                    case 'midYear':// 年中热促
                        tag.is_year_mid_promotion = true;
                        break;
                    case 'yearEnd':// 年终大促
                        tag.is_year_end_promotion = true;
                        break;
                    case 'is_presell':// 预售
                        tag.is_presell = true;
                        break;
                    default:
                        break;
                }
                tags.push(tag);
            });

            product.tags = tags;
            isfew ? product.is_few = isfew : delete product.is_few;
        }
        if (options.query && _.isString(product.product_name)) {
            let qreg = new RegExp(options.query.replace('\\', '\\\\'), 'ig');

            product.product_name = product.product_name.replace(qreg, '<span style="color:#c00;">$&</span>');
        }
        pruductList.push(product);
    });

    return handleGoodsListData(pruductList);
};


/**
 * 处理筛选数据
 * @param list
 * @param  string | options
 * @return array 处理之后的筛选数据
 */
exports.processFilter = (list, options) => {
    const filters = {
        classify: []
    };

    const filtersType = {
        brand: {
            name: '所有品牌',
            title: '品牌',
            dataId: 'id',
            subsName: 'brandName',
            firstSub: 0,
            dataType: 'brand'
        },
        color: {
            name: '所有颜色',
            title: '颜色',
            dataId: 'colorId',
            subsName: 'colorName',
            firstSub: 0,
            dataType: 'color'
        },
        discount: {
            name: '所有商品',
            title: '折扣',
            dataId: 'key',
            subsName: 'name',
            firstSub: '0.1,0.9',
            dataType: 'p_d'
        },
        gender: {
            name: '所有性别',
            title: '性别',
            dataId: 'key',
            subsName: 'flag',
            firstSub: '1,2,3',
            dataType: 'gender'
        },
        groupSort: {
            name: '所有品类',
            title: '品类',
            dataId: 'relationParameter',
            subsName: 'categoryName',
            firstSub: 0,
            dataType: 'sort'
        },
        priceRange: {
            name: '所有价格',
            title: '价格',
            dataId: 'key',
            subsName: 'flag',
            firstSub: 0,
            dataType: 'price'
        },
        size: {
            name: '所有尺码',
            title: '尺码',
            dataId: 'sizeId',
            subsName: 'sizeName',
            firstSub: 0,
            dataType: 'size'
        }
    };

    options = Object.assign({
        gender: '1,2,3', // 默认选择的性别,默认1,2,3表示所有
        exclude: null // 需要排除的字段
    }, options);
    list = camelCase(list);

    _.forEach(list, (item, key) => {
        let classify = {
            subs: []
        };

        if (key === 'group_sort') {
            return;
        }

        if ((options.hideSize && key === 'size') || (options.hideSort && key === 'groupSort')) {
            return;
        }

        classify.dataType = filtersType[key].dataType;
        classify.name = filtersType[key].name;
        classify.title = filtersType[key].title;

        classify.subs.push({
            chosed: true,
            dataId: filtersType[key].firstSub,
            name: filtersType[key].name
        });

        _.forEach(item, (sub, index) => {
            let subs = {};

            if (filtersType[key].dataId === 'key') {
                subs.dataId = index;
            } else if (filtersType[key].dataId === 'relationParameter') {
                subs.dataId = sub.relationParameter['sort']; // eslint-disable-line
            } else {
                subs.dataId = sub[filtersType[key].dataId];
            }

            if (filtersType[key].subsName === 'flag') {
                subs.name = sub;
            } else {
                subs.name = sub[filtersType[key].subsName];

                if (key === 'discount') {
                    subs.name = subs.name + '折商品';
                }
            }
            classify.subs.push(subs);
        });

        filters.classify.push(classify);
    });

    return filters;
};

// 处理单个商品
exports.processProduct = (productData, options) => {
    let result = {},
        flag = false;

    options = Object.assign({
        showTags: true,
        showNew: true,
        showSale: true,
        width: 290,
        height: 388,
        showPoint: true
    }, options);

    // 商品信息有问题,则不显示
    if (!productData.product_skn || !productData.goods_list[0]) {
        return false;
    }

    // 市场价和售价一样,则不显示市场价
    if (parseInt(productData.market_price, 0) === parseInt(productData.sales_price, 0)) {
        productData.market_price = false;
    }

    // 设置默认图片
    _.forEach(productData.goods_list, item => {
        if (item.is_default === 'Y') {
            productData.default_images = procProductImgs(item, options.gender);
            flag = true;
        }
    });

    if (!flag) {
        productData.default_images = procProductImgs(productData.goods_list[0], options.gender);
    }

    result.id = productData.product_skn;
    result.product_id = productData.product_id;
    result.thumb = helpers.image(productData.default_images, options.width, options.height);
    result.name = productData.product_name;
    result.price = !productData.market_price ? false : productData.market_price;
    result.salePrice = productData.sales_price;
    if (options.showPoint) {
        result.price += '.00';
        result.salePrice += '.00';
    }

    result.is_soon_sold_out = (productData.is_soon_sold_out === 'Y');
    result.url = helpers.getUrlBySkc(productData.product_skn);

    if (options.showTags) {
        result.tags = {};
        result.tags.is_new = options.showNew && productData.is_new && productData.is_new === 'Y'; // 新品
        result.tags.is_discount = options.showSale && productData.is_discount && productData.is_discount === 'Y'; // 在售
        result.tags.is_limited = productData.is_limited && productData.is_limited === 'Y'; // 限量
        result.tags.is_yohood = productData.is_yohood && productData.is_yohood === 'Y'; // YOHOOD
        result.tags.midYear = productData['mid-year'] && productData['mid-year'] === 'Y'; // 年中
        result.tags.yearEnd = productData['year-end'] && productData['year-end'] === 'Y'; // 年末
        result.tags.is_advance = productData.is_advance && productData.is_advance === 'Y'; // 再到着

        if (result.is_soon_sold_out && result.tags.is_discount) {
            result.tags.is_new = false;// 打折与即将售完组合显示打折
        } else if (result.tags.is_discount &&
            (result.tags.is_new || result.tags.is_limited || result.tags.is_yohood || result.tags.is_advance)) {
            result.tags.is_discount = false;// 打折与其它组合则隐藏打折
        } else if (result.tags.is_yohood && result.tags.is_new) {
            result.tags.is_new = false;// YOHOOD和新品组合显示YOHOOD
        }
    }
    return result;
};