var FactoryOrderNo;


$(function () {

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

    setOperationBtns();

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

    TdRowOverOutWithSpan("tOrder");
    SetSpanColor("tOrder");

    $("#PaymentAmount").inputmask({ 'mask': "-{0,1}9{0,9}[.9{0,2}]", greedy: false });

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

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

function AddPayment(id, paymentType) {
    $.ajax({
        url: "/FactoryOrder/GetPaymentDetail",
        type: 'POST',
        cache: false,
        data: { FactoryOrderNo: 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);

                FactoryOrderNo = result.data.FactoryOrderNo;

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

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

function AddBatchPayment() {

    var totalUnpaid = 0;

    $("#orderList").find("input[type=checkbox]").each(function (v, val) {
        if ($(val).prop("checked")) {
            totalUnpaid = totalUnpaid + parseFloat($(val).parent().parent().find("span[id='s2']").html());
        }
    });

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

    $('#divBatchPayment').dialog('open');
}

function BatchComplete() {

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

    synConfirm("确定对所选记录批量完工吗？",
        function () {
            $.ajax({
                url: "/FactoryOrder/BatchComplete",
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: { FactoryOrderNo: GetSelectedIds() },
                success: function (result) {
                    if (result.code == 0) {
                        RefreshPage();
                    }
                    else {
                        alert(result.message);
                    }
                },
                error: function (e) {
                    alert('批量支付失败');
                }
            });
        });


}

function DeleteOrder(id, FactoryOrderNo, orderName) {
    synConfirm("确定删除订单 [" + FactoryOrderNo + "," + orderName + "] 吗?",
        function () {
            $.ajax({
                url: "/FactoryOrder/Delete",
                type: 'POST',
                cache: false,
                data: { FactoryOrderNo: id },
                success: function (result) {
                    if (result.code == 0) {
                        var tr = $("#tOrder").find("tr[id='" + id + "']");

                        if (tr.find("td").eq(8).text() != "--") {
                            var deleteAmount = parseFloat(tr.find("td").eq(8).text());
                            var totalAmount = parseFloat($(".oderAmountTotal").text());
                            $(".oderAmountTotal").text(FixTwoDecimal(totalAmount - deleteAmount));
                        }

                        $("#tOrder").find("tr[id='" + id + "']").remove();
                    }
                    else if (result.code == 1) {
                        alert(result.message);
                    }
                },
                error: function (e) {
                    alert('删除失败');
                }
            });
        })
}

function EditOrder(id, model) {
    var url = {};
    url.root = "/FactoryOrder/Index";
    url.paras = [];
    if ($("#sStatus").val() != "") {
        url.paras.push({ name: "sStatus", value: $("#sStatus").val() });
    }
    if ($("#sPaymentStatus").val() != "") {
        url.paras.push({ name: "sPaymentStatus", value: $("#sPaymentStatus").val() });
    }

    if ($("#sFactoryNo").val() != "") {
        url.paras.push({ name: "sFactoryNo", value: $("#sFactoryNo").val() });
    }
    if ($("#sBeginDate").val() != "") {
        url.paras.push({ name: "sBeginDate", value: $("#sBeginDate").val() });
    }
    if ($("#sEndDate").val() != "") {
        url.paras.push({ name: "sEndDate", value: $("#sEndDate").val() });
    }
    if ($("#sKey").val() != "") {
        url.paras.push({ name: "sKey", value: $("#sKey").val() });
    }
    //if ($("#sUserId").val() != "") {
    //    url.paras.push({ name: "sUserId", value: $("#sUserId").val() });
    //}

    url.paras.push({ name: "page", value: $($(".currentnum")[0]).html() });

    if (model == "1") {
        location.href = "/FactoryOrder/Edit?FactoryOrderNo=" + id + "&GoBackURL=" + JSON.stringify(url);
    }
    else if (model == "2") {
        location.href = "/FactoryOrder/SimpleEdit?FactoryOrderNo=" + id + "&GoBackURL=" + JSON.stringify(url);
    }
}

function SetStatus(id, status) {
    $.ajax({
        url: "/FactoryOrder/SetStatus",
        type: 'POST',
        cache: false,
        dataType: 'json',
        data: { FactoryOrderNo: id, Status: status },
        success: function (result) {
            if (result.code == 0) {
                RefreshPage();
            }
            else {
                SetErrorMsg("错误：保存失败，请稍后再试");
            }
        },
        error: function (e) {
            SetErrorMsg("错误：保存失败，请稍后再试");
        }
    });
    RefreshPage();
}

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

}
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 RefreshPage() {
    var url = "/FactoryOrder?page=" + $($(".currentnum")[0]).html();

    if ($("#sStatus").val() != "") {
        url = url + "&sStatus=" + $("#sStatus").val();
    }
    if ($("#sPaymentStatus").val() != "") {
        url = url + "&sPaymentStatus=" + $("#sPaymentStatus").val();
    }

    if ($("#sFactoryNo").val() != "") {
        url = url + "&sFactoryNo=" + $("#sFactoryNo").val();
    }
    if ($("#sBeginDate").val() != "") {
        url = url + "&sBeginDate=" + $("#sBeginDate").val();
    }
    if ($("#sEndDate").val() != "") {
        url = url + "&sEndDate=" + $("#sEndDate").val();
    }
    //if ($("#sUserId").val() != "") {
    //    url = url + "&sUserId=" + $("#sUserId").val();
    //}
    if ($("#sKey").val() != "") {
        url = url + "&sKey=" + $("#sKey").val();
    }

    location.href = url;
}

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

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

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

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

function DownLoadFile(no) {
    location.href = "/FactoryOrder/DownLoadAttachment?FileNo=" + no;
}

function btnPayment() {
    ClearMessage();
    if (SelectedNumber() == 0) {

        $('.errormsg').show();
        $('.errormsg').html('请先选择一条纪录');
        return;
    }

    if (SelectedNumber() > 1) {
        $('.errormsg').html('请只选择一条纪录');
        return;
    }

    AddPayment(GetSelectedId());
}

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

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

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

    AddBatchPayment();
}




function btnPrintOrder() {
    ClearErrorMsg();
    if (SelectedNumber() == 0) {
        return SetErrorMsg('请至少选择一条纪录');
    }

    if (SelectedNumber() > 50) {
        return SetErrorMsg('最多只能选择50条纪录');
    }

    if (!CheckSingleCustomer()) {
        return SetErrorMsg('只能选择同一个外协商的订单进行打印');
    }

    window.open("/FactoryOrder/PrintOrder?FactoryOrderNos=" + GetSelectedIds(), "_blank");
}


function btnPrint(type) {
    ClearErrorMsg();
    if (SelectedNumber() == 0) {
        return SetErrorMsg('请至少选择一条纪录');
    }

    if (SelectedNumber() > 50) {
        return SetErrorMsg('最多只能选择50条纪录');
    }

    if (!CheckSingleCustomer()) {
        return SetErrorMsg('只能选择同一个外协的订单进行打印');
    }

    if (type == 1) {
        window.open("/FactoryOrder/PrintFactoryOrder?FactoryOrderNos=" + GetSelectedIds(), "_blank");
    }
    else if (type == 2) {
        location.href = "/Pdf/PrintFactoryOrderPdf?FactoryOrderNos=" + GetSelectedIds();
    }
    else if (type == 3) {
        location.href = "/FactoryOrder/PrintFactoryOrderExcel?FactoryOrderNos=" + GetSelectedIds();
    }
}

function CheckSingleCustomer() {
    var customer = "";
    var result = true;
    $("#orderList").find("input[type=checkbox]").each(function (v, val) {
        if ($(val).prop("checked")) {
            if (customer == "") {
                customer = $(val).parent().parent().find(".client-name").find("input").val();
            }
            else {
                if (customer != $(val).parent().parent().find(".client-name").find("input").val()) {
                    result = false;
                    return;
                }
            }
        }
    });

    return result;
}


function GetSelectedName() {
    var result = "";
    $("#orderList").find("input[type=checkbox]").each(function (v, val) {
        if ($(val).prop("checked")) {
            result = $(val).parent().parent().find("td:eq(3)").find("b").html();
        }
    });

    return result;
}

function btnBatchInvoice() {
   
    if (SelectedNumber() < 2) {
        return SetErrorMsg('批量开票操作需要选择多条记录');
    }

    if (!CheckSingleCustomer()) {
        return SetErrorMsg('只能选择同一个外协的订单进行批量开票');
    }
    
    synConfirm("确定将所选订单设置为 [已开票] 吗?",
        function () {
            $.blockUI({ message: '<h5>保存中，请稍候...</h5>' });
            $.ajax({
                url: "/FactoryOrder/BatchInvoiceAdd",
                type: 'POST',
                cache: false,
                data: { OrderNos: GetSelectedIds()},
                success: function (result) {
                    $.unblockUI();
                    if (result.code == 0) {                        
                        $("#tOrder").find("input[type=checkbox]").prop("checked", false);
                        alert("操作成功");
                    }
                    
                },
                error: function (e) {
                    $.unblockUI();
                    alert('操作失败，请稍后再试');
                }
            });
        })
}