var inUploading = false;
$(function () {   

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

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


    $("#btnUpload").click(function () {
        ajaxFileUpload();
    });

    $("#btnOrderMemo").click(function () {
        $('#errorMessageMemo').html('');
        $('#OrderMemo').removeClass('redBorder');
        if (checkRequired('MemoPanel', 'errorMessageMemo') == false) {
            return;
        }
       
            $.ajax({
                url: "/FactoryOrder/AddOrderMemo",
                type: 'POST',
                cache: false,
                dataType: 'json',
                async: false,
                data: { FactoryOrderNo: $("#FactoryOrderNo").val(), Memo: $("#OrderMemo").val() },
                success: function (result) {
                    if (result.code == 0) {
                        $("#OrderMemo").val("");
                        $("<tr><td>" + result.data.Addition1 + "</td><td>" + result.data.Addition2 + "</td><td>" + result.data.Addition3 + "</td></tr>").appendTo($("#dOrderMemo"));
                    }
                    else {
                        SetErrorMsg("保存失败", "divDetail");
                    }
                },
                error: function (e) {
                    SetErrorMsg("保存失败", "divDetail");
                }
            });
       
    }); 
});

function ShowDetail(id) {
    ClearErrorMsg();
    $("#FactoryOrderNo").val(id);
    $.ajax({
        url: "/FactoryOrder/GetDetail",
        type: 'POST',
        cache: false,
        data: { FactoryOrderNo: id },
        success: function (result) {
            if (result.code == 0) {
                $("#dStatus").html(result.data.StatusDescription);

                $("#dPaymentStatus").html(result.data.PaymentStatusDescription);                  
 
                $("#dPayment").html(result.data.Payment);

                $("#dFactoryOrderNo").html(result.data.FactoryOrderNo);
                $("#dOrderName").html(result.data.OrderName);
                $("#dFactoryName").html(result.data.FactoryName);
                $("#dContact").html(result.data.Contact);

                if (result.data.Amount == 0) {
                    result.data.MarketAmount = "--";
                    result.data.Discount = "--";
                    result.data.Paid = "--";
                    result.data.Amount = "--";

                    $(result.data.FactoryOrderDetails).each(function (i, v) {
                        v.Price = "--";
                        v.Amount = "--";
                    });
                }

                $("#dIsInvoiced").html(result.data.IsInvoiced ? "已开票" : "未开票");   

                $("#dMarketAmount").html(result.data.MarketAmount);

                $("#dFeeDesign").html(result.data.FeeDesign);
                $("#dFeeDelivery").html(result.data.FeeDelivery);
                $("#dFeeInstallation").html(result.data.FeeInstallation);
                $("#dFeeOther").html(result.data.FeeOther);

                $("#dDiscount").html(result.data.Discount);
                $("#dPaid").html(result.data.Paid);
                $("#dAmount").html(result.data.Amount);
                $("#dCreatedTime").html(result.data.CreatedTimeString);
                $("#dTransactionDate").html(result.data.TransactionDateString);
                $("#dCreator").html(result.data.Creator);
                //FillOrderDetailInfo(eval(result.data.OrderTemplate), result.data.Category);
                SetDetailDetail(eval("(" + result.data.Detail + ")"));
                $("#dNumber").html(result.data.Number);
                $("#dExpectDeliveryDate").html(result.data.ExpectDeliveryDateString);
              
                $("#dMemo").html(result.data.Memo);
                $("#dDeliveryType").html(result.data.DeliveryType);
                $("#dDeliveryAddress").html(result.data.DeliveryAddress);               

                var table = $("#tableOrder");
                table.empty();

                $("#dHistory").html("");
          
                    $("#dHistory").html(result.data.History);

                    console.log(result.data);
                    if (result.data.Orders.length > 0) {
                        $('<thead><tr class="title"><th style="width:160px">客户订单号</th><th style="width:160px">客户</th></th><th>详细</th></tr></thead>').appendTo(table);
                    }

                    $.each(result.data.Orders, function () {
                        var tr = $("<tr></tr>");
                        $("<td><a target='_blank' href='/Order/OrderDetailInfo?orderNo=" + this.OrderNo + "'>" + this.OrderNo + "</a></td>").appendTo(tr);
                        $("<td>" + this.CustomerShortName + "</td>").appendTo(tr);
                        $("<td>" + this.OrderName + "</td>").appendTo(tr);                      
                        tr.appendTo(table);
                    });
                         

                $("#dQueryURL").html("");
                var a = $("<a target='_blank' href='" + result.data.QueryURL + "'>" + result.data.QueryURL + "</a>").appendTo($("#dQueryURL"));
                $("#dOrderMemo").html("");
                for (var r in result.data.OrderMemos) {
                    $("<tr><td>" + result.data.OrderMemos[r].Addition1 + "</td><td>" + result.data.OrderMemos[r].Addition2 + "</td><td>" + result.data.OrderMemos[r].Addition3 + "</td></tr>").appendTo($("#dOrderMemo"));
                }
                var t = $("#tdAttachment");
                t.html("");
                for (var r in result.data.Attachments) {
                    console.log(r);
                    if (result.data.Attachments[r].Addition3 != null && result.data.Attachments[r].Addition3 != "") {
                        var a = $("<a class='order-detail-thumbnail' target='_blank'></a>");
                        a.css("background-image", 'url(' + result.data.Attachments[r].Addition3.split("|")[0] + ')');
                        a.attr("href", result.data.Attachments[r].Addition3.split("|")[1]);
                        a.attr("title", result.data.Attachments[r].ItemText);
                        a.appendTo(t);
                    }
                }

                for (var r in result.data.Attachments) {                    
                    var a = $("<div><img src='" + result.data.Attachments[r].Addition1 + "' alt=''/><a href='#' style='text-decoration:underline;' onclick=\"javascript:return DownLoadFile('" + result.data.Attachments[r].ItemValue + "');\">" + result.data.Attachments[r].ItemText + "</a> (" + result.data.Attachments[r].Addition4 + " " + result.data.Attachments[r].Addition2 + ")</div>");
                    a.appendTo(t);
                }


                var orderDetails = [];

                $(result.data.FactoryOrderDetails).each(function (i, v) {

                    eval("var d=" + v.Detail + ";");
                    orderDetails.push({
                        Id: v.Id,
                        OrderName: v.OrderName,
                        Detail: d,
                        DetailText: v.DetailText,
                        Category: v.Category,
                        CategoryName: v.CategoryName,
                        ReportCategory: v.ReportCategory,
                        Number: v.Number,
                        Price: v.Price,
                        Amount: v.Amount,
                        MaterialName: v.MaterialName,
                        UnitName: v.UnitName,
                        Memo: v.Memo
                    });
                });

                FillFactoryOrderDetailInfo(orderDetails);

                SetDetailDetail(eval("(" + result.data.Detail + ")"));

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

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


function ajaxFileUpload() {
    ClearErrorMsg();   

    if ($("#fileToUpload").val() == "") {
        SetErrorMsg("请选择上传文件", "divAttachment");        
        return;
    }

    var point = $("#fileToUpload").val().lastIndexOf(".");
    var type = $("#fileToUpload").val().substr(point).toLowerCase();

    if (type == ".exe" || type == ".bat" || type == ".msi") {
        SetErrorMsg("文件类型不允许", "divAttachment");         
        return;
    }
    $("#loading").show();

    $.ajaxFileUpload({
        url: '/FactoryOrder/FileUpload',
        secureuri: false,
        fileElementId: 'fileToUpload',
        data: { FactoryOrderNo: $("#FactoryOrderNo").val() },
        dataType: 'json',
        success: function (d, status) {
            var data = JSON.parse(d);
            data = data.Data;            
            if (data.code == "1") {
                $("#divAttachment input").removeAttr("disabled");
                inUploading = false;
                SetErrorMsg(data.message, "divAttachment");  
                $("#loading").hide();
            }
            else if (data.code == "0") {
                $("#divAttachment input").removeAttr("disabled");
                inUploading = false;
                $("#loading").hide();
                alert("上传成功！");                 
                $('#divAttachment').dialog('close');
            }
        },
        error: function (data, status, e) {           
            $("#divAttachment input").removeAttr("disabled");
            inUploading = false;
            SetErrorMsg("上传时发生错误", "divAttachment"); 
            $("#loading").hide();
        }
    });

    $("#divAttachment input").attr("disabled", "disabled");
    inUploading = true;
    return false;
}
 
function ShowAttachment(FactoryOrderNo) {
    ClearErrorMsg();
    $("#FactoryOrderNo").val(FactoryOrderNo);

    $.ajax({
        url: "/FactoryOrder/GetOrderAttachments",
        type: 'GET',
        cache: false,
        data: { FactoryOrderNo: $("#FactoryOrderNo").val() },
        success: function (result) {
            if (result.code == 0) {
                $("#dAttachment").html("");

                if (result.data.length > 0) {
                    for (var r in result.data) {
                        var tr = $("<tr id='" + result.data[r].ItemValue + "'></tr>");
                        var td = $("<td style='text-align: center;'></td>");
                        var image = $("<img src='" + result.data[r].Addition1 + "' alt=''>");
                        image.appendTo(td);
                        td.appendTo(tr);
                        td = $("<td></td>");
                        td.html(result.data[r].ItemText);
                        td.appendTo(tr);
                        td = $("<td></td>");
                        td.html(result.data[r].Addition3 + " MB");
                        td.appendTo(tr);
                        td = $("<td></td>");
                        td.html(result.data[r].Addition2);
                        td.appendTo(tr);
                        td = $("<td></td>");
                        var tno = result.data[r].ItemValue;
                        var t = $("<a href='#' onclick=\"javascript:return DownLoadFile('" + tno + "');\">下载</a>");
                        t.appendTo(td);

                        t = $("<a href='#' style='margin-left:5px;' onclick=\"javascript:return DeleteFile('" + tno + "','" + result.data[r].ItemText + "');\">删除</a>");

                        t.appendTo(td);
                        td.appendTo(tr);

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

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

function DeleteFile(no, name) {
    ClearErrorMsg();

    if (inUploading) {
        return false;
    }

    synConfirm('确定删除附件 ' + name + ' 吗？', function () {
        $.ajax({
            url: "/FactoryOrder/DeleteAttachment",
            type: 'GET',
            cache: false,
            data: { FileNo: no, FactoryOrderNo: $("#FactoryOrderNo").val() },
            success: function (result) {
                if (result.code == 0) {
                    $("#tAttachment").find("tr[id=" + result.FileNo + "]").remove();
                }
                else {
                    alert("删除失败.");
                }

            },
            error: function (e) {
                alert("删除失败.");
            }
        });
    }); 
}

function DownLoadFile(no) {
    ClearErrorMsg();

    if (inUploading) {
        return false;
    }

    location.href = "/FactoryOrder/DownLoadAttachment?FileNo=" + no;
}

