/*
 * @Author: Targaryen
 * @Date: 2017-06-21 10:30:21
 * @Last Modified by: Targaryen
 */
require('scss/buynow/order-ensure.page.scss');
const $ = require('yoho-jquery');
const lazyLoad = require('yoho-jquery-lazyload');
const cookie = require('yoho-cookie');
const qs = require('yoho-qs');
const OrderEnsure = require('./cartbuynow/order-ensure');

let tip = require('js/plugin/tip'),
    loading = require('js/plugin/loading'),
    dialog = require('js/plugin/dialog'),
    order = require('js/cart/buynow/order-info'),
    richTip = require('js/plugin/rich-tip');

let $invoice = $('.invoice'),
    $addressWrap = $('.address-wrap'),
    $coinCheck = $('.coin-check'),
    $coinLi = $('li.coin'),
    $subBlock = $('.sub-block'),
    $ticketsMobile = $('#mobile'),
    payType,
    queryString = $.queryString(),
    orderInfo = order.orderInfo,
    isSubmiting,
    dispatchInfo,
    total,
    headerTop = $('#yoho-header').outerHeight(),
    isYohoCoinClick = $coinLi.data('yoho-coin-click') * 1, // 判断有货币是否可以单击
    addressTop = $('.address-wrap').outerHeight(),
    $message = $('#msg'),
    delivery = 0,
    $noPrintPrice = $('.no-print-price');

const orderEnsure = new OrderEnsure(order);

require('js/common');

lazyLoad();

// 存 COOKIE
orderInfo('product_sku', qs.product_sku);

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

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

    if ($(e.target).closest('.coin-check').length && !isYohoCoinClick) {
        return true;
    }

    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');
    }
});

function updateDeliverWay(deliver_way) {
    let $moreJit = $('.more-jit a').get(0),
        url;

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

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

function orderCompute() {
    let use_yoho_coin = orderInfo('use_yoho_coin'),
        deliver_way = orderInfo('delivery_way'),
        data = {
            product_sku: qs.product_sku,
            buy_number: qs.buy_number,
            cart_type: orderInfo('cartType') || 'ordinary',
            delivery_way: orderInfo('delivery_way'),
            payment_type: orderInfo('payment_type'),
            coupon_code: orderInfo('coupon_code'),
            gift_card_code: orderInfo('gift_card_code'),
            use_yoho_coin: use_yoho_coin
        };

    loading.showLoadingMask();
    $.ajax({
        method: 'POST',
        url: '/cart/index/buynow/ordercompute',
        data: data
    }).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);
                $coinCheck.find('em').show();
            }
            if (res.gift_card) {
                $('#giftCardRightInfo').html('可以抵用¥' + res.gift_card.amount.toFixed(2));
            }
            $coinLi.find('.msg').html(res.yohoCoinCompute.yohoCoinMsg);
            isYohoCoinClick = res.yohoCoinCompute.yohoCoinClick * 1;
            $('.coin').data('yoho-coin', res.yohoCoinCompute.yohoCoin);

            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);
                $('.coupon .count').html(res.coupon.showText);
                $('.coupon .coupon-price-info').html(res.coupon.priceText);
            }

            updateDeliverWay(deliver_way);
        }
    }).fail(function() {
        window.location.reload();
    }).always(function() {
        loading.hideLoadingMask();
    });
}

/**
 * 提交订单
 * @param {短信验证码} verifyCode
 */
function submitOrder(verifyCode) {
    let msg = $('#msg').find('input').val() || orderInfo('msg');

    if (isSubmiting) {
        return false;
    }

    if (msg) {
        if (msg.length > 40) {
            tip.show('留言不得超过40个汉字');
            return;
        }
    }
    loading.showLoadingMask();
    isSubmiting = true;

    let postData = {
        product_sku: qs.product_sku,
        buy_number: qs.buy_number,
        address_id: orderInfo('address_id'),
        delivery_way: orderInfo('delivery_way'),
        delivery_time: orderInfo('delivery_time'),
        msg: msg,
        is_print_price: orderInfo('is_print_price'),
        payment_id: orderInfo('payment_id'),
        payment_type: orderInfo('payment_type'), // 支付方式
        coupon_code: orderInfo('coupon_code'),
        gift_card_code: orderInfo('gift_card_code'),
        verifyCode: verifyCode || null,
        use_yoho_coin: orderInfo('use_yoho_coin')
    };

    if (orderInfo('invoice')) {
        Object.assign(postData, {
            invoice: orderInfo('invoice'),
            invoices_title: orderInfo('invoices_title'), // 发票抬头
            invoices_type: orderInfo('invoices_type'), // 发票类型 1 纸质 2 电子
            invoice_payable_type: orderInfo('invoice_payable_type'), // 发票类型 1 个人 2 企业
            receiverMobile: orderInfo('receiverMobile'), // 接收人电话
            buyerTaxNumber: orderInfo('buyerTaxNumber') // 购买方纳税人识别号,需要开具
        });

        if (orderInfo('invoices_title_personal')) {
            Object.assign(postData, {
                invoices_title_personal: orderInfo('invoices_title_personal')
            });
        }
    }

    $.ajax({
        method: 'POST',
        url: '/cart/index/buynow/ordersub',
        data: postData
    }).then(function(res) {
        let 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/paynew?order_code=' + res.data.order_code;
            }

            if (window._yas && window._yas.sendCustomInfo) {
                window._yas.sendCustomInfo({
                    op: 'YB_SC_TOPAY_CLICK',
                    param: JSON.stringify({
                        C_ID: window._ChannelVary[cookie.get('_Channel')],
                        ORDER_CODE: res.data.order_code + '',
                        PRD_NUM: $('#goods-num').val(),
                        ORDER_AMOUNT: res.data.order_amount
                    })
                }, true);
            }

            if (window._fxcmd) {
                window._fxcmd.push(['trackOrder', {
                    oid: res.data.order_code,
                    otp: res.data.order_amount,
                    u_info: cookie.get('_UID'),
                    u_type: cookie.get('_isNewUser') ? 1 : 0
                }, []]);
            }

            cookie.remove(['buynow_info']);
            window.location.href = url;
        } else if (res.code === 409) {
            richTip.show(res.message, res.buttons);
        } else if (res.code === 440) {
            dialog.showDialog({
                dialogText: res.message,
                hasFooter: {
                    centerBtnText: '我知道了'
                }
            });
        } else if (res.code === 411) {
            orderEnsure.showSafeCheckDialog({
                message: res.message
            }, submitOrder);
        } else if (res.message) {
            tip.show(res.message);
        }
    }).fail(function() {
        tip.show('系统繁忙,请稍后再试!');
    }).always(function() {
        isSubmiting = false;
        loading.hideLoadingMask();
    });
}

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

$('.delivery-id').on('touchend', 'li', function(event) {
    if ($(this).hasClass('no-support')) {
        return false;
    }

    orderInfo('delivery_way', $(this).data('id'));

    // 实付金额发生变化,使用有货币为0
    orderInfo('use_yoho_coin', 0);
    $('.coin').find('.checkbox').removeClass('icon-cb-radio').addClass('icon-radio');

    orderCompute();
    event.stopPropagation();
});

$('.payment-type').on('touchend', 'li', function() {
    let $paymentType = $('.icon-cb-radio', this);

    orderInfo('payment_id', $paymentType.data('id')); // 支付方式id
    orderInfo('payment_type', $paymentType.data('payment-type')); // 支付方式
});

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

$('.yoho-coin-help-dialog-bg, .yoho-coin-footer').on('touchend', function(e) {
    e.preventDefault();
    $('.yoho-coin-help-dialog-bg').removeClass('show');
    $('.yoho-coin-help-dialog').removeClass('show');
});

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

    if ($(e.target).closest('.yoho-coin-help').length) {
        $('.yoho-coin-help-dialog-bg').addClass('show');
        $('.yoho-coin-help-dialog').addClass('show');
        return true;
    }

    if ($(e.target).closest('.coin-check').length <= 0) {
        return false;
    }

    if (!isYohoCoinClick) {
        return true;
    }

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

/**
 * 是否打印价格
 */
$noPrintPrice.on('touchend', '.checkbox', function(e) {
    let $this = $(this);

    orderInfo('is_print_price', $this.hasClass('icon-cb-radio') ? 'N' : 'Y');
    e.preventDefault();
    e.stopPropagation();
});

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

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

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

$('.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() {
    // 送货时间提示语li,不响应事件
    if ($(this).hasClass('dispatch-time-info')) {
        return true;
    }

    if ($(this).hasClass('no-support')) {
        return false;
    }

    $.each($(this).parents('ul').find('i'), function() {
        $(this).parents('ul').find('i').removeClass('icon-cb-radio').addClass('icon-radio');
    });
    let self = $(this);

    // 点击货到付款弹出提示语
    if (self.find('span').data('message') && delivery === 0 &&
        parseInt(self.find('i').data('payment-type'), 10) === 2) {

        dialog.showDialog({
            hasHeader: '温馨提示',
            dialogText: self.find('span').data('message'),
            hasFooter: {
                centerBtnText: '我知道了'
            }
        });

        delivery = 1;
    }

    setTimeout(function() {
        self.parents('ul').hide();
    }, 300);

    $('.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() {
    let $paymentType;

    $paymentType = $('.payment-type .icon-cb-radio');
    orderInfo('payment_id', $paymentType.data('id')); // 支付方式id
    orderInfo('payment_type', $paymentType.data('payment-type')); // 支付方式

    payType = $paymentType.data('payment-type');
    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('delivery_way', $('.delivery-id .icon-cb-radio').data('id'));
    orderCompute();
}

// 校验手机号
$ticketsMobile.blur(function() {
    let reg = /^[0123456789]{1,30}$/;
    let mobile = $ticketsMobile.val();

    if (!reg.test(mobile)) {
        tip.show('手机号码不正确!');
    }
});

// 留言点击滚动屏幕
$message.on('click', function() {
    $('html,body').animate({
        scrollTop: $message.offset().top
    }, 500);
});

$(window).scroll(function() {

    if ($(this).scrollTop() >= (headerTop + addressTop)) {
        $('.address-bottom').show();
    } else {
        $('.address-bottom').hide();
    }
});

// 商品是否支持退换货原因弹框
$('.no-support-reason').click(function() {
    dialog.showDialog({
        dialogText: '该商品支持7天无理由退换,不支持7天以上15天内的无理由换货,如有疑问,请联系客服',
        hasFooter: {
            centerBtnText: '我知道了'
        }
    });
});