individuation.js 10.3 KB
import $ from 'jquery';
import jsonp from './jsonp';
import user from './user';
import utils from './utils';
import cookies from './cookies';
import lazyLoad from './lazyload';

let abTestFlag = false; // ab测试
let getPname = function () {
    let pName = '';

    if (utils.isMobile.iOS()) {
        pName = 'iFP_SalesPromotion_h5';
    }

    if (utils.isMobile.Android()) {
        pName = 'aFP_SalesPromotion_h5';
    }

    return pName;
};

let _replaceData = function(el, cond, data, wh, fp) {
    if (!data) {
        return;
    }
    let product_url = `//m.yohobuy.com/product/${data.product_skn}.html?openby:yohobuy={"action":"go.productDetail","params":{"product_skn":${data.product_skn},"from_page_name":"${getPname()}","from_page_param":"${location.href.split('?')[0]}"}}`;

    if (data.collage_price && data.collage_activity_id) {
        product_url = `//m.yohobuy.com/activity/group/detail?activityId=${data.collage_activity_id}&productSkn=${data.product_skn}&openby:yohobuy={"action":"go.productDetail","params":{"product_skn":"${data.product_skn}","activity_id":"${data.collage_activity_id}","activity_type":"groupPurchase"}}`;
    }
    el.find('.brand-name').html(data.brand_name);
    el.find('.product-detail').attr('href', product_url);
    el.find('.product-name').html(data.product_name);
    el.find('.vip-price-val').html(${data.vip_price}`);
    el.find('.sale-price').html(${data.sales_price}`);
    el.data('skn', data.product_skn);

    if (data.curPlanPrice) {
        el.find('.advance .advance-price').html(${data.curPlanPrice}`);
        el.find('.advance').css({display: 'inline-block'});
    }

    const $productDetailImg = el.find('.product-detail-img');

    if ($productDetailImg.hasClass('lazy')) {
        $productDetailImg.attr('data-original', utils.image(data.default_images, wh.w, wh.h, 2, 75));
    } else {
        $productDetailImg.attr('src', utils.image(data.default_images, wh.w, wh.h, 2, 75));
    }

    if (data.sales_price === data.market_price) {
        el.find('.market-price').hide();
    } else {
        el.find('.market-price').html(${data.market_price}`).show();
    }

    let brandDom = el.find('.product-brand');
    if (brandDom) {
        if (data.shop_id) {
            // eslint-disable-next-line
            brandDom.attr('href', `//m.yohobuy.com/product/index/brand?shop_id=${data.shop_id}&openby:yohobuy={"action":"go.shop","params":{"shop_id":${data.shop_id},"shop_template_type":${data.shop_template_type || "1"},"is_red_shop":${data.is_red_shop || 1}}}`);
        } else {
            brandDom.attr('href', `//m.yohobuy.com/product/index/brand?domain=${data.brand_domain}&openby:yohobuy={"action":"go.brand","params":{"brand_id":${data.brand_id}}}`);
        }
    }

    // 楼层数据
    if (fp) {
        if (!fp.I_INDEX) fp.I_INDEX = 0;

        fp.I_INDEX++;
        el.find('.product-detail').attr('fp', JSON.stringify(fp));
        if (brandDom) {
            fp.I_INDEX++;
            brandDom.attr('fp', JSON.stringify(fp));
        }
    }

    let listDom = el.find('.list-product');
    if (listDom) {
        let sortStr = '',
            gender = cond.gender ? cond.gender : '1,3',
            url = `//list.m.yohobuy.com?gender=${gender}`;

        if (listDom.data('sort')) {
            sortStr += `,"sort":${data.small_sort_id}`;
            url += `&sort=${data.small_sort_id}`;
        }
        if (listDom.data('misort')) {
            sortStr += `,"misort":${data.middle_sort_id}`;
            url += `&misort=${data.middle_sort_id}`;
        }
        if (listDom.data('msort')) {
            sortStr += `,"msort":${data.max_sort_id}`;
            url += `&msort=${data.max_sort_id}`;
        }

        url += `&openby:yohobuy={"action":"go.list","params":{"actiontype":1,"gender":${gender}${sortStr}}}`;
        listDom.attr('href', url);
    }
    el.html(el.html());
    return el;
};

let _getProductData = function(dataArr){
    if (!dataArr.length) {
        return;
    }

    var data = dataArr.shift();
    if (!data || !data.default_images) {
        return _getProductData(dataArr);
    }
    return data;
};

let _jsonp = function(el, param, cond){
    let cloneitem = el.attr('cloneitem');
    let loading = el.find('.loading');
    let goods = el.find('.feature-product-info');
    let rowNum = el.data('rownum');

    if (!goods.length) {
        return;
    }

    if (cond.abtest) {
        // ab测试,访客 和 >=512的uid 显示默认推荐
        if (!param.uid || (Number(param.uid) % 1024 >= 512)) {
            if (cloneitem) {
                $(goods[0]).remove();
            } else {
                goods.removeClass('novisible');
                loading.hide();
            }
            return;
        }
    }

    let imgwh = el.find('.imgwh').val() || ''; // 获取图片宽x高
    imgwh = imgwh.split('x') || [];

    let wh = {
        w: imgwh[0] || 300,
        h: imgwh[1] || 400
    };

    // 楼层数据
    let fp = el.attr('fp');
    fp = fp ? JSON.parse(fp) : '';

    jsonp({
        url: '//m.yohobuy.com/activity/individuation?callback=?',
        data: $.extend({}, param, cond)
    }).then(function(res) {
        if (!res || !res.length) {
            if (cloneitem) {
                $(goods[0]).remove();
            } else {
                goods.removeClass('novisible');
                loading.hide();
            }
            return;
        }

        // 最后商品数量不足一行,截掉
        res.length = res.length - (res.length % rowNum);

        if (cloneitem) { // 可复制item
            var cnt = isNaN(Number(cloneitem)) ? res.length : Number(cloneitem);
            for (let indx = 0; indx < cnt; indx++) {
                let data = _getProductData(res); // 获取商品数据
                if (indx === 0) {
                    let gel = $(goods[0]);
                    let nel = _replaceData(gel, cond, data, wh, fp);
                    if (nel) {
                        nel.removeClass('novisible');
                    } else {
                        gel.remove();
                    }
                } else {
                    let nel = _replaceData($(goods[0]).clone(), cond, data, wh, fp);
                    if (nel) {
                        nel.removeClass('novisible');
                        nel.appendTo(el);
                    }
                }
            }
        } else {
            for (let i = 1; i < res.length; i++) {
                goods.last().after(goods.clone());
            }

            let $newGoods = el.find('.feature-product-info');

            $newGoods.each(function(indx, perProduct) {
                let $perProduct = $(perProduct);
                _replaceData($perProduct, cond, _getProductData(res), wh, fp);
            });
            $newGoods.removeClass('novisible');
            loading.hide();
        }
        lazyLoad($('.product-source img.lazy'));
    }, function(){
        if (cloneitem) {
            $(goods[0]).remove();
        } else {
            goods.removeClass('novisible');
            loading.hide();
        }
    });
};

let _abTest = function() {
    let mkt_code = user.getMktCode();

    // cover覆盖mkt_code
    utils.sParamByIframe('callback=jQueryMktCode&cover=1&mkt_code=' + mkt_code +'&expires=' + (7 * 24 * 60 * 60 * 1000));

    // 上报曝光事件
    let actionUrl = [];
    $('a').each(function(){
        let href = $(this).attr('href');
        if (href && !/^#.*$/.test(href) && !/^javascript.*$/i.test(href)) {
            actionUrl.push(href);
        }
    });

    var cnt = 0;
    var timer = setInterval(function() {
        cnt++;
        if (cnt > 3) {
            clearInterval(timer);
            return;
        }
        if (window._yas && window._yas.sendAppLogs && window.appBaseLogs) {
            clearInterval(timer);
            window._yas.sendAppLogs({
                appop: 'YB_H5_PAGE_AB_OPEN_L',
                param: JSON.stringify({
                    C_ID: utils.queryString().yh_channel || 1,
                    PAGE_URL: window.originUrl,
                    PAGE_NAME: decodeURI(window.qs.title || document.title),
                    ACTION_URL: actionUrl,
                    CROWD_CODE: mkt_code + ''
                })
            }, true);

            $('a').click(function() {
                let furl = $(this).attr('href');
                if (furl && !/^#.*$/.test(furl) && !/^javascript.*$/i.test(furl)) {
                    window._yas.sendAppLogs({
                        appop: 'YB_H5_PAGE_AB_FLR_C',
                        param: JSON.stringify({
                            C_ID: utils.queryString().yh_channel || 1,
                            PAGE_URL: window.originUrl,
                            PAGE_NAME: decodeURI(window.qs.title || document.title),
                            F_URL: furl,
                            CROWD_CODE: mkt_code + ''
                        })
                    }, true);
                }
            });
        }
    }, 1000);
};

let _getProduct = function(param) {
    $('.product-source').each(function(i, el){
        el = $(el);
        let cond = el.attr('condition');
        if (!cond) {
            return;
        }
        cond = JSON.parse(cond);

        let yh_channel = utils.queryString().yh_channel;
        if (cond.abtest) {
            abTestFlag = true;
        }

        if (yh_channel) {
            cond.yh_channel = yh_channel;
        }

        if (i > 3) {
            setTimeout(function(){
                _jsonp(el, param, cond);
            }, 300);
        } else {
            _jsonp(el, param, cond);
        }
    });

    abTestFlag && _abTest();
};

export default {
    init(uid) {
        if (!uid && utils.isApp()) {
            // document.addEventListener('deviceready', function() {
            //     window.yohoInterface.triggerEvent(function(data) {
            //         // 获取个性话数据
            //         _getProduct({
            //             uid: data.uid,
            //             udid: data.udid
            //         });
            //     }, function() {}, {
            //         method: 'get.analyticAppData'
            //     });
            // }, false);

            _getProduct({
                uid: '',
                udid: utils.queryString().udid || ''
            });
        } else {
            // 获取个性话数据
            _getProduct({
                uid: uid,
                udid: cookies.cookie('_yasvd')
            });
        }
    }
};