$(function () {

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

    console.log($('#divMaterial').length);
    if ($('#divMaterial').length > 0) {
        $('#divMaterial').dialog({
            width: 600,
            autoOpen: false,
            modal: true,
            buttons: {
            }
        });

        $('#btnNewMaterial').click(function () {
            clearMaterialForm();
            $("#IsActive").prop("checked", "true");
            $("#ForStock").change();
            showMaterial();
        });


        $("#ForStock").change(function () {
            if ($(this).prop("checked")) {
                $("#trRMaterial").hide();
                $("#trSaftyStock").show();
            }
            else {
                $("#trRMaterial").show();
                $("#trSaftyStock").hide();
            }
        });
    }
});

function ShowStockInDetail(id) {
    ClearErrorMsg();
    $("#Id").val(id);
    $.ajax({
        url: "/Warehouse/GetStockInDetail",
        type: 'POST',
        cache: false,
        data: { Id: id },
        success: function (result) {
            if (result.code == 0) {
                $("#dStatus").html(result.data.StatusDescription);
                $("#dType").html(result.data.TypeDescription);
                $("#dPaymentStatus").html(result.data.PaymentStatusDescription);

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

                $("#dSN").html(result.data.SN);

                $("#dSupplierName").html(result.data.SupplierName);

                $("#dMarketAmount").html(result.data.MarketAmount);
                $("#dDiscount").html(result.data.Discount);
                $("#dPaid").html(result.data.Paid);
                $("#dAmount").html(result.data.Amount);

                $("#dCreatedTime").html(result.data.CreatedTimeString);
                $("#dStockInTime").html(result.data.StockInTimeString);
                $("#dCreator").html(result.data.Creator);
                $("#dOperator").html(result.data.Operator);

                $("#dMemo").html(result.data.Memo);

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

                var stockInDetails = [];

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

                    eval("var d=" + v.Detail + ";");
                    stockInDetails.push({
                        Id: v.Id,
                        MaterialName: v.MaterialName,
                        UnitName: v.UnitName,
                        Number: v.Number,
                        Price: v.Price,
                        Amount: v.Amount,
                        Memo: v.Memo
                    });
                });

                FillStockInDetailInfo(stockInDetails);

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

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

function FillStockInDetailInfo(stockInDetails) {

    var tBody = $("#tableDetail");
    tBody.empty();

    var tr, td, a;
    console.log(stockInDetails);
    $(stockInDetails).each(function (i, v) {
        tr = $("<tr></tr>");
        td = $("<td>" + v.MaterialName + "</td>");
        td.appendTo(tr);

        td = $("<td>" + v.UnitName + "</td>");
        td.appendTo(tr);

        td = $("<td>" + v.Number + "</td>");
        td.appendTo(tr);

        td = $("<td>" + v.Price + "</td>");
        td.appendTo(tr);

        td = $("<td>" + v.Amount + "</td>");
        td.appendTo(tr);

        td = $("<td>" + v.Memo + "</td>");
        td.appendTo(tr);

        tr.appendTo(tBody);
    });
}

function ShowStockOutDetail(id) {
    ClearErrorMsg();
    $("#Id").val(id);
    $.ajax({
        url: "/Warehouse/GetStockOutDetail",
        type: 'POST',
        cache: false,
        data: { Id: id },
        success: function (result) {
            if (result.code == 0) {
                $("#dStatus").html(result.data.StatusDescription);
                $("#dType").html(result.data.TypeDescription);



                $("#dSN").html(result.data.SN);



                $("#dCreatedTime").html(result.data.CreatedTimeString);
                $("#dStockOutTime").html(result.data.StockOutTimeString);
                $("#dCreator").html(result.data.Creator);
                $("#dOperator").html(result.data.Operator);

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

                var stockOutDetails = [];

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

                    eval("var d=" + v.Detail + ";");
                    stockOutDetails.push({
                        Id: v.Id,
                        MaterialName: v.MaterialName,
                        UnitName: v.UnitName,
                        Number: v.Number,
                        Memo: v.Memo
                    });
                });

                FillStockOutDetailInfo(stockOutDetails);


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

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

function FillStockOutDetailInfo(stockOutDetails) {

    var tBody = $("#tableDetail");
    tBody.empty();

    var tr, td, a;

    $(stockOutDetails).each(function (i, v) {
        tr = $("<tr></tr>");
        td = $("<td>" + v.MaterialName + "</td>");
        td.appendTo(tr);

        td = $("<td>" + v.UnitName + "</td>");
        td.appendTo(tr);

        td = $("<td>" + v.Number + "</td>");
        td.appendTo(tr);

        td = $("<td>" + v.Memo + "</td>");
        td.appendTo(tr);

        tr.appendTo(tBody);
    });
}

function GetGroupedMaterial(ddlElementId, ddlValue) {

    $.blockUI({ message: '<h5>加载中...</h5>' });
    var selMaterial = $("#" + ddlElementId);

    $.ajax({
        url: "/Warehouse/GetGroupedMaterial",
        type: 'GET',
        cache: false,
        dataType: 'json',
        async: false,
        success: function (result) {
            console.log(result.data);

            $("<option value=''>请选择材料</option>").appendTo(selMaterial);
            var optGroup, opt;
            $(result.data).each(function (i, v) {

                optGroup = $("<optgroup label='排序'></optgroup>");
                optGroup.attr("label", v.Name);

                $(v.List).each(function (i, v) {
                    opt = $("<option></option>");
                    opt.text(v.Name);
                    opt.attr("value", v.Id);
                    opt.appendTo(optGroup);
                });

                optGroup.appendTo(selMaterial);

            });

            if (ddlValue) {
                selMaterial.val(ddlValue);
            }
            $.unblockUI();
        },
        error: function (e) {
            $.unblockUI();
        }
    });
}

function clearMaterialForm() {
    ClearErrorMsg();
    $("#divMaterial input").removeClass("redBorder");
    $("#divMaterial input[type=text]").val("");
    $("#divMaterial textarea").val("");
    $("#divMaterial input[type=checkbox]").prop("checked", true);
    $("#divMaterial #Id").val("");
}

function showMaterial() {
    $('#divMaterial').dialog('open');
}

function closeMaterial() {
    $('#divMaterial').dialog('close');
}


function GetFormMaterialObject() {
    return {
        Id: $("#divMaterial #Id").val(),
        Name: $("#divMaterial #Name").val(),
        CategoryId: $("#divMaterial #CategoryId").val(),
        CostPrice: $("#divMaterial #CostPrice").val(),
        SailPrice: $("#divMaterial #SailPrice").val(),
        FactoryPrice: $("#divMaterial #FactoryPrice").val(),
        PriceUnitId: $("#divMaterial #PriceUnitId").val(),
        ForStock: $("#divMaterial #ForStock").prop("checked"),
        ForOrder: $("#divMaterial #ForOrder").prop("checked"),
        StockMaterialId: $("#divMaterial #StockMaterialId").val(),
        SafetyStock: $("#divMaterial #SafetyStock").val(),
        Memo: $("#divMaterial #Memo").val(),
        IsActive: $("#divMaterial #IsActive").prop("checked")
    }
}

function SaveQuickMaterial() {

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

    synConfirm("确定保存吗？", function () {
        $.ajax({
            url: "/Warehouse/SaveMaterial",
            type: 'POST',
            cache: false,
            data: GetFormMaterialObject(),
            success: function (result) {
                if (result.code == 0) {
                    closeMaterial();
                    if (result.id > 0) {
                        if (result.forOrder) {
                            var opt = $("<option></option>");

                            opt.text(result.name);
                            opt.attr("value", result.id);

                            opt.insertAfter($("#Material").find("option:first"));

                            var ddls;
                            if ($("#simpleStockInTr").length > 0) {
                                ddls = $("#simpleStockInTr tr");
                            }
                            else {
                                ddls = $("#simpleStockOutTr tr");
                            }

                            if (allMaterial!=null && allMaterial!=undefined) {
                                allMaterial.push({ Id: result.id, UnitName: result.unitName });
                            }
                            

                            $(ddls).each(function (i, v) {

                                var ddl = $(v).find("#MaterialId");
                                var opt1 = opt.clone();
                                opt1.insertAfter($(ddl).find("option:first"));
                                if ($(ddl).val() == "") {
                                    $(ddl).val(result.id).trigger("change");
                                }
                            });
                        }
                    }
                }
                else {
                    SetErrorMsg(result.message, "divMaterial");
                }
            },
            error: function (e) {
                SetErrorMsg("保存失败", "divMaterial");
            }
        })
    });
}