/*
 * @Author: Targaryen
 * @Date: 2017-03-23 11:02:31
 * @Last Modified by: Targaryen
 */
/* 红人店铺数据处理 */

'use strict';

const _ = require('lodash');
const helpers = global.yoho.helpers;
const productPrcs = require('./product-process');
const listParamsProcess = require('./list-params-process');
const GENDER = {
    1: '男',
    2: '女',
    3: '男|女'
};

let countCarouselImage = 0; // 轮播图模块统计
let isMipFlag = false;


/**
 * 将商品转化成以 product_skn 为键名的对象
 * @param {*} goodsArray
 */
const _goodsArrayToObj = (goodsArray) => {
    return _.keyBy(goodsArray, value => {
        return value.product_skn;
    });
};

/**
 * 链接处理
 * @param {*} linkParent
 */
const _linkhandle = (linkParent) => {
    let union_type = '100000000013130';
    let param;

    if (linkParent.linkType) {
        switch (parseInt(linkParent.linkType, 10)) {
            case 0:
                param = {
                    filter_poolId: linkParent.resource,
                    title: linkParent.text
                };

                if (isMipFlag) {
                    param.union_type = union_type;
                }

                return helpers.urlFormat('', param, 'list');
            case 1:
                param = '/product/' + linkParent.resource + '.html' + (isMipFlag ? `?union_type=${union_type}` : '');

                return helpers.urlFormat(param);
            case 2:
                param = '';

                if (isMipFlag) {
                    param = linkParent.resource.indexOf('?') > -1 ? '&' : '?';
                    param += `union_type=${union_type}`;
                }

                return linkParent.resource + param;
            default:
                break;
        }
    } else {
        return false;
    }
};

/**
 * 图片处理
 * @param {*} moduleData
 */
const _picsHandle = (moduleData) => {
    let pics = [];

    _.forEach(_.get(moduleData, 'data', []), value => {
        let showProductInfo = true;

        if (_.has(value, 'showProductInfo')) {
            showProductInfo = value.showProductInfo;
        }

        pics.push({
            src: value.pic,
            link: _linkhandle(value),
            text: value.text,
            showProductInfo: showProductInfo,
            skn: _.parseInt(value.linkType) === 1 ? value.resource : ''
        });
    });
    return pics;
};

/**
 * 红人店铺楼层数据处理工具
 */
const _tools = {

    /**
     * 模块标题
     * @param {*} moduleData
     */
    title(moduleData) {
        return {
            module_type: 'Title',
            text: _.get(moduleData, 'data[0].text', ''),
            isModuleMargin: _.get(moduleData, 'properties.isModuleMargin', 0),
            link: _linkhandle(_.get(moduleData, 'data[0]', 0))
        };
    },

    /**
     * 视频模块
     * @param {*} moduleData
     */
    video(moduleData) {
        return {
            module_type: 'Video',
            title: _.get(moduleData, 'data[0].text.title', ''),
            content: _.get(moduleData, 'data[0].text.content', ''),
            pic: _.get(moduleData, 'data[0].pic', ''),
            isModuleMargin: _.get(moduleData, 'properties.isModuleMargin', 0),
        };
    },

    /**
     * 轮播图
     * @param {*} moduleData
     */
    carouselImage(moduleData) {
        return {
            module_type: 'CarouselImage',
            num: countCarouselImage,
            pics: _picsHandle(moduleData),
            isModuleMargin: _.get(moduleData, 'properties.isModuleMargin', 0),
        };
    },

    /**
     * 一张图片
     * @param {*} moduleData
     */
    singleImage(moduleData) {
        return {
            module_type: 'SingleImage',
            pics: _picsHandle(moduleData),
            text: _.get(moduleData, 'data[0].text', ''),
            width: _.get(moduleData, 'properties.width', ''),
            height: _.get(moduleData, 'data[0].text', ''),
            moduleHeight: _.get(moduleData, 'properties.moduleHeight', ''),
            isModuleMargin: _.get(moduleData, 'properties.isModuleMargin', 0),
        };
    },

    /**
     * 两张图片
     * @param {*} moduleData
     */
    doubleImage(moduleData) {
        return {
            module_type: 'DoubleImage',
            pics: _picsHandle(moduleData),
            isModuleMargin: _.get(moduleData, 'properties.isModuleMargin', 0),
        };
    },

    /**
     * 三张图片
     * @param {*} moduleData
     */
    tripleImage(moduleData) {
        let displayType = parseInt(_.get(moduleData, 'properties.displayType', 0), 10);

        // 没有展示方式,不展示此模块,处理接口返回数据异常的情况
        if (!displayType) {
            return {};
        }

        return {
            module_type: 'TripleImage',
            pics: _picsHandle(moduleData),
            isModuleMargin: _.get(moduleData, 'properties.isModuleMargin', 0),
            displayType: displayType,
        };
    },

    /**
     * 四张图片
     * @param {*} moduleData
     */
    fourImage(moduleData) {
        return {
            module_type: 'FourImage',
            pics: _picsHandle(moduleData),
            isModuleMargin: _.get(moduleData, 'properties.isModuleMargin', 0)
        };
    },

    /**
     * 推荐商品列表
     * @param {*} moduleData
     */
    appRecommendProduct(moduleData) {
        let displayType = _.parseInt(_.get(moduleData, 'properties.displayType', 0));

        let result = {
            module_type: 'AppRecommendProduct',
            type: displayType
        };


        let skns = '';

        switch (displayType) {
            case 0:
                _.assign(result, {
                    order: _.get(moduleData, 'data[0].order', 'p_d_asc')
                });
                break;
            case 1:
                _.forEach(_.get(moduleData, 'data[0].sknList', []), value => {
                    skns += value + ',';
                });
                _.assign(result, {
                    skns: skns
                });
                break;
            default:
                break;
        }

        return result;
    }
};

/**
 * 处理红人店铺楼层
 * @param {*} decoratorsData
 */
const floor = (decoratorsData, isMip) => {
    let decorators = [];
    let skns;

    isMipFlag = isMip;
    countCarouselImage = 0;
    _.forEach(decoratorsData, value => {
        try {
            value.module_data = JSON.parse(value.module_data);
        } catch (error) {
            console.log(error);
        }

        switch (value.module_type) {
            case 'Title':
                decorators.push(_tools.title(value.module_data));
                break;

            // case 'Video':
            //     decorators.push(_tools.video(value.module_data));
            //     break;
            case 'CarouselImage':
                countCarouselImage++;
                decorators.push(_tools.carouselImage(value.module_data));
                break;
            case 'SingleImage':
                decorators.push(_tools.singleImage(value.module_data));
                break;
            case 'DoubleImage':
                decorators.push(_tools.doubleImage(value.module_data));
                break;
            case 'TripleImage':
                decorators.push(_tools.tripleImage(value.module_data));
                break;
            case 'FourImage':
                decorators.push(_tools.fourImage(value.module_data));
                break;
            case 'SknList':
                skns = _.get(value, 'module_data.data').join(',');
                break;
            case 'AppRecommendProduct':
                decorators.push(_tools.appRecommendProduct(value.module_data));
                break;
            default:
                break;
        }
    });

    return {
        decorators: decorators,
        skns: skns
    };
};

/**
 * 店铺介绍处理
 * @param {*} params
 */
const shopIntro = (params) => {
    if (params) {
        params.shop_intro_link = helpers.urlFormat('/product/index/intro', { shop_id: params.shops_id });
    }

    return params;
};

/**
 * 店铺分类处理
 * @param {*} params
 */
const category = (params, shopParams, isMip) => {
    let categoryData = {
        list: [],
        url: ''
    };

    if (!params) {
        return categoryData;
    }

    if (params.length > 6) {
        let opt = {
            shop_id: shopParams.shopId
        };

        if (isMip) {
            opt.union_type = '100000000013130';
        }

        categoryData.url = helpers.urlFormat('/product/index/category', opt);
    } else {
        _.forEach(params, value => {
            let opt = {
                shop_id: shopParams.shopId,
                sort: (value.relation_parameter && value.relation_parameter.sort) || '',
                title: value.category_name
            };

            if (isMip) {
                opt.union_type = '100000000013130';
            }

            categoryData.list.push({
                url: listParamsProcess.generatePathUrl(opt, `shop/${shopParams.domain}-${shopParams.shopId}`),
                name: value.category_name
            });
        });
    }

    return categoryData;
};

/**
 * 加入商品价格等数据
 * @param {*} decorators
 * @param {*} goodsList
 */
const pushGoodsInfo = (decorators, goodsList) => {
    let goodsObj = _goodsArrayToObj(productPrcs.processProductList(goodsList));

    _.forEach(decorators, (value, key) => {
        _.forEach(_.get(value, 'pics', []), (subValue, subKey) => {
            let hasGoods = _.get(goodsObj, `${subValue.skn}.default_images`, false);

            if (!hasGoods) {
                decorators[key].noShowProductInfo = true;
            }

            if (subValue.skn && hasGoods && value.module_type !== 'CarouselImage') {
                let salesPrice = _.get(goodsObj, `${subValue.skn}.sales_price`, '');
                let marketPrice = _.get(goodsObj, `${subValue.skn}.market_price`, '');
                let imageSrc = _.get(goodsObj, `${subValue.skn}.default_images`, '');

                if (salesPrice === 0) {
                    decorators[key].noShowProductInfo = true;
                }

                decorators[key].pics[subKey].name = _.get(goodsObj, `${subValue.skn}.product_name`, '');
                decorators[key].pics[subKey].salesPrice = salesPrice ? '¥' + salesPrice : '';
                decorators[key].pics[subKey].marketPrice = marketPrice ? '¥' + marketPrice : '';
                decorators[key].pics[subKey].isGood = true;
                decorators[key].pics[subKey].alt = _.get(goodsObj, `${subValue.skn}.brand_name`, '') +
                    '|' + GENDER[_.get(goodsObj, `${subValue.skn}.gender`, '3')] +
                    '|' + _.get(goodsObj, `${subValue.skn}.small_sort_name`, '') +
                    '|' + _.get(goodsObj, `${subValue.skn}.product_name`, '');

                if (value.module_type === 'TripleImage' ||
                    value.module_type === 'DoubleImage' ||
                    value.module_type === 'SingleImage') {

                    // decorators[key].pics[subKey].src = imageSrc; // 为了和 APP 统一,图暂时不取商品图
                } else if (value.module_type === 'FourImage') {
                    decorators[key].pics[subKey].isGood = false;
                } else {
                    decorators[key].pics[subKey].src = imageSrc.split('?')[0];
                }
            }
        });
    });

    return decorators;
};

/**
 * 获取非红人店铺的店铺 Banner
 */
const getShopBanner = (shopDecoratorList) => {
    let banner = '';

    _.forEach(shopDecoratorList, floorData => {
        let resData = JSON.parse(floorData.resource_data);

        if (floorData.resource_name) {
            floorData[_.camelCase(floorData.resource_name)] = true;
        }

        // 店铺banner
        if (floorData.shopTopBannerApp) {
            banner = resData[0].shopSrc +
                '?imageMogr2/auto-orient/strip/thumbnail/x{height}/crop/{width}x{height}';
        }
    });

    return banner;
};

module.exports = {
    floor,
    shopIntro,
    category,
    pushGoodsInfo,
    getShopBanner
};