/**
 * 订单确认
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2015/11/12
 */

var $ = require('jquery'),
    lazyLoad = require('yoho.lazyload'),
    tip = require('../plugin/tip'),
    loading = require('../plugin/loading'),
    order = require('./order-info');

var $invoice = $('.invoice'),
    $couponUse = $('.coupon-use.used'),
    $addressWrap = $('.address-wrap'),
    $coinCheck = $('.coin-check'),
    $coinUsed = $('.coin .used'),
    $subBlock = $('.sub-block'),
    payType,
    queryString = $.queryString(),
    orderInfo = order.orderInfo,
    isSubmiting,
    dispatchInfo,
    total;

var orderCont = window.cookie('order-info') && JSON.parse(window.cookie('order-info'));
var invoiceCont = {
        7: '服装',
        1: '图书',
        9: '配件',
        11: '日用品',
        3: '办公用品',
        6: '体育用品',
        10: '数码产品'
    },
    invoicesType = {
        1: '纸质',
        2: '电子'
    };

require('../common');

lazyLoad();

// 初始化发票信息
function invoiceInit() {
    if (orderCont.invoiceType) {
        $('.invoice-type').text(invoiceCont[orderCont.invoiceType] + '(' + invoicesType[orderCont.invoicesType] + ')');
    } else {
        $('.invoice-type').text('服装(电子)');
    }
}

function getQueryParam() {
    var queryArray = location.search.substr(1).split('&'),
        i,
        subArr = [],
        obj = {};

    for (i = 0; i < queryArray.length; i++) {
        subArr = queryArray[i].split('=');
        obj[subArr[0]] = subArr[1];
        subArr = [];
    }

    return obj;
}

function isLimitGood() {
    return getQueryParam().limitproductcode;
}


if (window.getUid() !== orderInfo('uid')) {
    order.init();
    window.location.reload();
}

if ($couponUse.data('name') !== orderInfo('couponName')) {
    orderInfo('couponCode', null);
    orderInfo('couponName', null);
}

// 来自购物车的链接默认不使用优惠券
if (document.referrer && document.referrer.indexOf('/cart/index/index') !== -1) {
    orderInfo('couponCode', null);
    orderInfo('couponName', null);
}

isLimitGood() && (function() {
    var a = [];

    var data = getQueryParam();

    data.type = 'limitcode';

    a.push(data);
    orderInfo('skuList', JSON.stringify(a));
    orderInfo('limitUrlSufix', location.search);
})();

if (queryString.cartType || queryString.carttype || !orderInfo('cartType')) {
    orderInfo('cartType', queryString.cartType || queryString.carttype || 'ordinary');
}

// function dispacthTapEvt(e) {
//     var $cur = $(e.target).closest('li');

//     if ($cur.length === 0 || $cur.hasClass('chosed')) {
//         return;
//     }

//     $cur.siblings('li.chosed').removeClass('chosed');
//     $cur.addClass('chosed');
// }

$('.checkbox').on('touchstart', function() {
    var $this = $(this);

    if ($this.hasClass('icon-cb-radio')) {
        $this.removeClass('icon-cb-radio').addClass('icon-radio');
        return;
    }
    if ($this.hasClass('icon-radio')) {
        $this.removeClass('icon-radio').addClass('icon-cb-radio');
    }
});

$invoice.on('touchend', '.checkbox', function() {
    var $this = $(this);

    if ($this.hasClass('icon-cb-radio')) {
        $invoice.addClass('focus');
        orderInfo('invoiceText', '');
        orderInfo('invoiceType', '7');
        orderInfo('receiverMobile', $('.user-mobile').val());
        orderInfo('invoicesType', '2');
        orderInfo('invoiceTitle', '个人');
    }
    if ($this.hasClass('icon-radio')) {
        $invoice.removeClass('focus');
        orderInfo('invoiceText', null);
        orderInfo('invoiceType', null);
        orderInfo('receiverMobile', null);
        orderInfo('invoicesType', null);
        orderInfo('invoiceTitle', null);
    }

    orderCont = window.cookie('order-info') && JSON.parse(window.cookie('order-info'));
    invoiceInit();
});


function updateDeliverId(id) {
    var $moreJit = $('.more-jit a').get(0),
        url;

    if ($moreJit) {
        url = $moreJit.href;
    } else {
        return;
    }

    if (url.indexOf('deliveryId') < 0) {
        $moreJit.href = url + '&deliveryId=' + id;
    } else {
        $moreJit.href = url.replace(/deliveryId=(\d)/, 'deliveryId=' + id);
    }
}

function orderCompute() {
    var yohoCoin = orderInfo('yohoCoin'),
        deliverId = orderInfo('deliveryId');

    loading.showLoadingMask();
    $.ajax({
        method: 'POST',
        url: '/cart/index/orderCompute',
        data: {
            cartType: orderInfo('cartType') || 'ordinary',
            deliveryId: orderInfo('deliveryId'),
            paymentTypeId: orderInfo('paymentTypeId'),
            couponCode: orderInfo('couponCode'),
            yohoCoin: yohoCoin,
            skuList: isLimitGood() ? orderInfo('skuList') : undefined
        }
    }).then(function(res) {
        if ($.type(res) !== 'object') {
            window.location.reload();
        } else {
            if (typeof res.last_order_amount !== undefined) {
                res.last_order_amount = (+res.last_order_amount).toFixed(2);
            }
            if (res.use_yoho_coin) {
                $coinCheck.find('em').html('- ¥ ' + res.use_yoho_coin);
                $coinUsed.html('已抵¥' + res.use_yoho_coin);
                $coinCheck.find('em').show();
                $coinUsed.show();
            }
            total = '';
            if (res.promotion_formula_list) {
                $.each(res.promotion_formula_list, function(index, value) {
                    total += '<li>' +
                            '<p>' + value.promotion + '</p>' +
                            '<span>' + value.promotion_amount + '</span>' +
                            '</li>';
                });
                $('.price-cost span').html('¥' + res.last_order_amount);
                $('.bill span').html('¥' + res.last_order_amount);
                $('.total').html(total);
            }

            updateDeliverId(deliverId);
        }
    }).fail(function() {
        window.location.reload();
    }).always(function() {
        loading.hideLoadingMask();
    });
}

function submitOrder() {
    var invoiceText = $invoice.find('[name="invoice-title"]').val() || orderInfo('invoiceText'),
        msg = $('#msg').find('input').val() || orderInfo('msg');

    if (isSubmiting) {
        return false;
    }

    // if (orderInfo('invoice')) {
    //     if (!invoiceText) {
    //         tip.show('请输入发票抬头');
    //         return;
    //     }
    //     if (invoiceText.length > 30) {
    //         tip.show('发票抬头不得超过30个汉字');
    //         return;
    //     }
    // }

    if (msg) {
        if (msg.length > 40) {
            tip.show('留言不得超过40个汉字');
            return;
        }
    }
    loading.showLoadingMask();
    isSubmiting = true;
    $.ajax({
        method: 'POST',
        url: '/cart/index/orderSub',
        data: {
            addressId: orderInfo('addressId'),
            cartType: orderInfo('cartType') || 'ordinary',
            deliveryId: orderInfo('deliveryId'),
            deliveryTimeId: orderInfo('deliveryTimeId'),
            invoiceText: orderInfo('invoice') ? invoiceText : null,
            invoiceType: orderInfo('invoice') ? ($invoice.find('.invoice-type').val() ||
                orderInfo('invoiceType')) : null,
            msg: msg,
            paymentTypeId: orderInfo('paymentTypeId'),
            paymentType: orderInfo('paymentType'), //支付方式
            couponCode: orderInfo('couponCode'),
            yohoCoin: orderInfo('yohoCoin'),
            skuList: isLimitGood() ? orderInfo('skuList') : undefined

        }
    }).then(function(res) {
        var url;

        if (!res) {
            tip.show('系统繁忙,请稍后再试!');
            return;
        }
        if (res.code === 200) {
            if (payType === 2) {

                // 货到付款的进入订单页面
                url = '/home/orderDetail?order_code=' + res.data.order_code;
            } else {
                url = '/home/orders/pay?order_code=' + res.data.order_code;
            }
            window.setCookie('order-info', '');
            window.location.href = url;
        } else if (res.message) {
            tip.show(res.message);
        }
    }).fail(function() {
        tip.show('系统繁忙,请稍后再试!');
    }).always(function() {
        isSubmiting = false;
        loading.hideLoadingMask();
    });
}

// 界面点击,状态存 cookie
if (!orderInfo('addressId')) {
    orderInfo('addressId', $addressWrap.data('id'));
}

$('.delivery-id').on('touchend', 'li', function() {
    orderInfo('deliveryId', $(this).data('id'));
    orderCompute();
});

$('.payment-type').on('touchend', 'li', function() {
    orderInfo('paymentType', $('.icon-cb-radio', this).data('id'));
});

$('.dispatch-time').on('touchend', 'li', function() {
    orderInfo('deliveryTimeId', $(this).data('id'));
});

$('.coin').on('touchend', function() {
    var $this = $(this);

    if ($this.find('.checkbox').hasClass('icon-cb-radio')) {
        orderInfo('yohoCoin', $this.data('yoho-coin'));
        $this.find('.can-use').hide();
    } else {
        orderInfo('yohoCoin', 0);
        $this.find('.coin-check em').hide();
        $this.find('.can-use').show();
        $this.find('.used').hide();
    }
    orderCompute();
});

$invoice.on('touchend', '.checkbox', function(e) {
    var $this = $(this);

    orderInfo('invoice', $this.hasClass('icon-cb-radio'));
    e.preventDefault();
    e.stopPropagation();
});

$invoice.find('[name="invoice-title"]').on('blur', function() {
    orderInfo('invoiceText', $(this).val());
}).end().find('.invoice-type').on('change', function() {
    orderInfo('invoiceType', $(this).val());
});

$('#msg').find('textarea').on('blur', function() {
    orderInfo('msg', $(this).val());
});

$('.pay-mode').on('click', 'li', function() {
    var $this = $(this);

    orderInfo('paymentTypeId', $this.data('pay-id'));
    orderInfo('paymentType', $this.data('pay-type'));
    payType = $this.data('pay-type');
});

$('form').on('submit', function() {
    return false;
});

// xwg 2016/3/21 13:22
$('.dispatch').on('touchend', 'h3', function() {
    if ($(this).siblings('ul').is(':hidden')) {
        $('.dispatch h3').removeClass('border-none');
        $(this).addClass('border-none');
        $('.down').removeClass('hide');
        $('.up').addClass('hide');
        $('.up', this).removeClass('hide');
        $('.down', this).addClass('hide');
        $('.dispatch ul').hide();
        $(this).siblings('ul').show();
    } else {
        $(this).removeClass('border-none');
        $('.down', this).removeClass('hide');
        $('.up', this).addClass('hide');
        $(this).siblings('ul').hide();
    }
});

$subBlock.on('touchstart', 'li', function() {
    $.each($(this).parents('ul').find('i'), function() {
        $(this).parents('ul').find('i').removeClass('icon-cb-radio').addClass('icon-radio');
    });
    $(this).parents('ul').hide();
    $('.down').removeClass('hide');
    $('.up').addClass('hide');
    $('.dispatch h3').removeClass('border-none');
    dispatchInfo = $(this).find('span').html();
    $(this).parents('.sub-block').find('h3 span').html(dispatchInfo);
    if ($(this).find('i').hasClass('icon-cb-radio')) {
        $(this).find('i').addClass('icon-radio');
    } else if ($(this).find('i').hasClass('icon-radio')) {
        $(this).find('i').addClass('icon-cb-radio');
    }
});


$('.bill a').on('touchstart', function() {
    orderInfo('paymentTypeId', $('.delivery-id .icon-cb-radio').data('id'));
    orderInfo('paymentType', $('.payment-type .icon-cb-radio').data('id'));

    payType = $('.payment-type .icon-cb-radio').data('id');
    submitOrder();
});

function phoneHidden(phone) {
    phone = phone || '';
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}

$('.info-phone').html(phoneHidden($('.info-phone').html()));

if (orderInfo('address') && orderInfo('address').is_support === 'N') {
    orderInfo('deliveryId', $('.delivery-id .icon-cb-radio').data('id'));
    orderCompute();
}

// 初始化发票信息内容
invoiceInit();