$(document).ready(function () {
    InitDialog();
    InitSumAmount();
    $(".item_delete").live("click", function () {
        $(this).parent().parent().remove(); SumAmount();
        if ($(".table_list").find('tr').length == 2) {
            $(".good_tip").show();
        } else {
            $(".good_tip").hide();
        }
    })
    $(".p_paynum").live("blur", function () { SumAmount(); })
    $(".p_price").live("blur", function () { SumAmount(); })
})
//初始化弹出框控件事件
function InitDialog() {
    //负责人选择
    $("#btnUserSelect").click(function () {
        OpenRadioDialog('/Dialog/EmploySelectDialog.aspx?user=0', '选择负责人', function (text, value) {
            $("#ctl00_ContentPlace_lblTrackUserName").html(text);
            $("#ctl00_ContentPlace_hdfTrackUserID").val(value);
        });
    });
    $("#btnUserClear").click(function () {
        $(".TrackUserName").val("");
        $("#ctl00_ContentPlace_hdfTrackUserID").val("");
    });
    //客户选择
    $("#ctl00_ContentPlace_btnCustomerSelect").click(function () {
        OpenRadioDialog('/Dialog/CustomerDialog.aspx', '选择客户', function (text, value) {
            $("#ctl00_ContentPlace_lblCustomerName").html(text);
            $("#ctl00_ContentPlace_hdfCustomerId").val(value);

            $("#ctl00_ContentPlace_LinkCustomer").attr("href", "/crm/Customer/CustomerView.aspx?CustomerId=" + value);

        });
    });
    $("#btnCustomerClear").click(function () {
        $(".CustomerName").val("");
        $("#ctl00_ContentPlace_hdfCustomerId").val("");
        $("#ctl00_ContentPlace_hdfRegionId").val("");
        $("#ctl00_ContentPlace_addrs").text("");
    })
    //地址选在
    $(".addrsDialog").click(function () {
        var customerId = $('#ctl00_ContentPlace_hdfCustomerId').val();
        if (customerId == null || customerId == "") {
            alert("请先选择下单客户");
            return;
        }
        OpenRadioDialog('/Dialog/CAddrsSelectDialog.aspx?CId=' + customerId, '选择收货地址', function (text, value) {
            $('#ctl00_ContentPlace_addrs').text(text);
            $('#ctl00_ContentPlace_hdfRegionId').val(value);
        });
    })
    //添加商品
    $('input[name="btnAdd"]').click("click", function () {
        AddGood();
    })
    $(".btnAdd").click("click", function () {
        AddGood();
    })
}
//初始化金额计算控件
function InitSumAmount() {
    if ($("#ctl00_ContentPlace_chkbInvoice").attr("checked")) { $(".bInvoice_item").show(); }
    //配送方式
    var ShippingList = document.getElementsByName("ctl00$ContentPlace$ddlShippingId");
    for (var i = 0; i < ShippingList.length; i++) {

        $(ShippingList[i]).click(function () {
            var freight = $(this).parent().attr("freight");
            $("#ctl00_ContentPlace_txtFreight").val(freight);

            SumAmount();

        })
    }

    $("#ctl00_ContentPlace_txtFreight").blur(function () { SumAmount(); });
    //支付方式

    var PayMothodList = document.getElementsByName("ctl00$ContentPlace$ddlPayMothodId");
    for (var i = 0; i < PayMothodList.length; i++) {

        $(PayMothodList[i]).click(function () {

            SumAmount();

        })
    }
    //发票类型
    var InvTypeList = document.getElementsByName("ctl00$ContentPlace$rdoInvType");

    for (var i = 0; i < InvTypeList.length; i++) {
        
        $(InvTypeList[i]).click(function () {
            
            if ($(this).val() == "1")
                $("#ctl00_ContentPlace_DivInv").show();
            else
                $("#ctl00_ContentPlace_DivInv").hide();

        })
    }

    //保险费
    $("#ctl00_ContentPlace_txtInsurance").blur(function () { SumAmount(); });
    //发票税
    $("#ctl00_ContentPlace_txtTax").blur(function () { SumAmount(); });


    $("#ctl00_ContentPlace_chkbInvoice").change(function () {
        if ($(this).attr("checked")) { $(".bInvoice_item").show(); } else { $(".bInvoice_item").hide(); }
        SumAmount();
    })
}

function GetFee() {

    var PayMothodList = document.getElementsByName("ctl00$ContentPlace$ddlPayMothodId");
    for (var i = 0; i < PayMothodList.length; i++) {

        if (PayMothodList[i].checked) {

            var fee = $(PayMothodList[i]).parent().attr("fee");

            return fee;
        }

    }
}
//金额计算
function SumAmount() {
    var freight = parseFloat($("#ctl00_ContentPlace_txtFreight").val());
    var fee = GetFee();
    var insurance = parseFloat($("#Insurance").html());
    var tax = parseFloat($("#ctl00_ContentPlace_txtTax").val());

    var g_amount = GetProductPrice();
    if (isNaN(freight) || freight == "") freight = 0;
    if (isNaN(fee)) fee = 0;
    if (isNaN(insurance) || insurance == "") insurance = 0;
    if (isNaN(tax) || tax == "") tax = 0;
    if (isNaN(g_amount)) g_amount = 0;

    var fee_amount = (freight + g_amount + insurance + tax) * fee * 0.01; //手续费
    var order_amount = freight + g_amount + fee_amount + insurance + tax; //订单总金额
    $("#pAmount").text(g_amount);
    $("#freight").text(freight);
    $("#fee").text(fee_amount.toFixed(2) + "(" + fee + "%)");
    $("#amount").text(order_amount.toFixed(2));
    //$("#Insurance").text(insurance.toFixed(2));
    $("#ctl00_ContentPlace_hdfGoodsAmount").val(g_amount.toFixed(2));
    $("#ctl00_ContentPlace_hdfPayFee").val(fee_amount.toFixed(2));
    $("#ctl00_ContentPlace_hifOrderTotal").val(order_amount.toFixed(2));
}
//商品总金额
function GetProductPrice() {
    var product_price = 0;
    var trs = $(".table_list").find("tr");
    $.each(trs, function (index, tr) {
        if (index > 1) {
            var pric = parseFloat($(tr).find(".p_price").val());
            var count = parseInt($(tr).find(".p_paynum").val());
            product_price += pric * count;
        }
    });

    return product_price;
}
//添加商品
function AddGood() {
    art.dialog.open('OrderProductSelect.aspx', {
        title: '添加商品',
        ok: function () {
            var dBody = $(this.iframe.contentWindow.document.body);
            var TrSN = dBody.find('.tr_sn');
            var SkuId = dBody.find('#hdfSkuId').val();
            var SKUName = dBody.find('#txtSKUName').val();
            var SKUCode = dBody.find('#hdfSKUCode').val();
            var PyaSum = dBody.find('#txtPyaSum').val();
            var Price = dBody.find('#txtPrice').val();
            var Unit = dBody.find(' .unit').text();
            var IsRenewal = dBody.find('#hdfIsRenewal').val();

            var HasSn = dBody.find('#hdfHasSn').val();
            var SellorRent = dBody.find('#hdfSellorRent').val();

            var SN = "";
            if (SkuId == "" || SKUName == "" || PyaSum == "" || Price == "")
            { alert("请补充完整信息"); return false; }
            if (TrSN.is(":hidden") == false) {
                SN = dBody.find("#txtSN").val();
                if (SN == "") {
                    alert("请选序列号");
                    return false;
                }
            }
            $("#ctl00_ContentPlace_hdfIsRenewal").val(IsRenewal);
            var b = $(".table_list").find('input[name="p_id[' + SkuId + ']"]').length > 0;
            
            if (!b || (HasSn == "1" && SellorRent == "2")) {
                var row = "<tr align=\"left\">";
                row += "<td ><a href=\"javascript:void(0);return false;\" class=\"item_delete\">删除<\/a>";
                row += "<input name=\"p_id[" + SkuId + "]\" value=\"" + SkuId + "\" type=\"hidden\" \/>";
                row += "<input name=\"p_SN[" + SkuId + "]\" value=\"" + SN + "\" type=\"hidden\"  \/>";
                row += "<input name=\"p_IsRenewal[" + SkuId + "]\" value=\"" + IsRenewal + "\" type=\"hidden\"  \/>";
                row += "<\/td>";
                row += "<td>" + SKUCode + "<\/td>";
                row += "<td>" + SKUName;
                if (IsRenewal == "1") {
                    row += "<span class=\"red\">[续单]<\/span>";
                }
                if (SN != "") {
                    row += "<span>（序列号：" + SN + "）<\/span>";
                }
                row += "<\/td><td>";
                row += "<input type=\"text\" name=\"p_price[" + SkuId + "]\" class=\"p_price text width50\" value=\"" + Price + "\" \/><\/td>";
                row += "<td><input type=\"text\" name=\"p_paynum[" + SkuId + "]\" class=\"p_paynum text width50\" value=\"" + PyaSum + "\" \/>";
                row += Unit + "<\/td>";
                row += '</tr>';
                $(".table_list").append(row);
            }
            else
                alert("同时满足租用和开启序列号的商品才能重复添加");
            if ($(".table_list").find('tr').length == 2) {
                $(".good_tip").show();
            } else {
                $(".good_tip").hide();
            }
            SumAmount();
        },
        cancel: true
    }, false).lock();
}