var orderTemplate = {};
var isOrderAdd = true;
var orderDetails = [];
var allUnits = [];
var allMaterials = [];
var divTechnics = 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,
                MaterialId: v.MaterialId,
                DetailText: v.DetailText,
                Category: v.Category,
                CategoryName: v.CategoryName,
                ReportCategory: v.ReportCategory,
                Number: v.Number,
                Price: v.Price,
                Amount: v.Amount,
                Memo: v.Memo,
                MaterialName: FindMaterialName(v.MaterialId),
                PriceUnitId: v.PriceUnitId,
                Technic: v.Technic,
                TechnicText: v.TechnicText == null ? '' : v.TechnicText,
                Guid: newId()
            });
        });

        generateDetailTable();
    }
}

function getAllPriceUnit() {
    $.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 () {


    divTechnics = $("#popOrderDetail #divTechnics")

    getAllPriceUnit();
    constructDetail();
    generateDetailTable();

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

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

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

    $("#Category").append("<option value=''>请选择业务类型</option>");
    for (var i in orderTemplate) {
        $("#Category").append("<option value=\"" + orderTemplate[i].id + "\">" + orderTemplate[i].text + "</option>");
    }

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

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

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


    $('#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: {
        }
    });

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

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

    $('#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) {

                }
            });
        }
    });
    $('#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");
            }
        });

    });

    $("#popOrderDetail #MaterialId").change(function () {

        var materialId = $(this).val();

        if (materialId) {
            $.ajax({
                url: "/FactoryOrder/GetFactoryPrice",
                type: 'GET',
                cache: false,
                data: { FactoryNo: $('#FactoryNo').val(), MaterialId: materialId },
                success: function (result) {
                    if (result.code == 0) {
                        getLocalPrice(materialId, result.price);
                        SetPopTechnics(result.technics);
                    }
                },
                error: function (e) {
                    getLocalPrice(materialId, 0);
                }
            });
        }
        else {
            divTechnics.empty();
        }
    });


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

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

        ClearErrorMsg();

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

        if (orderDetails.length == 0) {
            return SetErrorMsg("请至少添加一个订单明细。")
        }

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

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



        // deep colone array and its element,
        // slice can not works here, since elements of the array is object too.
        //var orderDetailsClone = orderDetails.slice();
        var orderDetailsClone = JSON.parse(JSON.stringify(orderDetails));

        $(orderDetailsClone).each(function (i, v) {
            v.Detail = JSON.stringify(v.Detail);
        });

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

        if (isOrderAdd) {

            $.ajax({
                url: "/FactoryOrder/Add",
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: { BasicInfo: GetBasicInfo(), orderDetails: JSON.stringify(orderDetailsClone), 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/Update",
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: { BasicInfo: GetBasicInfo(), orderDetails: JSON.stringify(orderDetailsClone), 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();
        $("#popOrderDetail #MaterialId").val("");
        $("#popOrderDetail #MaterialId").change();
        resetPriceFactor();
    });

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

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

    $("#popOrderDetail #Amount").keyup(function () {
        PopUpAmountChange();
    }).blur(function () {
        PopUpAmountChange();
    });

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


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

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 = $("#Memo").val();
    result.TemplateId = $("#TemplateId").val();
    result.TemplateNo = $("#TemplateNo").val();
    result.IsInvoiced = $("#IsInvoiced").prop("checked");

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

    return JSON.stringify(result);
}

function GetDetailDetail() {
    var result = {};

    var guid = $("#Guid").val();
    result.Guid = guid == "" ? newId() : guid;
    result.Id = $("#Id").val() == "" ? "0" : $("#Id").val();
    result.OrderName = $("#OrderName").val();
    result.Category = $("#Category").val();
    result.ReportCategory = $("#ReportCategory").val();
    result.Number = $("#popOrderDetailC #Number").val();
    result.Price = $("#popOrderDetailC #Price").val();
    result.Amount = $("#popOrderDetailC #Amount").val();
    result.Memo = $("#popOrderDetailC #Memo").val();
    result.MaterialId = $("#popOrderDetailC #MaterialId").val();
    result.MaterialName = $("#popOrderDetail #MaterialId").find("option:selected").text();
    result.PriceUnitId = $("#popOrderDetailC #PriceUnitId").val();
    result.Detail = {};
    result.Technic = JSON.stringify(GetPopSelectedTechnics());
    result.TechnicText = GetPopSelectedTechnicsText();

    var id;
    $("#tableDetail").find("input[id^='f']").each(function (i, t) {
        id = t.id.replace(/\(/g, "");
        id = id.replace(/\)/g, "");
        console.log("result.Detail['" + t.id + "']='" + $(t).val() + "';");
        eval("result.Detail['" + t.id + "']='" + $(t).val() + "';");
    });
    $("#tableDetail").find("textarea[id^='f']").each(function (i, t) {
        id = t.id.replace(/\(/g, "");
        id = id.replace(/\)/g, "");
        console.log("result.Detail['" + t.id + "']='" + $(t).val() + "';");
        eval("result.Detail['" + t.id + "']='" + $(t).val() + "';");
    });
    $("#tableDetail").find("select[id^='f']").each(function (i, t) {
        id = t.id.replace(/\(/g, "");
        id = id.replace(/\)/g, "");
        eval("result.Detail['" + t.id + "']='" + $(t).val() + "';");
    });

    result.DetailText = GetDetailDetailText();
    formatOrderDetailObj(result);

    return result;
}

function GetDetailDetailText() {
    var result = "";
    $("#tableDetail").find("input[id^='f'],select[id^='f'],textarea[id^='f']").each(function (i, t) {
        if ($(t).val() != '') {
            result = result + $(t).parent().prev().html() + ": " + $(t).val() + ", ";
        }
    });
    if (result.length > 2) {
        result = result.substr(0, result.length - 2);
    }
    return result;
}

function CategoryChange() {
    var table = $("#tableDetail");
    table.find("tr").remove();

    var k = 0;
    var tr;
    var td;
    var cms = null;
    for (var i in orderTemplate) {
        if (orderTemplate[i].id == $('#Category').val()) {
            $('#divPriceTip').find("#divPriceText").html("");
            if (orderTemplate[i].priceTip != undefined) {
                $('#divPriceTip').find("#divPriceText").html(orderTemplate[i].priceTip.replace(/\n/g, '<br>'));
            }

            if ($.trim($('#divPriceTip').find("#divPriceText").html()) == "") {
                $('#divPriceTip').find("#divPriceText").html("没有发现价格信息!<br/>请在“系统管理->外协模板”中进行设置。");
            }

            $("#ReportCategory").val(orderTemplate[i].reportCategory);

            for (var j = 0; j < orderTemplate[i].fields.length; j++) {
                k = k + 1;
                if (k % 3 == 1) {
                    tr = $("<tr></tr>")
                }

                td = $("<td class='label'>" + orderTemplate[i].fields[j].label + "</td>");

                td.appendTo(tr);

                td = $("<td class='value'></td>");
                var fieldId = "f" + orderTemplate[i].id + orderTemplate[i].fields[j].id;

                fieldId = fieldId.replace(/\(/g, "");
                fieldId = fieldId.replace(/\)/g, "");

                if (orderTemplate[i].fields[j].type == 1) {
                    var textbox = $("<input type='text' id='" + fieldId + "' />");
                    if (orderTemplate[i].fields[j].formular != undefined
                        && orderTemplate[i].fields[j].formular != "") {
                        //textbox.attr("readonly", "readonly");
                        textbox.addClass("formular");
                        textbox.inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });
                    }
                    if (orderTemplate[i].fields[j].isPriceFactor != undefined
                        && orderTemplate[i].fields[j].isPriceFactor) {
                        textbox.addClass("isPriceFactor");
                        textbox.inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });
                    }

                    textbox.appendTo(td);

                }
                else if (orderTemplate[i].fields[j].type == 2) {
                    // dropdown list
                    var ddl = $("<select id='" + fieldId + "'></select>");
                    for (var s in orderTemplate[i].fields[j].options) {
                        ddl.append("<option value=\"" + orderTemplate[i].fields[j].options[s] + "\">" + orderTemplate[i].fields[j].options[s] + "</option>");
                    }
                    if (orderTemplate[i].fields[j].isPriceFactor != undefined
                        && orderTemplate[i].fields[j].isPriceFactor) {
                        ddl.addClass("isPriceFactor");
                    }
                    ddl.appendTo(td);
                }
                else if (orderTemplate[i].fields[j].type == 3) {
                    var textbox = $("<textarea id='" + fieldId + "'></textarea>");
                    if (orderTemplate[i].fields[j].formular != undefined
                        && orderTemplate[i].fields[j].formular != "") {
                        //textbox.attr("readonly", "readonly");
                        textbox.addClass("formular");
                        textbox.inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });
                    }
                    if (orderTemplate[i].fields[j].isPriceFactor != undefined
                        && orderTemplate[i].fields[j].isPriceFactor) {
                        textbox.addClass("isPriceFactor");
                        textbox.inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });
                    }

                    textbox.appendTo(td);

                    td.attr("colspan", "5");
                    k = k + 2;
                }

                if (orderTemplate[i].fields[j].isRequired) {
                    $("<span class='redStar'> *</span>").appendTo(td);
                }
                td.appendTo(tr);

                if (j < orderTemplate[i].fields.length - 1 && orderTemplate[i].fields[j + 1].type == 3) {
                    // the next is memo
                    if (k % 3 == 1) {
                        td.attr("colspan", "5");
                        k = k + 2;
                    }
                    else if (k % 3 == 2) {
                        td.attr("colspan", "3");
                        k = k + 1;
                    }

                }

                if (k % 3 == 0) {
                    tr.appendTo(table);
                }
            }

            if (k % 3 == 1) {
                td.attr("colspan", "5");
                tr.appendTo(table);
            }
            else if (k % 3 == 2) {
                td.attr("colspan", "3");
                tr.appendTo(table);
            }

            cms = orderTemplate[i].MaterialCategory;

            break;
        }
    }

    FilterMaterialDdl(cms, $("#popOrderDetail #MaterialId"));

    $("#tableDetail").find(".formular").each(function (i, e) {
        for (var i in orderTemplate) {
            if (orderTemplate[i].id == $('#Category').val()) {

                for (var j in orderTemplate[i].fields) {
                    var fieldId = FormatFieldsName("f" + orderTemplate[i].id + orderTemplate[i].fields[j].id);

                    if (fieldId == $(this).attr("id")) {
                        var formular = orderTemplate[i].fields[j].formular;
                        var fieldPrefix = FormatFieldsName("#f" + orderTemplate[i].id);

                        var condiateFields = formular.replace(/\+/g, "*").replace(/\-/g, "*").replace(/\//g, "*").replace(/\(/g, "*").replace(/\)/g, "*")
                            .replace(/\=/g, "*").replace(/\?/g, "*").replace(/\:/g, "*").replace(/\"/g, "*").replace(/\'/g, "*")
                            .replace(/\>/g, "*").replace(/\</g, "*").replace(/\!/g, "*").split("*");


                        var fields = [];

                        $(condiateFields).each(function (vv, v) {
                            $(orderTemplate[i].fields).each(function (x, y) {
                                if (v == y.id) {
                                    fields.push(v);
                                }
                            });
                        });

                        for (var s in fields) {
                            fields[s] = fields[s].replace(/\(/g, "");
                            fields[s] = fields[s].replace(/\)/g, "");

                            if ($(fieldPrefix + fields[s])[0].type != 'select-one') {
                                $(fieldPrefix + fields[s]).inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });
                            }

                            $(fieldPrefix + fields[s]).change(function () {
                                var canCalculate = true;
                                for (var s in fields) {
                                    var fieldValue = $(fieldPrefix + fields[s]).val();
                                }
                                if (canCalculate) {
                                    var cresult = 1;
                                    var cresultString = formular;

                                    for (var s in fields) {
                                        var reg = "/" + fields[s] + "/g";

                                        var fieldValue = $(fieldPrefix + fields[s]).val();

                                        cresultString = cresultString.replace(eval(reg), fieldValue)

                                        //cresult = cresult * parseFloat(fieldValue);
                                    }

                                    try {
                                        eval("cresult=" + cresultString);
                                        console.log(cresultString);
                                        $(e).val(FixFourDecimal(cresult));
                                        $(e).change();
                                    }
                                    catch (ee) {

                                    }
                                }
                                else {
                                    $(e).val("");
                                    $(e).change();
                                }
                            });
                        }
                    }
                }
            }
        }
    });



    $("#tableDetail").find(".isPriceFactor").change(function (i, e) {

        var result = 1;
        var canCalculate = true;
        $("#tableDetail").find(".isPriceFactor").each(function (ii, ee) {
            var v = $(ee).val();
            if (v == "" || isNaN(v)) {
                canCalculate = false;
                return;
            }
            else {
                result = result * parseFloat(v);
            }
        });

        priceFactor = result;
        $("#Price").change();


    });
}

function OpenPriceTip() {

    if (!$("#Category").val()) {
        alert("请选择业务类型");
    }
    else {
        $('#divPriceTip').dialog('open');
    }
}

function addDetail() {
    ClearErrorMsg();

    divTechnics.empty();

    $("#Guid").val("");
    $("#Id").val("");
    $("#ReportCategory").val();
    $("#Category option:first").prop("selected", 'selected');
    $('#popOrderDetail input[type=text]').val("");
    $('#popOrderDetail textarea').val("");
    $('#popOrderDetail select').val("");
    $('#popOrderDetail').dialog('open');

    CategoryChange();
    resetPriceFactor();

    $("#popOrderDetail #Category").val("").select2();

    $("#popOrderDetail #MaterialId").val("");
    $("#popOrderDetail #MaterialId").change();
    FilterMaterialDdl(null, $("#popOrderDetail #MaterialId"));
}

function CalculatePrice() {
    var amount = $("#Amount").val();
    var number = $("#Number").val();

    if (!isNaN(amount) && !isNaN(number)) {
        $("#Price").val(FixFourDecimal(parseFloat(amount) / parseFloat(number)));
    }
}

function AutoGetPrice() {
    if ($.trim($("#FactoryNo").val()) == "") {
        alert("请先选择[外协商]！");
        return;
    }

    $.ajax({
        url: "/FactoryOrder/GetOrderHistoryPrice",
        type: 'GET',
        cache: false,
        dataType: 'json',
        async: false,
        data: { FactoryNo: $("#FactoryNo").val(), CategoryNo: $("#Category").val(), DetailText: GetDetailDetailText() },
        success: function (result) {

            if (result.code == 0) {
                $("#Price").val(result.data);
                PopUpPriceChange();
                ShowPriceMessage("#priceMessage", "获取成功！");
            }
            else if (result.code = 1) {
                ShowPriceMessage("#priceMessage", "没有找到匹配的历史单价！");
            }
        },
        error: function (e) {
        }
    });
}

function ShowPriceMessage(id, text) {
    $(id).html(text);
    $(id).fadeIn("fast");
    $(id).fadeOut(2500);
}

function AutoGetFactoryPrice() {

    $.ajax({
        url: "/FactoryOrder/GetOrderFactoryHistoryPrice",
        type: 'GET',
        cache: false,
        dataType: 'json',
        async: false,
        data: { FactoryNo: $("#FactoryNo").val(), CategoryNo: $("#Category").val(), DetailText: GetDetailDetailText() },
        success: function (result) {
            if (result.code == 0) {
                $("#FactoryPrice").val(result.data);
                FactoryPriceChange();
                ShowPriceMessage("#factoryPriceMessage", "获取成功！");
            }
            else if (result.code = 1) {
                ShowPriceMessage("#factoryPriceMessage", "没有找到匹配的外协订单价！");
                $("#factoryPriceMessage").html("没有找到匹配的外协订单价！");
            }
        },
        error: function (e) {
        }
    });
}

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 saveDetail() {
    if (!checkRequired("popOrderDetail")) {
        return;
    }

    var detail = GetDetailDetail();

    var detailExisted = false;
    for (var i = 0; i < orderDetails.length; i++) {
        if (orderDetails[i].Guid == detail.Guid) {
            orderDetails[i] = detail;
            detailExisted = true;
            break;
        }
    }
    if (!detailExisted) {
        orderDetails.push(detail);
    }

    generateDetailTable();
    calcMarketAmount();
    $("#popOrderDetail").dialog("close");
}

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

    var tr, td, a;
    console.log(orderDetails);

    $(orderDetails).each(function (i, v) {
        tr = $("<tr id='" + v.Guid + "'></tr>");

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

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

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

        td = $("<td></td>").html(getUnitNameById(v.PriceUnitId));
        td.appendTo(tr);

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

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

        td = $("<td>" + v.Memo + "</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></td>");
        a = $("<a href='#' onclick='editDetail(this)'>编辑</a>")
        a.appendTo(td);
        a = $("<a style='margin-left:10px' href='#' onclick='deleteDetail(this)'>删除</a>")
        a.appendTo(td);
        td.appendTo(tr);
        tr.appendTo(tBody);
    });
}

function editDetail(t) {
    ClearErrorMsg();

    $('#popOrderDetail input[type=text]').val("");
    $('#popOrderDetail textarea').val("");
    $('#popOrderDetail select').val("");

    var guid = $($(t).parent().parent()).attr("id");
    $("#Guid").val(guid);

    $(orderDetails).each(function (i, v) {
        if (guid == v.Guid) {
            $("#OrderName").val(v.OrderName);
            $("#Category").val(v.Category).select2();
            $("#Number").val(v.Number);
            $("#Price").val(v.Price);
            $("#Amount").val(v.Amount);
            $("#popOrderDetail #Memo").val(v.Memo);
            $("#Id").val(v.Id);
            $("#MaterialId").val(v.MaterialId).select2();
            $("#PriceUnitId").val(v.PriceUnitId);
            CategoryChange();
            SetDetailDetail(v.Detail);
            resetPriceFactor();

            if (v.MaterialId > 0) {
                SetPopDetailMaterialTechnics(v.MaterialId);
            }

            return false;
        }
    });

    $('#popOrderDetail').dialog('open');
}

function deleteDetail(t) {
    ClearErrorMsg();
    $('#popOrderDetail input[type=text]').val("");

    var guid = $($(t).parent().parent()).attr("id");


    for (var i = 0; i < orderDetails.length; i++) {
        if (orderDetails[i].Guid == guid) {
            orderDetails.splice(i, 1);
            break;
        }
    }

    generateDetailTable();
    calcMarketAmount();
}

function calcMarketAmount() {
    var MarketAmount = 0;

    $(orderDetails).each(function (i, v) {
        MarketAmount += parseFloat(v.Amount);
    });

    if ($("#FeeInstallation").val() && !isNaN($("#FeeInstallation").val())) {
        MarketAmount += parseFloat($("#FeeInstallation").val());
    }
    if ($("#FeeDelivery").val() && !isNaN($("#FeeDelivery").val())) {
        MarketAmount += parseFloat($("#FeeDelivery").val());
    }
    if ($("#FeeDesign").val() && !isNaN($("#FeeDesign").val())) {
        MarketAmount += parseFloat($("#FeeDesign").val());
    }
    if ($("#FeeOther").val() && !isNaN($("#FeeOther").val())) {
        MarketAmount += parseFloat($("#FeeOther").val());
    }

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

    calcRealAmount();
}

function OpenPriceHistory() {

    var tbody = $("#priceHistoryList");
    tbody.empty();

    $.ajax({
        url: "/FactoryOrder/GetOrderHistoryByCategoryAndFactory",
        type: 'GET',
        cache: false,
        dataType: 'json',
        async: false,
        data: { FactoryNo: $("#FactoryNo").val(), CategoryNo: $("#Category").val() },
        success: function (result) {
            if (result.code == 0) {
                $('#divPriceHistory').dialog('open');

                var tr;
                var td;

                for (var r in result.data) {

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

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

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

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

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

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

                    tr.appendTo(tbody);
                }
            }
            else {
            }
        },
        error: function (e) {
        }
    });
}

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 resetPriceFactor() {
    var result = 1;
    var canCalculate = true;
    $("#tableDetail").find(".isPriceFactor").each(function (ii, ee) {
        var v = $(ee).val();
        if (v == "" || isNaN(v)) {
            canCalculate = false;
            return;
        }
        else {
            result = result * parseFloat(v);
        }
    });

    priceFactor = result;
}


function getUnitNameById(id) {
    var unitName = "";
    $(allUnits).each(function (i, v) {
        if (id == v.ItemValue) {
            unitName = v.ItemText;
            return false;
        }
    });

    return unitName;
}

function FillMaterialDdl(data) {
    var selMaterial = $("#popOrderDetail #MaterialId");
    $("<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(materialId, price) {

    var realPrice = 0;
    $(allMaterials).each(function (i, v) {
        $(v.List).each(function (x, y) {
            if (materialId == y.Id) {

                realPrice = price ? price : y.FactoryPrice;
                $("#popOrderDetail #hiddenFactoryPrice").val(realPrice);
                $("#PriceUnitId").val(y.PriceUnitId);

                $("#Price").val(realPrice == 0 ? "" : realPrice);
                $("#Price").change();

                return false;

            }
        });
    });
}

function FindMaterialName(id) {

    var result = "";

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

        $(v.List).each(function (x, y) {

            if (y.Id == id) {
                result = y.Name;
                return false;
            }
        });

    });

    return result;
}

function SetPopTechnics(technics) {

    var guid = $("#Guid").val();

    divTechnics.empty();

    $(technics).each(function (i, v) {
        console.log(divTechnics);
        CreateTechnicDiv(v).appendTo(divTechnics);
    });
}

function CreateTechnicDiv(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");
        }

        PopTechnicChanged();
    });

    return div;
}


function PopTechnicChanged() {

    var totalPrice = parseFloat($("#popOrderDetail #hiddenFactoryPrice").val()) + GetPopTechnicFactoryPrice();
    $("#popOrderDetail #Price").val(totalPrice == 0 ? "" : totalPrice);
    $("#popOrderDetail #Price").change();
}

function GetPopTechnicFactoryPrice() {
    var technicFactoryPrices = 0;

    $(divTechnics.find("div")).each(function (i, v) {
        if ($(v).hasClass("selected")) {
            technicFactoryPrices += FixFourDecimal($(v).attr("data-fprice"));
        }
    });

    return technicFactoryPrices;
}

function SetPopDetailMaterialTechnics(materialId) {

    divTechnics.empty();

    if (!materialId) {
        return;
    }

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

                var guid = $("#Guid").val();

                $(result.technics).each(function (i, v) {
                    CreateTechnicDiv(v).appendTo(divTechnics);
                });

                $(orderDetails).each(function (i, v) {
                    if (guid == v.Guid) {

                        if (v.Technic != "" && v.Technic != null) {
                            $(JSON.parse(v.Technic)).each(function (i, v) {
                                var tc = $(divTechnics).find("div[data-id='" + v.TechnicId + "']");
                                if (tc.length == 0) {
                                    CreateTechnicDiv(v).appendTo(divTechnics);
                                }
                                else {
                                    tc.addClass("selected");
                                }
                            });
                        }
                        return false;
                    }
                });

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

            }
        },
        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 GetPopSelectedTechnics() {

    var selectedTechnics = [];
    $(divTechnics.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 GetPopSelectedTechnicsText() {

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

    return selectedTechnics.join(", ");
}