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

function constructDetail() {

    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,
                Detail: d,
                DetailText: v.DetailText,
                Category: v.Category,
                CategoryName: v.CategoryName,
                ReportCategory: v.ReportCategory,
                Number: v.Number,
                Price: v.Price,
                Amount: v.Amount,
                Width: d.Width,
                Height: d.Height,
                Area: d.Area,
                Memo: v.Memo,
                MaterialId: v.MaterialId,
                PriceUnitId: v.PriceUnitId,
                Technic: v.Technic,
                TechnicText: v.TechnicText == null ? '' : v.TechnicText,
            });
        });

        generateDetailTable();
    }
}

function addOrderDetailRow(rowData) {
    if (rowData == null) {
        rowData = {
            Id: '0',
            OrderName: '',
            MaterialId: '',
            PriceUnitId: '',
            Width: '',
            Height: '',
            Amount: '',
            Number:'',
            Area: '',
            Price: '',
            DetailText: '',
            Category: '',
            CategoryName: '',
            ReportCategory: '',
            Memo: '',
            Technic: '[]',
            TechnicText: ''
        };
    }

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

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

    var hiddenId = $("<input type='hidden' id='Id'></input>").val(rowData.Id);
    var hiddenTechnic = $("<input type='hidden' id='hiddenTechnic'></input>").val(rowData.Technic);
    var hiddenFactoryPrice = $("<input type='hidden' id='hiddenFactoryPrice'></input>").val("0");
    td = $("<td></td>");
    hiddenId.appendTo(td);
    hiddenTechnic.appendTo(td);
    hiddenFactoryPrice.appendTo(td);
    td.appendTo(tr);

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

    select.val(rowData.Category);

    td = $("<td></td>");
    select.appendTo(td);    
    td.appendTo(tr);

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

    td = $("<td></td>");
    select = $("#Material").clone();
    select.attr("id", "MaterialId");
    select.addClass("select2");
    select.val(rowData.MaterialId);
    select.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='Technic' readonly='readonly' value='" + rowData.TechnicText + "'></input>");
    td = $("<td></td>");
    input.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='number'></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='Price' class='price'></input>").val(rowData.Price);
    td = $("<td></td>");
    input.appendTo(td);
    td.appendTo(tr);

    input = $("<input type='text' id='Amount' class='amount'></input>").val(rowData.Amount);
    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);

    if (rowData.Category) {
        $(orderTemplate).each(function (x, y) {
            if (y.text == rowData.Category) {
                FilterMaterialDdl(y.MaterialCategory, $(tr).find("#MaterialId"));
                return false;
            }
        });
    }

    bindEvents();
}

function CategoryChange(c) {

    $(c).parent().parent().find("#MaterialId").val("");

    var cv = $(c).val();
    var reportCategory;
    var cms = null;
    if (cv) {
        $(orderTemplate).each(function (i, v) {
            if (v.id == cv) {
                $(c).parent().parent().find("#ReportCategory").val(v.reportCategory);
                cms = v.MaterialCategory;
                return false;
            }
        });
    }
    FilterMaterialDdl(cms, $(c).parent().parent().find("#MaterialId"));
    $(c).parent().parent().find("#MaterialId").change();
}

function MaterialChange(m) {

    divSimpleTechnics.empty();
    $(m).parent().parent().find("#hiddenTechnic").val("[]");
    $(m).parent().parent().find("#Technic").val("");

    var materialId = $(m).parent().parent().find("#MaterialId").val();

    if (materialId) {

        if ($("#FactoryNo").val()) {

            $.ajax({
                url: "/FactoryOrder/GetFactoryPrice",
                type: 'GET',
                cache: false,
                data: { FactoryNo: $("#FactoryNo").val(), MaterialId: materialId },
                success: function (result) {
                    console.log(result);
                    if (result.code == 0) {
                        getFactoryLocalPrice(m, materialId, result.price);
                    }
                    else {
                        getFactoryLocalPrice(m, materialId, 0);
                    }

                },
                error: function (e) {
                    getFactoryLocalPrice(m, materialId, 0);
                }
            });
        }
        else {
            getFactoryLocalPrice(m, materialId, 0);
        }
    }
}

function getFactoryLocalPrice(m, materialId, price) {
    console.log(price);
    $(allMaterials).each(function (i, v) {

        $(v.List).each(function (x, y) {
            if (y.Id == materialId) {
                $(m).parent().parent().find("#PriceUnitId").val(y.PriceUnitId);
                $(m).parent().parent().find("#ValuationType").val(y.PriceType);

                var realPrice = price == 0 ? y.FactoryPrice : price;
                console.log(price);
                console.log(realPrice);
                $(m).parent().parent().find("#Price").val(realPrice == 0 ? "" : realPrice);

                WidthHeightChange(m);
                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;
            }
        });
    }
    else {
        $(u).parent().parent().find("#ValuationType").val("3");
    }

    SimplePriceChange($(u).parent().parent());
}

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));
        }
    }


    SimplePriceChange(row);
}

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;
    }

    var tr = trs.clone();

    var td = tr.find("td:eq(1)");
    var sel = td.find("select");
    td.empty();
    $(sel).appendTo(td);

    var td3 = tr.find("td:eq(3)");
    var sel3 = td3.find("select");
    td3.empty();
    $(sel3).appendTo(td3);

    $(tr).appendTo($("#simpleOrderTr"));

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

    bindEvents();

    calcSimpleRealAmount();
}

function deleteDetail() {

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

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

    $(trs).remove();

    calcSimpleRealAmount();
}

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

    $(orderDetails).each(function (i, v) {
        addOrderDetailRow(v);
    });
}

function bindEvents() {

    $(".price").inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });
    $(".width").inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });
    $(".amount").inputmask({ 'mask': "9{0,9}[.9{0,2}]", greedy: false }); 
    $(".number").inputmask({ 'mask': "9{0,9}[.9{0,2}]", 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 #FactoryCategoryId").unbind("change").change(function () {
        FactoryCategoryChange(this);
    });

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

    $("#simpleOrderDetail #PriceUnitId").unbind("change").change(function () {
        UnitChange(this);
    });

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

    $("#simpleOrderDetail #Price,#simpleOrderDetail #Area,#simpleOrderDetail #Price").unbind("change").change(function () {
        SimplePriceChange($(this).parent().parent());
    });

    //$("#simpleOrderDetail #Amount").unbind("change").change(function () {
    //    calcSimpleRealAmount();
    //});

    //$("#simpleOrderDetail #Amount").unbind("keyup").keyup(function () {
    //    SimpleAmountChange($(this).parent().parent());
    //});

    $("#simpleOrderDetail #Amount").unbind("change").change(function () {
        SimpleAmountChange($(this).parent().parent());
        calcSimpleRealAmount();
    });

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

    $("#simpleOrderDetail #Technic").unbind("click").click(function () {
        SetSimpleMaterialTechnics($(this));
    });

    $(".select2").select2();
}

function GetPriceUnit() {
    $.blockUI({ message: '<h5>加载中...</h5>' });
    $.ajax({
        url: "/FactoryOrder/GetJsonFactoryPriceUnit?factoryOrderNo=" + $("#FactoryOrderNo").val(),
        type: 'GET',
        cache: false,
        dataType: 'json',
        async: false,
        success: function (result) {
            $.unblockUI();
            allUnits = result.priceUnits;

            allMaterials = result.materials;
            FillMaterialDdl(allMaterials);
        },
        error: function (e) {
            $.unblockUI();
        }
    });
}

function InitialTemplateCategoryDropDown() {
    orderTemplate = eval($("#OrderTemplate").val());
    $("<option value=''>&nbsp;</option>").appendTo($("#Category"));
    for (var i in orderTemplate) {
        $("#Category").append("<option value=\"" + orderTemplate[i].id + "\">" + orderTemplate[i].text + "</option>");
    }
}

$(function () {

    divSimpleTechnics = $("#divPopTechnic .divTechnics");

    $(".select2").select2();

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

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

    GetPriceUnit();
    InitialTemplateCategoryDropDown();
    constructDetail();
    generateDetailTable();

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

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

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

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

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

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

    $("#btnFile").click(function () {
        $("#fileSelect").click();
    });

    $("#tipFileName").click(function () {
        $('#divFileNameTip').dialog('open');
    });

    var fileElement = document.getElementById('fileSelect');
    fileElement.addEventListener('change', function () {
        if (this.files.length == 0) {
            return;
        }

        var t_files = this.files;

        for (var i = 0, len = t_files.length; i < len; i++) {
            addDetailByFileName(t_files[i].name);
        }

    }, false);

    if (isOrderAdd) {
        $("#trPrePaid").css("display", '');
        $("#trWorkFlow").css("display", '');
    }

    $(".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 });
    $(".price").inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });


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


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

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

    $('#FactoryNo').change(function () {

        if ($('#FactoryNo').val() != "") {


            $.ajax({
                url: "/FactoryOrder/GetFactoryContact",
                type: 'POST',
                cache: false,
                data: { FactoryNo: $('#FactoryNo').val() },
                success: function (result) {
                    if (result.code == 0) {
                        $("#Contact").val(result.data);
                    }
                    else {

                    }
                },
                error: function (e) {

                }
            });
        }
    });

    $('#btnCancelCustomer').click(function () {
        $('#divCustomer').dialog('close');
    });


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

    $("#btnSearch").click(function () {
        searchOrder();
    });

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

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

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

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

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


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

        $.ajax({
            url: "/Customer/AddFactory",
            type: 'POST',
            cache: false,
            data: { FactoryName: $("#FactoryName").val() },
            success: function (result) {
                if (result.code == 0) {

                    $('#divFactory').dialog('close');

                    $("<option value='" + result.data + "'>" + $("#FactoryName").val() + "</option>").appendTo($("#FactoryNo"));

                    $("#FactoryNo").val(result.data);

                }
                else {
                    SetErrorMsg(result.message, "divFactory");
                }
            },
            error: function (e) {
                SetErrorMsg("添加外协商失败，可能是您的权限不足", "divFactory");
            }
        });

    });

    $("#btnSaveRelation").click(function () {
        saveRelation();
    });

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

        ClearErrorMsg();

        if ($("#FactoryNo").val() == "") {
            $("#FactoryNo").addClass("redBorder");
            return SetErrorMsg('请选择外协商');
        }

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

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

        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("#Amount").val()) {
                $(v).find("#Amount").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;
                }
            }
            else if (unit == "4") {
                if (!$(v).find("#Width").val() || !$(v).find("#Height").val() || !$(v).find("#Number").val()) {
                    $(v).find("#Width").addClass("redBorder");
                    $(v).find("#Height").addClass("redBorder");
                    $(v).find("#Number").addClass("redBorder");
                    SetErrorMsg("计价方式为周长时，必须填写宽度，高度和数量");
                    checkResult = false;
                    return false;
                }
            }

        });

        if (!checkResult) {
            return;
        }

        var orderDetails = GetOrderDetails();


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

        if (isOrderAdd) {

            $.ajax({
                url: "/FactoryOrder/SimpleAdd",
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: { BasicInfo: GetBasicInfo(), orderDetails: JSON.stringify(orderDetails), relations: getRelationOrderNos() },
                success: function (result) {
                    $.unblockUI();
                    if (result.code == 0) {
                        location.href = "/FactoryOrder/Index";
                    }
                    else if (result.code == 1) {
                        SetErrorMsg(result.message);
                    }
                    else if (result.code == 9) {
                        location.href = "/MySpace/Index";
                    }
                    else {
                        return SetErrorMsg_Save_Failed();
                    }
                },
                error: function (e) {
                    $.unblockUI();
                    return SetErrorMsg_Save_Failed();
                }
            });

        }
        else {
            var additonMessage = "";

            $.ajax({
                url: "/FactoryOrder/SimpleUpdate",
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: { BasicInfo: GetBasicInfo(), orderDetails: JSON.stringify(orderDetails), relations: getRelationOrderNos() },
                success: function (result) {
                    $.unblockUI();
                    if (result.code == 0) {
                        if ($("#BackURL").val() == "") {
                            location.href = '/FactoryOrder/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();
                }
            });
        }
    });


    $('#Category').change(function () {
        CategoryChange();
    });

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

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

    $("#MarketAmount").keyup(function () { calcSimpleRealAmount(); }).blur(function () { calcSimpleRealAmount(); }).change(function () { calcSimpleRealAmount(); });
    $("#Discount").keyup(function () { calcSimpleRealAmount(); }).blur(function () { calcSimpleRealAmount(); }).change(function () { calcSimpleRealAmount(); });
    $("#FeeInstallation,#FeeDelivery,#FeeDesign,#FeeOther").keyup(function () { calcSimpleRealAmount(); }).blur(function () { calcSimpleRealAmount(); }).change(function () { calcSimpleRealAmount(); });


    // tabs    
    $(".nav-tabs a").click(function () {
        $(".tab-pane").hide();
        $(".nav-tabs li").removeClass("active");
        $(this).parent().addClass("active");
        var id = "#tab_" + $(this).attr("id").replace("a", "");

        $(id).show();
    });

    resetSearchResult();

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

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

        var d = {
            Id: $(v).find("#Id").val(),
            OrderName: $(v).find("#OrderName").val(),
            Detail: JSON.stringify(GetDetailObject(v)),
            DetailText: GetDetailText(v),
            Number: $(v).find("#Number").val(),
            Price: $(v).find("#Price").val(),
            Amount: $(v).find("#Amount").val(),
            Category: $(v).find("#CategoryId").val(),
            ReportCategory: $(v).find("#ReportCategory").val(),
            MaterialId: $(v).find("#MaterialId").val(),
            PriceUnitId: $(v).find("#PriceUnitId").val(),
            Memo: $(v).find("#Memo").val(),
            Technic: $(v).find("#hiddenTechnic").val(),
            TechnicText: $(v).find("#Technic").val()
        };

        formatOrderDetailObj(d);
        result.push(d);

    });

    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 GetBasicInfo() {
    var result = {};
    result.FactoryOrderNo = $("#FactoryOrderNo").val();
    //result.OrderName = $("#OrderName").val();
    result.FactoryNo = $("#FactoryNo").val();
    result.Contact = $("#Contact").val();
    result.TransactionDate = $("#TransactionDate").val();
    result.MarketAmount = $("#MarketAmount").val();

    result.FeeInstallation = $("#FeeInstallation").val();
    result.FeeDelivery = $("#FeeDelivery").val();
    result.FeeDesign = $("#FeeDesign").val();
    result.FeeOther = $("#FeeOther").val();

    result.Discount = $("#Discount").val();
    result.RealAmount = $("#RealAmount").val();
    result.ExpectDeliveryDate = $("#ExpectDeliveryDate").val();
    result.Memo = $("TextArea[id='Memo']").val();
    result.TemplateId = $("#TemplateId").val();
    result.TemplateNo = $("#TemplateNo").val();
    result.IsInvoiced = $("#IsInvoiced").prop("checked");
    result.WidthUnit = $("#WidthUnit").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 newFactory() {
    ClearErrorMsg();
    $("#FactoryName").val("");
    $('#divFactory').dialog('open');
}

function addRelation() {
    resetSearchResult();
    $('#divRelation input[type=checkbox]').prop("checked", false);
    $("#tbodySearch").empty();
    $("#txtKey").val("");
    $('#divRelation').dialog('open');
}

function resetSearchResult() {
    $("#chart-no-data").hide();
    $(".nav-tabs li:first-child a").click();
}

function saveRelation() {

    ClearErrorMsg("divRelation");

    var orders = [];
    var order;
    var chks = $("#divRelation input[type=checkbox]");
    chks.each(function (i, v) {
        if ($(this).prop("checked")) {
            order = {};
            order.OrderNo = $(this).parent().parent().find("td:eq(1)").html();
            order.CustomerName = $(this).parent().parent().find("td:eq(2)").html();
            order.OrderName = $(this).parent().parent().find("td:eq(3)").html();

            orders.push(order);
        }
    });

    console.log(orders);

    if (orders.length == 0) {
        return SetErrorMsg("请至少选中一个客户订单", "divRelation");
    }

    var tbodyRelation = $("#tbodyRelation");

    var tr;
    var td;

    $(orders).each(function (i, v) {
        if (tbodyRelation.find("td[id='" + v.OrderNo + "']").length == 0) {

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

            td = $("<td></td>");
            td.attr("id", v.OrderNo).html(v.OrderNo).appendTo(tr);

            $("<td></td>").html(v.CustomerName).appendTo(tr);
            $("<td></td>").html(v.OrderName).appendTo(tr);

            $("<td><a href= 'javascript:void(0);' style= 'text-decoration:underline;' onclick= 'javascript:deleteRelation(this)' >取消关联</a ></td >").appendTo(tr);

            tr.appendTo(tbodyRelation);
        }

    });

    $('#divRelation').dialog('close');
}

function getRelationOrderNos() {

    var orderNos = [];

    var nos = $("#tbodyRelation tr").each(function (i, v) {
        orderNos.push($(v).find("td:eq(0)").text());
    });



    return orderNos.join(",");
}

function deleteRelation(v) {
    $(v).parent().parent().remove();
}

function searchOrder() {
    $("#chart-no-data").hide();

    $("#txtKey").removeClass("redBorder")

    if ($("#txtKey").val() == "") {
        $("#txtKey").addClass("redBorder");
        return;
    }

    $.ajax({
        url: "/FactoryOrder/SearchOrder",
        type: 'POST',
        cache: false,
        dataType: 'json',
        async: false,
        data: { keywords: $("#txtKey").val() },
        success: function (result) {
            if (result.code == 0) {
                var tbody = $("#tbodySearch");
                tbody.empty();

                var tr;
                var td;

                if (result.data.length == 0) {
                    $("#chart-no-data").show();
                }
                for (var r in result.data) {

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

                    td = $("<td><input type='checkbox' /></td>");

                    td.appendTo(tr);

                    td = $("<td></td>");
                    td.html(result.data[r].OrderNo);
                    td.appendTo(tr);

                    td = $("<td></td>");
                    td.html(result.data[r].CustomerName);
                    td.appendTo(tr);

                    td = $("<td></td>");
                    td.html(result.data[r].OrderName);
                    td.appendTo(tr);

                    tr.appendTo(tbody);
                }

            }
            else {
            }
        },
        error: function (e) {
        }
    });
}

function FillMaterialDdl(data) {
    var selMaterial = $("#Material");
    $("<option value=''>&nbsp;</option>").appendTo(selMaterial);
    var optGroup, opt;
    $(data).each(function (i, v) {

        optGroup = $("<optgroup></optgroup>").attr("data-id", v.Id);
        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);

    });
}

function getLocalPrice(m, materialId, Price) {

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

        $(v.List).each(function (x, y) {
            if (y.Id == materialId) {
                console.log(y);
                $(m).parent().parent().find("#PriceUnitId").val(y.PriceUnitId);
                $(m).parent().parent().find("#ValuationType").val(y.PriceType);

                if (Price) {
                    $(m).parent().parent().find("#Price").val(Price);
                }
                else if (y.FactoryPrice) {
                    $(m).parent().parent().find("#Price").val(y.FactoryPrice);
                }



                WidthHeightChange(m);
                return false;
            }
        });

    });
}

function SetSimpleMaterialTechnics(input) {

    currentSimpleRow = $(input).parent().parent();

    divSimpleTechnics.empty();
    $("#divPopTechnicNoData").hide();
    $("#divPopTechnic #btnSaveTechnic").show();

    var materialId = currentSimpleRow.find("#MaterialId").val();

    if (!materialId) {
        alert("请先选择材料");
        return;
    }

    $.ajax({
        url: "/FactoryOrder/GetMaterialTechnicsWithFPrice",
        type: 'GET',
        cache: false,
        data: { MaterialId: materialId, FactoryNo: $("#FactoryNo").val() },
        success: function (result) {
            if (result.code == 0) {

                divSimpleTechnics.empty();

                $(result.technics).each(function (i, v) {
                    CreateSimpleTechnicDiv(v).appendTo(divSimpleTechnics);
                });

                var selecteTechnics = $(currentSimpleRow).find("#hiddenTechnic").val();
                selecteTechnics = selecteTechnics ? selecteTechnics : '[]';
                $(JSON.parse(selecteTechnics)).each(function (i, v) {
                    var tc = $(divSimpleTechnics).find("div[data-id='" + v.TechnicId + "']");
                    if (tc.length == 0) {
                        CreateSimpleTechnicDiv(v).appendTo(divSimpleTechnics);
                    }
                    else {
                        tc.addClass("selected");
                    }
                });

                if (result.fPrice) {
                    $(currentSimpleRow).find("#hiddenFactoryPrice").val(result.fPrice);
                }
                else {
                    $(currentSimpleRow).find("#hiddenFactoryPrice").val(getFactoryPriceFromLocal(materialId));
                }

                if (divSimpleTechnics.find("div").length == 0) {
                    $("#divPopTechnicNoData").show();
                    $("#divPopTechnic #btnSaveTechnic").hide();
                }

                $("#divPopTechnic").dialog("open");
            }
        },
        error: function (e) {
        }
    });
}

function getFactoryPriceFromLocal(materialId) {
    var price = 0;
    $(allMaterials).each(function (i, v) {

        $(v.List).each(function (x, y) {
            if (y.Id == materialId) {
                price = y.FactoryPrice;
                return false;
            }
        });
    });

    return price;
}

function SaveSimpleTechnics() {
    currentSimpleRow.find("#hiddenTechnic").val(JSON.stringify(GetSimpleSelectedTechnics()));
    currentSimpleRow.find("#Technic").val(GetSimpleSelectedTechnicsText());

    setSimplePrice(currentSimpleRow.find("#Technic"));

    $("#divPopTechnic").dialog("close");
}

function GetTotalFactoryTechnicPrice(m) {
    var totalTechnicPrice = 0;
    var selecteTechnics = $(m).parent().parent().find("#hiddenTechnic").val();

    $(JSON.parse(selecteTechnics)).each(function (i, v) {
        totalTechnicPrice += parseFloat(v.FactoryPrice);
    });

    return totalTechnicPrice;
}

function GetSimpleSelectedTechnics() {

    var selectedTechnics = [];
    $(divSimpleTechnics.find("div")).each(function (i, v) {
        if ($(v).hasClass("selected")) {
            selectedTechnics.push({
                TechnicId: $(v).attr("data-id"),
                Name: $(v).attr("data-name"),
                SailPrice: $(v).attr("data-sprice"),
                FactoryPrice: $(v).attr("data-fprice"),
            });
        }
    });

    return selectedTechnics;
}

function GetSimpleSelectedTechnicsText() {

    var selectedTechnics = [];
    $(divSimpleTechnics.find("div")).each(function (i, v) {
        if ($(v).hasClass("selected")) {
            selectedTechnics.push($(v).attr("data-name"));
        }
    });

    return selectedTechnics.join(", ");
}

function CreateSimpleTechnicDiv(v) {
    var div = $("<div></div>").attr("title", "外协价: " + v.FactoryPrice).attr("data-id", v.TechnicId).attr("data-sprice", v.SailPrice).attr("data-fprice", v.FactoryPrice).attr("data-name", v.Name).html(v.Name).click(function () {
        if ($(this).hasClass("selected")) {
            $(this).removeClass("selected");
        }
        else {
            $(this).addClass("selected");
        }
    });

    return div;
}

function setSimplePrice(m) {

    var tr = $(m).parent().parent();

    var technicFactoryPrice = GetTotalFactoryTechnicPrice(m);
    var totalFactoryPrice = parseFloat(tr.find("#hiddenFactoryPrice").val()) + technicFactoryPrice;
    tr.find("#Price").val(totalFactoryPrice == 0 ? "" : totalFactoryPrice);

    WidthHeightChange(m);
}