var orderNo;
var allCustomer = [];

$(function () {  
    
    $("#sMaterialId").select2();
    setOperationBtns();
    setDueDay();

    $.ajax({
        url: "/Order/GetAutoCompleteCustomer",
        type: 'GET',
        cache: false,
        dataType: 'json',
        async: false,
        success: function (result) {
            for (var i in result.data) {
                allCustomer.push({ label: result.data[i].ItemText, value: result.data[i].ItemValue });
            }
        },
        error: function (e) {
        }
    });

    

    $("#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");    

    try {
        $('#txtCustomer').autocomplete({
            source: allCustomer,
            select: function (a, b, c) {
                $("#sCustomerNo").val(b.item.value);
            },
            close: function (envent, ui) {
                $('#txtCustomer').val("");
            }
        });
    }
    catch (e) {
    }

    $(".text-money").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: {
        }
    });  

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

    $("#divPayment #Discount").change(function () {      
        var discount = 0, marketAmount, amount, unPaid,paid=0;
        if ($(this).val() && !isNaN($(this).val())) {
            discount = parseFloat($(this).val());
        }
        if ($("#divPayment #Paid").html() && !isNaN($("#divPayment #Paid").html())) {
            paid = parseFloat($("#divPayment #Paid").html());
        }

        marketAmount = parseFloat($("#divPayment #MarketAmount").html());
        unPaid = FixTwoDecimal(marketAmount - discount - paid);      
        amount = FixTwoDecimal(marketAmount - discount);      
        $("#divPayment #UnPaid").html(unPaid);
        $("#divPayment #Amount").html(amount);
        
    });
});
 
function AddPayment(id,paymentType) {
    //event.stopPropagation();
    ClearErrorMsg("divPayment");
    $.ajax({
        url: "/Order/GetPaymentDetail",
        type: 'POST',
        cache: false,
        data: { OrderNo: id },
        success: function (result) {
            if (result.code == 0) {
                $("#divPayment #Amount").html(result.data.Amount);
                $("#divPayment #Paid").html(result.data.Paid);
                $("#divPayment #MarketAmount").html(result.data.MarketAmount);
                $("#divPayment #Discount").val(result.data.Discount);
                $("#divPayment #UnPaid").html(result.data.Unpaid);
                $("#divPayment #PaymentHistory").html(result.data.PaymentHistory); 

                $("#divPayment #pdPaymentStatus").removeClass("OrderStatusUnPaid");
                $("#divPayment #pdPaymentStatus").removeClass("OrderStatusPaid");
                $("#divPayment #pdPaymentStatus").addClass(result.data.Css);

                $("#divPayment #pdPaymentStatus").html(result.data.PaymentStatus);

                $("#divPayment #PaymentAmount").val("");
                $("#divPayment #PaymentMemo").val("");
                
                $("#divPayment #PaymentType").val(paymentType);

                $("#divPayment #pdBalance").text(result.data.Balance);

                orderNo = result.data.OrderNo;

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

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

function AddBatchPayment(paymentType) {
  
    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()); 
        }
    });

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

    $("#divBatchPayment #batchPaymentType").val(paymentType);
    $("#divBatchPayment #PaymentAmount").val('');
    $('#divBatchPayment').dialog('open');
} 

function DeleteOrder(id, orderNo, orderName) {
    synConfirm("确定删除订单 [" + orderNo + "," + orderName + "] 吗?",
        function () {
            $.ajax({
                url: "/Order/Delete",
                type: 'POST',
                cache: false,
                data: { OrderNumber: 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,editModel) {    
    var url = {};    
    url.root= "/Order/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 ($("#sCustomerNo").val() != "") {
        url.paras.push({ name: "sCustomerNo", value: $("#sCustomerNo").val() });
    }
    
    if ($("#sBeginDate").val() != "") {
        url.paras.push({ name: "sBeginDate", value: $("#sBeginDate").val() });
    }
    if ($("#sEndDate").val() != "") {
        url.paras.push({ name: "sEndDate", value: $("#sEndDate").val() });
    }
    if ($("#sCompletionBDate").val() != "") {
        url.paras.push({ name: "sCompletionBDate", value: $("#sCompletionBDate").val() });
    }
    if ($("#sCompletionEDate").val() != "") {
        url.paras.push({ name: "sCompletionEDate", value: $("#sCompletionEDate").val() });
    }
    if ($("#sKey").val() != "") {
        url.paras.push({ name: "sKey", value: $("#sKey").val() });
    }
    if ($("#sUserName").val() != "") {
        url.paras.push({ name: "sUserName", value: $("#sUserName").val() });
    }
    if ($("#sContact").val() != "") {
        url.paras.push({ name: "sContact", value: $("#sContact").val() });
    }   


    if ($("#sWorkFlow").val() != "") {
        url.paras.push({ name: "sWorkFlow", value: $("#sWorkFlow").val() });
    }   
    if ($("#sMaterialId").val() != "") {
        url.paras.push({ name: "sMaterialId", value: $("#sMaterialId").val() });
    }   
    if ($("#sInvoiceStatus").val() != "") {
        url.paras.push({ name: "sInvoiceStatus", value: $("#sInvoiceStatus").val() });
    }   
    if ($("#sDueDay").val() != "") {
        url.paras.push({ name: "sDueDay", value: $("#sDueDay").val() });
    }   

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

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

function savePayment() {
    $.ajax({
        url: "/Order/PaymentAdd",
        type: 'POST',
        cache: false,
        dataType: 'json',
        data: {
            OrderNo: orderNo,
            PaymentAmount: $("#PaymentAmount").val(),
            PaymentType: $("#PaymentType").val(),
            PaymentMemo: $("#PaymentMemo").val(),
            Discount: $("#Discount").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 = "/Order?page=" + $($(".currentnum")[0]).html();

    if ($("#sStatus").val() != "") {
        url = url + "&sStatus=" + $("#sStatus").val();
    }
    if ($("#sPaymentStatus").val() != "") {
        url = url + "&sPaymentStatus=" + $("#sPaymentStatus").val();
    }
    if ($("#sCustomerNo").val() != "") {
        url = url + "&sCustomerNo=" + $("#sCustomerNo").val();
    }
    
    if ($("#sBeginDate").val() != "") {
        url = url + "&sBeginDate=" + $("#sBeginDate").val();
    }
    if ($("#sEndDate").val() != "") {
        url = url + "&sEndDate=" + $("#sEndDate").val();
    }
    if ($("#sCompletionBDate").val() != "") {
        url = url + "&sCompletionBDate=" + $("#sCompletionBDate").val();
    }
    if ($("#sCompletionEDate").val() != "") {
        url = url + "&sCompletionEDate=" + $("#sCompletionEDate").val();
    }
    if ($("#sUserName").val() != "") {
        url = url + "&sUserName=" + $("#sUserName").val();
    }
    if ($("#sKey").val() != "") {
        url = url + "&sKey=" + $("#sKey").val();
    }
    if ($("#sContact").val() != "") {
        url = url + "&sContact=" + $("#sContact").val();
    }


    if ($("#sWorkFlow").val() != "") {
        url = url + "&sWorkFlow=" + $("#sWorkFlow").val();
    }
    if ($("#sMaterialId").val() != "") {
        url = url + "&sMaterialId=" + $("#sMaterialId").val();
    }
    if ($("#sInvoiceStatus").val() != "") {
        url = url + "&sInvoiceStatus=" + $("#sInvoiceStatus").val();
    }
    if ($("#sDueDay").val() != "") {
        url = url + "&sDueDay=" + $("#sDueDay").val();
    }

    location.href = url;
}

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

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

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

    if (parseFloat(payAmount) > parseFloat(unPaid)) {
        SetErrorMsg('支付金额不能大于未付金额', "divBatchPayment");
        return;
    }

    synConfirm("支付金额为 " + payAmount + " ，确定支付吗？",
        function () {
            $.blockUI({ message: '<h5>处理中...</h5>' });
            $.ajax({
                url: "/Order/BatchPaymentAdd",
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: {
                    OrderNos: GetSelectedIds(),
                    PaymentAmount: payAmount, PaymentType: $("#batchPaymentType").val(), PaymentMemo: $("#batchPaymentMemo").val()
                },
                success: function (result) {
                    $.unblockUI();

                    if (result.code == 0) {
                        $('#divBatchPayment').dialog('close');
                        RefreshPage();
                    }
                    else {
                        SetErrorMsg(result.message, "divBatchPayment");
                    }
                },
                error: function (e) {
                    $.unblockUI();
                    SetErrorMsg('批量支付失败', "divBatchPayment");
                }
            });
        });
}

function DownLoadFile(no) {
    location.href = "/Order/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(GetCustomerFirstPaymentType());
}

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

    if (!CheckSingleCustomer()) {
        return SetErrorMsg('只能选择同一个客户的订单进行批量开票');
    }
    
    synConfirm("确定将所选订单设置为 [已开票] 吗?",
        function () {
            $.blockUI({ message: '<h5>保存中，请稍候...</h5>' });
            $.ajax({
                url: "/Order/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('操作失败，请稍后再试');
                }
            });
        })
}


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

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

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

    if (type==1){
         window.open("/Order/PrintDelivery?OrderNos=" + GetSelectedIds(), "_blank");  
    }
    else if(type==2){
         location.href="/Pdf/PrintDeliveryPdf?OrderNos=" + GetSelectedIds();  
    }     
    else if (type == 3) {
        location.href="/Order/PrintDeliveryExcel?OrderNos=" + GetSelectedIds();  
    }
}

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

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

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

    $.ajax({
        url: "/Order/GetInstallationMemo",
        type: 'GET',
        cache: false,
        dataType: 'json',
        data: { OrderNos: GetSelectedIds()},
        success: function (result) {
            if (result.code == 0) {
                console.log(result);
                $('#divPrintInstallation #tdOrderNames').text(result.name);
                $('#divPrintInstallation #InstallMemo').val(result.memo);
                $('#divPrintInstallation #DeliveryAddress').val(result.deliveryAddress);
                $('#divPrintInstallation').dialog('open');
            }
            else {
                SetErrorMsg(result.message, "divPrintInstallation");
            }
        },
        error: function (e) {
            SetErrorMsg('查询安装需求失败', "divPrintInstallation");
        }
    });
}

function PrintInstallation(type) {   
    $('#divPrintInstallation').dialog('close');
    if (type == 1) {
        window.open("/Order/PrintInstallation?OrderNos=" + GetSelectedIds() + "&installMemo=" + $('#divPrintInstallation #InstallMemo').val() + "&deliveryAddress=" + $("#divPrintInstallation #DeliveryAddress").val(), "_blank");      
    }
    else if(type==2) {
        location.href = "/Pdf/PrintInstallationPdf?OrderNos=" + GetSelectedIds() + "&installMemo=" + $('#divPrintInstallation #InstallMemo').val() + "&deliveryAddress=" + $("#divPrintInstallation #DeliveryAddress").val();
    }     
    else if (type == 3) {
        location.href = "/Order/PrintInstallationExcel?OrderNos=" + GetSelectedIds() + "&installMemo=" + $('#divPrintInstallation #InstallMemo').val() + "&deliveryAddress=" + $("#divPrintInstallation #DeliveryAddress").val();      
    }
    
}

//function Print(orderNo) {
//    ClearErrorMsg();   
//    window.open("/Order/PrintDelivery?OrderNos=" + orderNo, "_blank");
//}

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

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

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

    if (type==1){
         window.open("/Order/PrintOrder?OrderNos=" + GetSelectedIds(), "_blank");  
    }
    else if (type==2){
        location.href= "/Pdf/PrintOrderPdf?OrderNos=" + GetSelectedIds();  
    }
    else if (type == 3) {
        location.href ="/Order/PrintOrderExcel?OrderNos=" + GetSelectedIds();  
    }     
}

//function PrintOrder(orderNo) {
//    ClearErrorMsg();   
//    window.open("/Order/PrintOrder?OrderNos=" + orderNo, "_blank");
//}

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 GetCustomerFirstPaymentType() {
    var result = "";
    $("#orderList").find("input[type=checkbox]").each(function (v, val) {
        if ($(val).prop("checked")) {            
            result = $(val).parent().parent().attr("data-paymenttype");
            console.log(result);
            return false;
        }
    });

    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 quickCreate(orderNo, editModel) {
    if (editModel == 1) {
        location.href = "/Order/Create?no=" + orderNo;
    }
    else {
        location.href = "/Order/SimpleCreate?no=" + orderNo;
    }
}

