/**
 * 赠品/加价购
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2015/10/23
 */

let $ = require('yoho-jquery'),
    lazyLoad = require('yoho-jquery-lazyload'),
    Hammer = require('yoho-hammer'),
    tip = require('plugin/tip'),
    loading = require('plugin/loading'),
    chosePanel = require('common/chose-panel-new');

let $page = $('.gift-advance-page'),
    queryString = $.queryString();

require('common');

lazyLoad($('.lazy'));

function getProductInfo(skn, promotionId) {
    loading.showLoadingMask();
    $.post('/cart/index/new/giftinfo', {
        skn: skn,
        promotionId: promotionId
    }).then(function(data) {

        if (!data) {
            tip.show('网络错误');
            return;
        }
        chosePanel.show({
            data,
            disableNum: true
        }).then(result => {
            if (result && result.sku) {
                let goodData,
                    url;

                if (queryString.edit) {
                    url = '/cart/index/new/modifyPriceGift';
                    goodData = {
                        new_product_sku: result.sku.skuId,
                        new_product_skn: result.skn,
                        buy_number: result.buyNum,
                        selected: true,
                        promotionId,
                        isEdit: 1
                    };
                } else {
                    url = '/cart/index/add';
                    goodData = {
                        productSku: result.sku.skuId,
                        new_product_skn: skn,
                        buyNumber: result.buyNum,
                        promotionId
                    };
                }
                $.ajax({
                    method: 'POST',
                    url: url,
                    data: goodData
                }).done(function(res) {
                    if (res && res.code === 200) {
                        window.location.href = '/cart/index/index';
                    }
                }).fail(function() {
                    tip.show('网络出了点问题~');
                });
            }
        }, () =>{});
    }, function() {
        tip.show('网络错误');
    }).always(function() {
        loading.hideLoadingMask();
    });
}

$page.find('.chose').each(function(i, elem) {
    let choseHammer = new Hammer(elem);

    choseHammer.on('tap', function(e) {
        let $this = $(e.target),
            id = $this.closest('.gift-advance-good').data('id'),
            promotionId = $this.closest('.advance-block').data('promotion-id');

        getProductInfo(id, promotionId);
    });
});