var Id;

function EditStockIn(Id) {
    location.href = "/Warehouse/StockInEdit?id=" + Id + "&GoBackURL=" + GetGoBackUrl();    
}

function ApproveStockIn(Id) {
    synConfirm("确定审核吗？<br/>提示：审核后库存信息将被自动更新。", function () {
        $.ajax({
            url: "/Warehouse/ApproveStockIn",
            type: 'POST',
            cache: false,
            data: { Id: Id },
            success: function (result) {
                if (result.code == 0) {                    
                    location.reload();
                }
                else {
                    alert(result.message);
                }
            },
            error: function (e) {
                alert('审核失败，请稍后再试');
            }
        });
    });   
}

function UnApproveStockIn(Id) {
    synConfirm("确定反审核吗？<br/>提示：反审核后库存信息将被自动更新。", function () {
        $.ajax({
            url: "/Warehouse/UnApproveStockIn",
            type: 'POST',
            cache: false,
            data: { Id: Id },
            success: function (result) {
                if (result.code == 0) {
                    location.reload();
                }
                else {
                    alert(result.message);
                }
            },
            error: function (e) {
                alert('反审核失败，请稍后再试');
            }
        });
    });     
}

function GetGoBackUrl() {
    var url = {};
    url.root = "/Warehouse/StockIn";
    url.paras = [];

    if ($("#sSupplierId").val() != "") {
        url.paras.push({ name: "sSupplierId", value: $("#sSupplierId").val() });
    }
    if ($("#sType").val() != "") {
        url.paras.push({ name: "sType", value: $("#sType").val() });
    }
    if ($("#sStatus").val() != "") {
        url.paras.push({ name: "sStatus", value: $("#sStatus").val() });
    }

    if ($("#sPaymentStatus").val() != "") {
        url.paras.push({ name: "sPaymentStatus", value: $("#sPaymentStatus").val() });
    }
    if ($("#sEndDate").val() != "") {
        url.paras.push({ name: "sEndDate", value: $("#sEndDate").val() });
    }
    if ($("#sBeginDate").val() != "") {
        url.paras.push({ name: "sBeginDate", value: $("#sBeginDate").val() });
    }
    if ($("#sKeywords").val() != "") {
        url.paras.push({ name: "sKeywords", value: $("#sKeywords").val() });
    }

    return JSON.stringify(url);
}

function DeleteStockIn(Id) {

    ClearErrorMsg();     

    synConfirm("确定删除吗？<br/>提示：与该进货单相关的日志及支付记录将一并删除。", function () {
        $.ajax({
            url: "/Warehouse/DeleteStockIn",
            type: 'POST',
            cache: false,
            data: { Id: Id },
            success: function (result) {
                if (result.code == 0) {
                    $("#tStockIn").find("tr[id='" + Id + "']").remove();
                }
                else {
                    alert(result.message);
                }
            },
            error: function (e) {
                alert('删除失败，请稍后再试');
            }
        });
    });    

    return false;
}

$(function () {

    $("#sSupplierId").select2();

    setOperationBtns();

    TdRowOverOut("tStockIn");  
    SetSpanColor("tStockIn");

    $("#tStockIn tr td").click(function () {
        if ($(this).parent().hasClass("totalTd")) {
            return;
        }
        if ($(this).hasClass("td-last") || $(this).hasClass("td-checkbox")) {
            return;
        }
        else {
            ShowStockInDetail($(this).parent().attr("id"));
        }
    });

    $('#divPayment').dialog({
        width: 700,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });

    $('#divBatchPayment').dialog({
        width: 600,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });  

    $('#btnNew').click(function () {       
        location.href = "/Warehouse/StockInEdit?GoBackURL=" + GetGoBackUrl();     
    });
    
    GetGroupedMaterial("sMaterial", $("#hiddenMaterial").val());
    $("#sMaterial").select2();
});

function AddPayment(id, paymentType) {
    Id = id;
    $.ajax({
        url: "/Warehouse/GetStockInPaymentDetail",
        type: 'POST',
        cache: false,
        data: { Id: id },
        success: function (result) {
            if (result.code == 0) {
                
                $("#Amount").html(result.data.Amount);
                $("#Paid").html(result.data.Paid);
                $("#PaymentHistory").html(result.data.PaymentHistory);

                if (result.data.Unpaid == 0) {
                    $("#unpaidDiv").hide();
                }
                else {
                    $("#unpaidDiv").show();
                    $("#unpaidAmount").html(result.data.Unpaid);

                    $("#trAddPayment2").show();
                    $("#trAddPayment3").show();
                    $("#btnAddPayment").show();
                }                

                $("#pdPaymentStatus").html(result.data.PaymentStatus);
                $("#PaymentAmount").val("");
                $("#PaymentMemo").val("");

                $("#PaymentType").val(paymentType);                

                SetSpanColor("divPayment");

                $('#divPayment').dialog('open');
            }
            else {
                alert("获取信息失败.");
            }

        },
        error: function (e) {
            alert("获取信息失败.");
        }
    });
}

function AddBatchPayment() {

    var totalUnpaid = 0;

    $("#stockInList").find("input[type=checkbox]").each(function (v, val) {
        if ($(val).prop("checked")) {
            var amount, paid;
            amount = $(val).parent().parent().find("#s1").html();
            paid = $(val).parent().parent().find("#s2").html();
            
            totalUnpaid = totalUnpaid + parseFloat(amount);

            if (paid!="" && !isNaN(paid)) {
                totalUnpaid = totalUnpaid - parseFloat(paid);  
            } 
             
        }
    });

    $("#batchUnpaidAmount").html(FixTwoDecimal(totalUnpaid));
    $("#divBatchPayment #PaymentAmount").val('');
 
    $('#divBatchPayment').dialog('open');
}

function BatchPaymentSubmit() {
    ClearErrorMsg("divBatchPayment");

    if (checkRequired('divBatchPayment', '') == false) {
        return;
    }

    var payAmount = $("#divBatchPayment #PaymentAmount").val();

    synConfirm("支付金额为 " + payAmount + " ，确定支付吗？",
        function () {
            $.ajax({
                url: "/Warehouse/StockInBatchPaymentAdd",
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: { Ids: GetSelectedIds(), PaymentAmount: payAmount, PaymentType: $("#batchPaymentType").val(), PaymentMemo: $("#batchPaymentMemo").val() },
                success: function (result) {
                    if (result.code == 0) {
                        location.reload();
                    }
                    else {
                        SetErrorMsg(result.message, "divBatchPayment");
                    }
                },
                error: function (e) {
                    SetErrorMsg('批量支付失败', "divBatchPayment");
                }
            });
        })
}

function PaymentSubmit() {
    ClearErrorMsg("divPayment");

    if (checkRequired('divPayment', 'errorMessagePayment') == false) {
        return;
    }

    if (parseFloat($("#PaymentAmount").val()) < 0) {
        if ($.trim($("#PaymentMemo").val()) == "") {
            $("#PaymentMemo").addClass("redBorder");
            return;
        }
    }

    if (parseFloat($("#PaymentAmount").val()) > parseFloat($("#unpaidAmount").html())) {
        return SetErrorMsg("总支付金额不能大于未付金额。", "divPayment");
    }

    return synConfirm("确定支付信息填写正确，并保存吗？", savePayment);

}


function savePayment() {
    $.ajax({
        url: "/Warehouse/StockInPaymentAdd",
        type: 'POST',
        cache: false,
        dataType: 'json',
        data: { Id: Id, PaymentAmount: $("#PaymentAmount").val(), PaymentType: $("#PaymentType").val(), PaymentMemo: $("#PaymentMemo").val() },
        success: function (result) {
            if (result.code == 0) {
                location.reload();
            }
            else {
                SetErrorMsg(result.message, "divPayment");
            }
        },
        error: function (e) {
            SetErrorMsg("错误：支付提交，请稍后再试", "divPayment");
        }
    });

}

function btnBatchPayment() {
    ClearErrorMsg();
    $("#batchPaymentType").val("");
    $("#batchPaymentMemo").val("");

    if (SelectedNumber() < 2) {
        return SetErrorMsg('批量支付需要选择多条记录');
    }

    if (!CheckSingleSuppliler()) {
        return SetErrorMsg('只能选择同一个供应商的订单进行批量支付');
    }

    AddBatchPayment();
}

function CheckSingleSuppliler() {
    var supplier = "";
    var result = true;
    $("#stockInList").find("input[type=checkbox]").each(function (v, val) {
        if ($(val).prop("checked")) {
            if (supplier == "") {
                supplier = $(val).parent().parent().find("td:eq(3)").html();
            }
            else {
                if (supplier != $(val).parent().parent().find("td:eq(3)").html()) {
                    result = false;
                    return;
                }
            }
        }
    });

    return result;
}

