var orderTemplate = {}; 
var isOrderAdd = true;
var orderDetails = []; 
var allUnits = []; 
var widthUnit = "m";

$(function () {

    widthUnit = $("#WidthUnit").val();

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

    if ($("#OrderNo").val() != "") {
        isOrderAdd = false;
    }

    $(".number,.amount,.price").each(function () {

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

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

    $.ajax({
        url: "/Portal/GetJsonPriceUnit",
        type: 'GET',
        cache: false,
        dataType: 'json',
        async: false,
        success: function (result) {
            $.unblockUI();
            
            allUnits = result.data;          
 
        },
        error: function (e) {
            $.unblockUI();
        }
    });

    constructDetail();

    generateDetailTable();

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

    $(".text-date").attr("readonly", "readonly");
    $(".text-date").datepicker({ dateFormat: 'yy-mm-dd' });

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


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

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

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

    $('#ContactNo').change(function () {
        if ($('#ContactNo').val() != "") {
            $("#Contact").val($("#ContactNo").find("option:selected").text());
        }
    });
 
 
 
    $('#btnCancel').click(function () {

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

    });

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

        ClearErrorMsg();
 

        var tbody = $("#simpleOrderTr tr");
        if (tbody.length < 1) {
            return SetErrorMsg('至少应该包含1个明细');
        }

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

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

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

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

         
        });

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

        checkResult = true;
        tbody.each(function (i, v) {

            var unit = $(v).find("#ValuationType").val();
            if (unit == "1") {
                if (!$(v).find("#Area").val()) {
                    $(v).find("#Area").addClass("redBorder");
                    SetErrorMsg("计价方式为面积计价时，必须填写面积");
                    checkResult = false;
                    return false;
                }
            }
            else if (unit == "2") {
                if (!$(v).find("#Width").val()) {
                    $(v).find("#Width").addClass("redBorder");
                    SetErrorMsg("计价方式为长度时，必须填写宽度");
                    checkResult = false;
                    return false;
                }
            }

            if ($(v).find("#FactoryPrice").val() || $(v).find("#FactoryAmount").val() || $(v).find("#FactoryCategoryId").val()) {
                if (!$(v).find("#FactoryNo").val()) {
                    $(v).find("#FactoryNo").addClass("redBorder");
                    SetErrorMsg("请选择外协商。如果无需外协请不要填写外协类别，单价和金额。");
                    checkResult = false;
                    return false;
                }
            }
        });

        if (!checkResult) {
            return;
        }
 

        orderDetails = GetOrderDetails();
         

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

        if (isOrderAdd) {

            $.ajax({
                url: "/Portal/SimpleAdd",
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: { BasicInfo: GetBasicInfo(), orderDetails: JSON.stringify(orderDetails) },
                success: function (result) {
                    $.unblockUI();
                    if (result.code == 0) {
                        location.href = "/Portal/Index";
                    }
                    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: "/Portal/SimpleUpdate",
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: { BasicInfo: GetBasicInfo(), orderDetails: JSON.stringify(orderDetails) },
                success: function (result) {
                    $.unblockUI();
                    if (result.code == 0) {
                        if ($("#BackURL").val() == "") {
                            location.href = '/Portal/Index';
                        }
                        else {
                            location.href = $("#BackURL").val();
                        }
                    }
                    else if (result.code == 1) {
                        SetErrorMsg(result.message);
                    }
                    else {
                        return SetErrorMsg_Save_Failed();
                    }
                },
                error: function (e) {
                    $.unblockUI();
                    return SetErrorMsg_Save_Failed();
                }
            });
        }
    });


    if (!$("#OrderNo").val() && $("#simpleOrderTr tr").length < 1) {
        addOrderDetailRow(null);
    }

}); 

function constructDetail() {

    orderTemplate = eval($("#OrderTemplate").val());  
    factoryOrderTemplate = eval($("#FactoryOrderTemplate").val());  

    if ($("#OrderDetails").val() != null) {
        var oDetails = eval($("#OrderDetails").val()); 
        
        $(oDetails).each(function (i, v) {         
            eval("var d=" + v.Detail+";"); 
            orderDetails.push({
                Id: v.Id,
                OrderName:v.OrderName,               
                DetailText:v.DetailText,
                Category:v.Category,              
                ReportCategory:v.ReportCategory,
                Number: v.Number,              
                PriceUnitId: v.PriceUnitId,
                Width: d.Width,
                Height: d.Height,
                Area: d.Area,
                Memo:v.Memo
            });
        });        
    }
   
    InitialCategoryDropdown();
}

function bindEvents() {    
    $(".width").inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });

    // select a row
    $("#simpleOrderDetail td").unbind("click").click(function () {      
        $("#simpleOrderDetail .tr-selected").removeClass("tr-selected");
        $(this).parent().addClass("tr-selected");
    });
 
    $("#simpleOrderDetail #CategoryId").unbind("change").change(function () {
        CategoryChange(this);
    });
    
    $("#simpleOrderDetail #PriceUnitId").unbind("change").change(function () {
        UnitChange(this);
     });

    $("#simpleOrderDetail #Width,#simpleOrderDetail #Height,#simpleOrderDetail #Number").unbind("change").change(function () {
        WidthHeightChange(this);
    });  

    // when the column is narrow,it is usefual to show the tip
    $("#simpleOrderDetail #OrderName,#simpleOrderDetail #Memo").hover(function () {        
        $(this).attr("title", $(this).val());
    });
    $("#simpleOrderDetail #MaterialId").hover(function () {
        if ($(this).val() != "") {
            $(this).attr("title", $(this).find("option:selected").text());
        }
        else {
            $(this).removeAttr("title");
        }
       
    });
}
 
function GetOrderDetails() {
    var result = [];
    $("#simpleOrderTr tr").each(function (i, v) {        
         
            result.push({
                Id: $(v).find("#Id").val(),
                OrderName: $(v).find("#OrderName").val(),
                Detail: JSON.stringify(GetDetailObject(v)),
                DetailText: GetDetailText(v),
                Number: $(v).find("#Number").val(),             
                Category: $(v).find("#CategoryId").val(),
                ReportCategory: $(v).find("#ReportCategory").val(),                
                PriceUnitId: $(v).find("#PriceUnitId").val(),
                Memo: $(v).find("#Memo").val(),
            });
         
    });

    return result;
}

function GetDetailObject(tr) {
    var result = {};
    result.Width = $(tr).find("#Width").val();
    result.Height = $(tr).find("#Height").val();
    result.Area = $(tr).find("#Area").val();   
    result.PriceUnitId = $(tr).find("#PriceUnitId").val();

    return result;
}

function GetDetailText(tr) {
    var result="";
    var obj = GetDetailObject(tr);
    if (obj.Width) {
        result += "高: " + obj.Width + widthUnit + ", ";
    }
    if (obj.Height) {
        result += "宽: " + obj.Height + widthUnit + ", ";
    }
    if (obj.Area) {
        result += "面积: " + obj.Area + "㎡, ";
    }

    if (result.length > 0) {
        result = result.substr(0, result.length - 2);
    }    

    return result;
}

function InitialCategoryDropdown() {
    $("<option value=''>&nbsp;</option>").appendTo($("#Category"));

    for (var i in orderTemplate) {
        $("#Category").append("<option value=\"" + orderTemplate[i].id + "\">" + orderTemplate[i].text + "</option>");
    }  

    $("<option value=''>&nbsp;</option>").appendTo($("#FactoryCategory"));    
}

function CategoryChange(c) {
    
    var cv = $(c).val();
    
    if (cv) {
        var guid;
        $(orderTemplate).each(function (i, v) {
            if (v.id == cv) {              
                $(c).parent().parent().find("#ReportCategory").val(v.reportCategory);   
                return false;
            }
        });       
    }
}


 
function UnitChange(u){
    var unitId = $(u).val();    
    if (unitId){
           $(allUnits).each(function (i, v) {
                if (v.ItemValue == unitId) {                   
                    $(u).parent().parent().find("#ValuationType").val(v.Addition1);                   
                    return false;
                }
            });
    }
}


function WidthHeightChange(input){
    var row = $(input).parent().parent();
 
    var width = parseFloat( row.find("#Width").val());
    var height = parseFloat(row.find("#Height").val());
    var valuationType = row.find("#ValuationType").val();
    var number = parseFloat(row.find("#Number").val()); 
    
    if (valuationType == "1" && !isNaN(width) && !isNaN(height) && !isNaN(number)) {  
        if (widthUnit == "m") {
            row.find("#Area").val(changeFourDecimal(width * height * number));
        }
        else if (widthUnit == "cm") {
            row.find("#Area").val(changeFourDecimal(width * height * number/10000.0));
        }    
        else if (widthUnit == "mm") {
            row.find("#Area").val(changeFourDecimal(width * height * number / 1000000.0));
        } 
    } 
 
}
 

function GetBasicInfo() {
    var result = {};
    result.OrderNo = $("#OrderNo").val();   
    result.CustomerNo = $("#CustomerNo").val();
    result.ContactNo = $("#ContactNo").val();
    result.Contact = $("#Contact").val();
    result.TransactionDate = $("#TransactionDate").val();   
    result.DeliveryType = $("#DeliveryType").val(),
    result.DeliveryAddress = $("#DeliveryAddress").val();     
  
    result.Memo = $("TextArea[id='Memo']").val();     
    result.TemplateNo = $("#TemplateNo").val();
    result.IsInvoiced = $("#IsInvoiced").prop("checked");
    result.WidthUnit = $("#WidthUnit").val();
  
    return JSON.stringify(result);
}
 

function addOrderDetailRow(rowData) {

    if (rowData == null) {
        rowData = {
            Id:'0',
            OrderName: '',          
            PriceUnitId:'',
            Width:'',
            Height:'',         
            Number:'',
            Area:'',         
            DetailText:'',           
            Memo:''           
        };
    }

    var tBody = $("#simpleOrderTr");
    var tr,td, input, select,hidden;
    var inputStock;
    tr = $("<tr></tr>");

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

    select = $("#Category").clone();
    select.attr("id", "CategoryId");    

    select.val(rowData.Category);    
    
    td = $("<td></td>");
    select.appendTo(td);
    $("<input type='hidden' id='ReportCategory'></input>").appendTo(td);
    td.appendTo(tr);

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

    td = $("<td></td>");
    hidden=$("<input type='hidden' id='ValuationType' />");
   
    select = $("<select id='PriceUnitId'></select>");

    $("<option value=''>&nbsp;</option>").appendTo(select);
    $(allUnits).each(function (i, v) {
        if (v.ItemValue == rowData.PriceUnitId) {
            $("<option selected value='" + v.ItemValue + "'>" + v.ItemText + "</option>").appendTo(select);            
            hidden.val(findValuationTypeByUnit(rowData.PriceUnitId));
        }
        else {
            $("<option value='" + v.ItemValue + "'>" + v.ItemText + "</option>").appendTo(select);
        }        
    });
    hidden.appendTo(td);
    select.appendTo(td);
    td.appendTo(tr);

    input = $("<input type='text' id='Width' class='width'></input>").val(rowData.Width);
    td = $("<td></td>");
    input.appendTo(td);
    td.appendTo(tr);

    input = $("<input type='text' id='Height' class='width'></input>").val(rowData.Height);
    td = $("<td></td>");
    input.appendTo(td);
    td.appendTo(tr);

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

    input = $("<input type='text' id='Area' class='width'></input>").val(rowData.Area);
    td = $("<td></td>");
    input.appendTo(td);
    td.appendTo(tr);

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

    bindEvents();
}

function findValuationTypeByUnit(unit) {
    var result;
   
    $(allUnits).each(function (i, v) {     
        if (v.ItemValue == unit) {
            result = v.Addition1;
            return false;
        }
    });

    return result;
}

function copyDetail() {
    var trs = $("#simpleOrderTr .tr-selected");

    if ($(trs).length == 0) {
        alert("请先选择要复制的行");
        return;
    }
    
    $(trs.clone()).appendTo($("#simpleOrderTr"));

    $($("#simpleOrderTr tr").last()).find("#Id").val("0");
    $($("#simpleOrderTr tr").last()).removeClass("tr-selected");
       
    bindEvents();
    
    calcRealAmount(); 
}

function deleteDetail() {

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

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

    $(trs).remove();

    calcRealAmount();
}
 
function generateDetailTable() {
    var tBody = $("#simpleOrderTr");
    tBody.empty();
 
    $(orderDetails).each(function (i, v) {
        addOrderDetailRow(v);
    });
}
