var allMaterial = [];
var stockInDetails = [];

function constructDetail() {

    if ($("#StockInDetails").val()) {
        var oDetails = eval($("#StockInDetails").val());

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

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

        generateDetailTable();
    }
}

function addStockInDetailRow(rowData) {

    if (rowData == null) {
        rowData = {
            Id: '0',
            MaterialId: '',
            Price: '',
            Number: '',
            Amount: '',
            Amount: '',
            Memo: '',
            UnitName: '' 
        };
    }

    var tBody = $("#simpleStockInTr");
    var tr, td, input, select, hidden;

    tr = $("<tr></tr>");

    $("<td><input type='hidden' id='Id' value='" + rowData.Id + "'></input></td>").appendTo(tr);

    select = $("#Material").clone();
    select.attr("id", "MaterialId");
    
    select.val(rowData.MaterialId);
    td = $("<td></td>");
    select.appendTo(td);    
    
    td.appendTo(tr);    

    
    td = $("<td id='UnitName' class='text-center'></td>");
    td.html(rowData.UnitName);
   
    td.appendTo(tr); 

    input = $("<input type='text' id='Number' class='number' value='" + rowData.Number + "'></input>");
    td = $("<td></td>");
    input.appendTo(td);
    td.appendTo(tr); 

    input = $("<input type='text' id='Price' class='price' value='" + rowData.Price + "'></input>");
    td = $("<td></td>");
    input.appendTo(td);
    td.appendTo(tr);

    input = $("<input type='text' id='Amount' class='price' value='" + rowData.Amount + "'></input>");
    td = $("<td></td>");
    input.appendTo(td);
    td.appendTo(tr);

    input = $("<input type='text' id='Memo' value='" + rowData.Memo + "'></input>");
    td = $("<td></td>");
    input.appendTo(td);
    td.appendTo(tr);
 

    tr.appendTo(tBody);

    bindEvents();
}

function MaterialChange(m) {

    var materialId = $(m).val();
    
    if (materialId) {
        $(allMaterial).each(function (i, v) {
            if (v.Id == materialId) {
                $(m).parent().parent().find("#UnitName").html(v.UnitName);
                return false;
            }
        });
    }    
} 

function PriceChange(v) {

    var price, number, amount, width, area, valuationType;

    price = $(v).find("#Price").val();
    number = $(v).find("#Number").val();
 
  
    amount = "";


    if (number && !isNaN(number)) {
        if (price && !isNaN(price)) {
          
           
                amount = FixTwoDecimal(parseFloat(price) * parseFloat(number));
            

        }

        $(v).find("#Amount").val(amount);
    }



    calcRealAmount();
} 

function copyDetail() {
    var trs = $("#simpleStockInTr .tr-selected");
    if ($(trs).length == 0) {
        alert("请先选择要复制的行");
        return;
    }


    var tr = trs.clone();
    var td = tr.find("td:eq(1)");
    var sel = td.find("select");
    console.log(sel);
    td.empty();
    $(sel).appendTo(td);
    $(tr).appendTo($("#simpleStockInTr"));

 

    $($("#simpleStockInTr tr").last()).attr("id", "0");
    $($("#simpleStockInTr tr").last()).removeClass("tr-selected");

    bindEvents();

    calcRealAmount();
}

function deleteDetail() {

    if ($("#simpleStockInTr tr").length == 1) {
        alert("订单至少必须包含一个明细，无法删除。");
        return;
    }

    var trs = $("#simpleStockInTr .tr-selected");
    if ($(trs).length == 0) {
        alert("请先选择要删除的行");
        return;
    }

    $(trs).remove();

    calcRealAmount();
}

function generateDetailTable() {
    var tBody = $("#simpleStockInTr");
    tBody.empty();

    $(stockInDetails).each(function (i, v) {
        addStockInDetailRow(v);
    });
}

function bindEvents() {

    $("#MaterialId").change(function () {
        //
    });
    

    $(".amount").inputmask({ 'mask': "9{0,9}[.9{0,2}]", greedy: false });
    $(".number").inputmask({ 'mask': "9{0,9}[.9{0,2}]", greedy: false });
    $(".price").inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });

    // select a row
    $("#simpleStockInDetail td").unbind("click").click(function () {
        $("#simpleStockInDetail .tr-selected").removeClass("tr-selected");
        $(this).parent().addClass("tr-selected");
    });   

    $("#simpleStockInDetail #MaterialId").unbind("change").change(function () {
        MaterialChange(this);        
    });  

    $("#simpleStockInDetail #MaterialId").select2();

    $("#simpleStockInDetail #Price,#simpleStockInDetail #Number").unbind("change").change(function () {
        PriceChange($(this).parent().parent());
    });

    $("#simpleStockInDetail #Amount").unbind("change").change(function () {
        calcRealAmount();
    });

    // when the column is narrow,it is usefual to show the tip
    $("#simpleStockInDetail #Memo").hover(function () {
        $(this).attr("title", $(this).val());
    });
}

function GetMaterialAndUnit() {

    $.blockUI({ message: '<h5>加载中...</h5>' });

    $.ajax({
        url: "/Warehouse/GetGroupedMaterial?stockInId=" + $("#stock #Id").val(),
        type: 'GET',
        cache: false,
        dataType: 'json',
        async: false,
        success: function (result) {
            console.log(result.data);
            var selMaterial = $("#Material");
            $("<option value=''>&nbsp;</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);

                    allMaterial.push({ Id: v.Id,UnitName:v.UnitName});
                });

                optGroup.appendTo(selMaterial);

            });
            $.unblockUI();            
        },
        error: function (e) {
            $.unblockUI();
        }
    });
}
 
$(function () {

    $("#simpleStockInDetail").resizableColumns({
        store: window.store
    });

    GetMaterialAndUnit();    
    constructDetail();
    generateDetailTable();
 
    $(".number,.amount,.price").each(function () {

        if ($(this).val() == "0") {
            $(this).val("");
        }
    });

    $('#btnNewDetail').click(function () {
        addStockInDetailRow(null);
    });

    $('#btnCopyDetail').click(function () {
        copyDetail(null);
    });

    $('#btnDeleteDetail').click(function () {
        deleteDetail();
    });

    if ($("#stock #Id").val()=="0") {
        $("#trPrePaid").css("display", '');       
    }

    $(".text-date").attr("readonly", "readonly");
    $(".text-date").datepicker({ dateFormat: 'yy-mm-dd' });  
    
   
    $('#divSupplier').dialog({
        width: 500,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    }); 


    $('#btnCancel').click(function () {

        synConfirm("确定要放弃修改吗？", function () {
            window.history.go(-1);
        });
    });


    $('#btnSaveSupplier').click(function () {
        if (checkRequired('divSupplier', 'errorMessage') == false) {
            return;
        }

        $.ajax({
            url: "/Warehouse/SaveSupplier",
            type: 'POST',
            cache: false,
            data: { Id: 0, Name: $("#SupplierName").val()},
            success: function (result) {
                if (result.code == 0) {
                    if (result.code == 0) {
                        $('#divSupplier').dialog('close');
                        $("<option value='" + result.data + "'>" + $("#SupplierName").val() + "</option>").appendTo($("#SupplierId"));
                        $("#SupplierId").val(result.data);
                    }
                    else {
                        SetErrorMsg(result.message, "divSupplier");
                    }
                }
                else {
                    SetErrorMsg(result.message, "divSupplier");
                }
            },
            error: function (e) {
                SetErrorMsg("保存失败");
            }
        });

    });
   

    $('#btnSave').click(function () {

        ClearErrorMsg();

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

        var tbody = $("#simpleStockInTr tr");

        if (tbody.length < 1) {
            return SetErrorMsg('至少应该包含1个明细');
        }

       

        if ($("#PrePaid").val() && !isNaN($("#PrePaid").val())) {
            if (!$("#PrePaidPaymentType").val()) {
                $("#PrePaidPaymentType").addClass("redBorder");
                return SetErrorMsg_Required();
            }
        }

        var checkResult = true;
        tbody.each(function (i, v) {
            if (!$(v).find("#MaterialId").val()) {
                $(v).find("#MaterialId").addClass("redBorder");
                checkResult = false;
            } 
 

            if (!$(v).find("#Amount").val()) {
                $(v).find("#Amount").addClass("redBorder");
                checkResult = false;
            }

            if (!$(v).find("#Number").val()) {
                $(v).find("#Number").addClass("redBorder");
                checkResult = false;
            }

            if (!$(v).find("#Price").val()) {
                $(v).find("#Price").addClass("redBorder");
                checkResult = false;
            }
        });

        if (!checkResult) {
            return SetErrorMsg_Required();
        } 

        var stockInDetails = GetStockInDetails();


        $.blockUI({ message: '<h5>保存中，请稍候...</h5>' });

        if ($("#stock #Id").val()=="0") {

            $.ajax({
                url: "/Warehouse/StockInAdd",
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: { BasicInfo: GetBasicInfo(), stockInDetails: JSON.stringify(stockInDetails) },
                success: function (result) {
                    $.unblockUI();
                    if (result.code == 0) {
                        if ($("#BackURL").val()) {
                            location.href = $("#BackURL").val();
                        }
                        else {
                            location.href = "/Warehouse/StockIn";
                        }                        
                    }
                    else if (result.code == 1) {
                        SetErrorMsg(result.message);
                    }                    
                    else {
                        return SetErrorMsg_Save_Failed();
                    }
                },
                error: function (e) {
                    $.unblockUI();
                    return SetErrorMsg_Save_Failed();
                }
            });

        }
        else {
            var additonMessage = "";

            $.ajax({
                url: "/Warehouse/StockInUpdate",
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: { BasicInfo: GetBasicInfo(), stockInDetails: JSON.stringify(stockInDetails) },
                success: function (result) {
                    $.unblockUI();
                    if (result.code == 0) {
                        if ($("#BackURL").val()) {
                            location.href = $("#BackURL").val();
                        }
                        else {
                            location.href = "/Warehouse/StockIn";
                        }      
                    }
                    else if (result.code == 1) {
                        SetErrorMsg(result.message);
                    }
                    else {
                        return SetErrorMsg_Save_Failed();
                    }
                },
                error: function (e) {
                    $.unblockUI();
                    return SetErrorMsg_Save_Failed();
                }
            });
        }
    });

    $('#divMaterial #btnSaveMaterial').click(function () {    

        SaveQuickMaterial();
    });

    $('#Supplier').change(function () {
        MaterialChange();
    });

    $("#Price").keyup(function () {
        PriceChange();
    }).blur(function () {
        PriceChange();
    }).change(function () {
        PriceChange();
    });

    $("#Number").keyup(function () {
        PriceChange();
    }).blur(function () {
        PriceChange();
    }).change(function () {
        PriceChange();
    });

    $("#MarketAmount").keyup(function () { calcRealAmount(); }).blur(function () { calcRealAmount(); }).change(function () { calcRealAmount(); });
    $("#Discount").keyup(function () { calcRealAmount(); }).blur(function () { calcRealAmount(); }).change(function () { calcRealAmount(); });
 
    if ($("#stock #Id").val()=="0" && $("#simpleStockInTr tr").length < 1) {         
        addStockInDetailRow(null);
    }


    $('#divMaterial #Id').val("0");
});

function GetStockInDetails() {
    var result = [];
    $("#simpleStockInTr tr").each(function (i, v) {

        result.push({
            Id: $(v).find("#Id").val(),
            MaterialId: $(v).find("#MaterialId").val(),          
            Number: $(v).find("#Number").val(),
            Price: $(v).find("#Price").val(),
            Amount: $(v).find("#Amount").val(),          
            Memo: $(v).find("#Memo").val(),
        });

    });

    return result;
}
 
function GetBasicInfo() {
    var result = {};
    result.Id = $("#stock #Id").val();    
    result.SupplierId = $("#SupplierId").val();
    result.Type = $("#Type").val();
    result.StockInTime = $("#StockInTime").val();
    result.MarketAmount = $("#MarketAmount").val();
    result.Discount = $("#Discount").val();
    result.RealAmount = $("#RealAmount").val();
    result.Operator = $("#Operator").val();
    result.Memo = $("TextArea[id='Memo']").val();   

    if ($("#PrePaid").val() && !isNaN($("#PrePaid").val())) {
        result.PrePaid = $("#PrePaid").val();
        result.PrePaidPaymentType = $("#PrePaidPaymentType").val();
        result.PrePaidMemo = $("#PrePaidMemo").val();
    }

    return JSON.stringify(result);
}

function newId() {
    var guid = "g";
    for (var i = 1; i <= 32; i++) {
        var n = Math.floor(Math.random() * 16.0).toString(16);
        guid += n;
        if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
            guid += "";
    }
    return guid;
}

function calcRealAmount() {

    var marketAmount = 0, rowAmount;

    $("#simpleStockInTr tr").each(function (i, v) {
        rowAmount = $(v).find("#Amount").val();
        if (rowAmount && !isNaN(rowAmount)) {
            marketAmount += parseFloat(rowAmount);
        }
    });

    $("#MarketAmount").val(marketAmount);

    if ($("#Discount").val() && !isNaN($("#Discount").val())) {

        if ($("#MarketAmount").val() && !isNaN($("#MarketAmount").val())) {
            $("#RealAmount").val(FixTwoDecimal(parseFloat($("#MarketAmount").val()) - parseFloat($("#Discount").val())));
        }
        else {
            $("#RealAmount").val("");
        }
    }
    else {
        $("#RealAmount").val($("#MarketAmount").val());
    }
}

function newSupplier() {
    $("#SupplierName").val("");
    $('#divSupplier').dialog('open');
}
 