index.page.js 2.75 KB
/**
 * 购物车商品
 * @author: feng.chen<feng.chen@yoho.cn>
 * @date: 2016/12/22
 */
'use strict';

let cookie = require('yoho-cookie');

require('cart/index.page.css');
require('../common');
let $ = require('yoho-jquery'),
    hbsTemplate = require('cart/index/index.hbs'),
    lazyLoad = require('yoho-jquery-lazyload'),
    loading = require('../plugin/loading');

let indexObj = {
    editMode: false,
    posting: false,
    init() {
        let self = this;

        $('.nav-btn').on('click', () => {
            self.navClick();
        });
        self.refreshPage();
        require('./index/recommend-for-you').init(self);
    },
    navClick() {
        let self = this;

        $('.main-wrap').toggleClass('edit');
        if ($('.main-wrap').hasClass('edit')) {
            self.editMode = true;
            $('.chk.edit').removeClass('checked');
        } else {
            self.editMode = false;
        }
    },
    getCartData() {
        return $.ajax({
            url: '/cart/index/new/data',
            type: 'POST'
        });
    },
    refreshPage(data) {
        let self = this;

        if (!data) {
            loading.showLoading();
            return self.getCartData().then(cartData => {
                return self.renderPage(cartData.data, true).then(() => {
                    loading.hideLoading();
                });
            });
        }
        return self.renderPage(data);
    },
    renderPage(data, no_try) {
        let self = this;

        if ((!data || (!data.commonCart && !data.preSellCart)) && no_try !== true) {
            self.refreshPage();
            return;
        }
        let cartType = cookie.get('_cartType') || 'ordinary';

        // 普通购物车空,则显示预售购物车

        if (data.commonGoodsCount === 0 && data.ordinarySoldOut === 0) {
            data.cartNav = false;
            data.cartType = 'advance';
        } else if (data.presellGoodsCount === 0 && data.advanceSoldOut === 0) { // 预售购物车空,则显示普通购物车
            data.cartNav = false;
            data.cartType = 'ordinary';
        } else { // 以上两个购物车中都有数据, 默认显示普通购物车
            data.cartNav = true;
            data.cartType = cartType || 'ordinary';
        }
        cookie.set('_cartType', data.cartType);
        data.ordinaryCart = data.cartType === 'ordinary';
        data.advanceCart = !data.ordinaryCart;
        if (data.isEmptyCart) {
            $('.nav-btn').hide();
        } else {
            $('.nav-btn').show();
        }
        $('.cart-box').html(hbsTemplate(data));
        require('./index/cart').init(self);
        require('./index/good').init(self);
        lazyLoad($('img.lazy'));
        return Promise.resolve();
    }
};

$(() => {
    indexObj.init();
});