var orderTemplate = {};
var allCustomer = [];
var orderDetails = [];
var allUnits = [];
var allMaterials = [];
var divTechnics = null;

function constructDetail() {

    orderTemplate = eval($("#OrderTemplateString").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,
                QuotationName: v.QuotationName,
                Detail: d,
                DetailText: v.DetailText,
                Category: v.Category,
                CategoryName: v.CategoryName,
                ReportCategory: v.ReportCategory,
                Number: v.Number,
                Price: v.Price,
                Amount: v.Amount,
                MaterialId: v.MaterialId,
                MaterialName: FindMaterialName(v.MaterialId),
                Memo: v.Memo,
                PriceUnitId: v.PriceUnitId,
                Technic: v.Technic,
                TechnicText: v.TechnicText == null ? '' : v.TechnicText,
                Guid: newId()
            });
        });

        generateDetailTable();
    }
}


$(function () {

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

    divTechnics = $("#popOrderDetail #divTechnics")

    $.blockUI({ message: '<h5>加载中...</h5>' });
    $.ajax({
        url: "/Order/GetJsonCustomerFactoryPriceUnit?quotationId=" + $("#QuotationId").val(),
        type: 'GET',
        cache: false,
        dataType: 'json',
        async: false,
        success: function (result) {
            $.unblockUI();

            allUnits = result.priceUnits;
            templateUnitAndPrices = result.unitPrices;

            for (var i in result.customers) {
                allCustomer.push({ label: result.customers[i].ItemText, value: result.customers[i].ItemValue });
            }

            allMaterials = result.materials;

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

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

    constructDetail();
    generateDetailTable();

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


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

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


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

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

        if (materialId) {

            $.ajax({
                url: "/Order/GetCustomerPrice",
                type: 'GET',
                cache: false,
                data: { CustomerNo: $('#CustomerNo').val(), MaterialId: materialId },
                success: function (result) {
                    if (result.code == 0) {
                        $("#popOrderDetail #PriceUnitId").val(result.unit);
                        getSailPrice(materialId, result.price);
                        SetPopTechnics(result.technics);
                    }
                },
                error: function (e) {
                    getSailPrice(materialId, 0);
                }
            });
        }
        else {
            divTechnics.empty();
        }
    });

    $('#CustomerNo').change(function () {
        if ($('#CustomerNo').val() == "") {
            return;
        }

        $.ajax({
            url: "/Order/GetContactAndPaymentType",
            type: 'GET',
            cache: false,
            data: { customerNo: $('#CustomerNo').val() },
            success: function (result) {

                $("#ContactNo").empty();
                $("#Contact").val("");

                $("#ContactNo").append("<option></option>");
                var mainContactId = "";
                for (var r in result.Data) {
                    if (result.Data[r].IsMain) {
                        mainContactId = result.Data[r].Id;
                    }
                    $("#ContactNo").append("<option value='" + result.Data[r].Id + "'>" + result.Data[r].Name + " " + result.Data[r].Phone + "</option>");
                }
                $("#ContactNo").val(mainContactId);

                $("#ContactNo").change();
            },
            error: function (e) {
            }
        });
    });

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

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

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

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

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

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

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

        $.ajax({
            url: "/Customer/Add",
            type: 'POST',
            cache: false,
            data: {
                CanLogin: false,
                CustomerFullName: $("#CustomerFullName").val(),
                CustomerShortName: $("#CustomerFullName").val(),
                UseBalanceFirst: false
            },
            success: function (result) {
                if (result.code == 0) {
                    $('#divCustomer').dialog('close');
                    $("<option value='" + result.data + "'>" + $("#CustomerFullName").val() + "</option>").appendTo($("#CustomerNo"));
                    $("#CustomerNo").val(result.data);
                }
                else {
                    SetErrorMsg(result.message, "divCustomer");
                }
            },
            error: function (e) {
                SetErrorMsg("添加客户失败", "divCustomer");
            }
        })
    });

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

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

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

    });

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

        ClearErrorMsg();

        if ($("#CustomerNo").val() == "" && $("#CustomerName").val() == "") {
            $("#CustomerName").addClass("redBorder");
            return SetErrorMsg('请选择客户，临时客户请填写客户名称。');
        }

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

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

        // 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 ($("#QuotationId").val() == "0") {

            $.ajax({
                url: "/Order/QuotationAdd",
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: { BasicInfo: GetBasicInfo(), orderDetails: JSON.stringify(orderDetailsClone) },
                success: function (result) {
                    $.unblockUI();
                    if (result.code == 0) {
                        location.href = "/Order/QuotationList";
                    }
                    else if (result.code == 1) {
                        SetErrorMsg(result.message);
                    }
                    else if (result.code == 2) {
                        $("#CustomerNo").addClass("redBorder");
                        SetErrorMsg(result.message);
                    }
                    else {
                        return SetErrorMsg_Save_Failed();
                    }
                },
                error: function (e) {
                    $.unblockUI();
                    return SetErrorMsg_Save_Failed();
                }
            });

        }
        else {
            var additonMessage = "";

            $.ajax({
                url: "/Order/QuotationUpdate",
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: { BasicInfo: GetBasicInfo(), orderDetails: JSON.stringify(orderDetailsClone) },
                success: function (result) {
                    $.unblockUI();
                    if (result.code == 0) {
                        if ($("#BackURL").val() == "") {
                            location.href = '/Order/QuotationList';
                        }
                        else {
                            location.href = $("#BackURL").val();
                        }
                    }
                    else if (result.code == 1) {
                        SetErrorMsg(result.message);
                    }
                    else if (result.code == 2) {
                        $("#CustomerNo").addClass("redBorder");
                        SetErrorMsg(result.message);
                    }
                    else {
                        return SetErrorMsg_Save_Failed();
                    }
                },
                error: function (e) {
                    $.unblockUI();
                    return SetErrorMsg_Save_Failed();
                }
            });
        }
    });

    if ($('#CustomerNo').val() != "") {
        $.ajax({
            url: "/Order/GetContactAndPaymentType",
            type: 'GET',
            cache: false,
            async: false,
            data: { customerNo: $('#CustomerNo').val() },
            success: function (result) {
                if (result != null) {

                    $("#ContactNo").append("<option></option>");

                    for (var r in result.Data) {
                        $("#ContactNo").append("<option value='" + result.Data[r].Id + "'>" + result.Data[r].Name + " " + result.Data[r].Phone + "</option>");
                    }
                }
                else {
                }
            },
            error: function (e) {
            }
        });
    }

    $('#Category').change(function () {
        CategoryChange();
        $("#popOrderDetail #MaterialId").val("");
        $("#popOrderDetail #MaterialId").change();
        resetPriceFactor();
    });

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

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


    $("#TaxType,#TaxRatio").change(function () {
        calcRealAmount();
    });

    if ($("#TaxType").val() == "") {
        $("#TaxRatio").attr("readonly", true);
    }
});

function GetBasicInfo() {
    var result = {};
    result.Id = $("#QuotationId").val();
    result.CustomerNo = $("#CustomerNo").val();
    result.CustomerName = $("#CustomerName").val();
    result.ContactNo = $("#ContactNo").val();
    result.Contact = $("#Contact").val();
    result.QuotationDate = $("#QuotationDate").val();

    result.MarketAmount = $("#MarketAmount").val();
    result.Discount = $("#Discount").val();
    result.RealAmount = $("#RealAmount").val();

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

    result.Memo = $("TextArea[id='Memo']").val();
    result.TemplateNo = $("#TemplateNo").val();

    result.TaxType = $("#TaxType").val();
    result.TaxRatio = $("#TaxRatio").val();
    result.TaxAmount = $("#TaxAmount").val();
    result.FeeTax = $("#FeeTax").val();

    return JSON.stringify(result);
}

function GetDetailDetail() {
    var result = {};

    var guid = $("#popOrderDetail #Guid").val();
    result.Guid = guid == "" ? newId() : guid;
    result.Id = $("#popOrderDetail #Id").val() == "" ? "0" : $("#Id").val();
    result.QuotationName = $("#popOrderDetail #QuotationName").val();
    result.Category = $("#popOrderDetail #Category").val();
    result.ReportCategory = $("#popOrderDetail #ReportCategory").val();
    result.Number = $("#popOrderDetail #Number").val();
    result.StockNumber = $("#popOrderDetail #StockNumber").val();
    result.Price = $("#popOrderDetail #Price").val();
    result.Amount = $("#popOrderDetail #Amount").val();
    result.Memo = $("#popOrderDetail #Memo").val();
    result.MaterialId = $("#popOrderDetail #MaterialId").val();
    result.MaterialName = $("#popOrderDetail #MaterialId").find("option:selected").text();
    result.PriceUnitId = $("#popOrderDetail #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("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']").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 in orderTemplate[i].fields) {
                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></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 });
                    }
                    if (orderTemplate[i].fields[j].isStockFactor != undefined
                        && orderTemplate[i].fields[j].isStockFactor) {
                        textbox.addClass("isStockFactor");
                        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");
                    }
                    if (orderTemplate[i].fields[j].isStockFactor != undefined
                        && orderTemplate[i].fields[j].isStockFactor) {
                        ddl.addClass("isStockFactor");
                    }
                    ddl.appendTo(td);
                }

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

                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;
            console.log(cms);
            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, "*").split("*");

                        var fields = [];
                        $(condiateFields).each(function (i, v) {
                            if (isNaN(v)) {
                                fields.push(v);
                            }
                        });

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

                            $(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 (fieldValue == "" || isNaN(fieldValue)) {
                                        canCalculate = false;
                                        break;
                                    }
                                }
                                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);
                                    }
                                    eval("cresult=" + cresultString);

                                    $(e).val(FixFourDecimal(cresult));
                                    $(e).change();
                                }
                                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);
            }
        });
        console.log(result);
        priceFactor = result;
        $("#Price").change();
    });

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

        var result = 1;
        var canCalculate = true;
        $("#tableDetail").find(".isStockFactor").each(function (ii, ee) {
            var v = $(ee).val();
            if (v == "" || isNaN(v)) {
                canCalculate = false;
                return;
            }
            else {
                result = result * parseFloat(v);
            }
        });
        console.log(result);
        stockFactor = 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 select').val("");
    $('#popOrderDetail textarea').val("");
    $('#popOrderDetail').dialog('open');
    
    $("#popOrderDetail #Category").val("").select2();
    $("#popOrderDetail #MaterialId").val("").select2();

    CategoryChange();

    resetPriceFactor();
}

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

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

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

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

    CalcPopUpStockNumber();

    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.QuotationName + "</td>");
        td.appendTo(tr);

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

        td = $("<td>" + getUnitNameById(v.PriceUnitId) + "</td>");
        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("");

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

    $(orderDetails).each(function (i, v) {
        if (guid == v.Guid) {
            $("#popOrderDetail #QuotationName").val(v.QuotationName);
            $("#popOrderDetail #Category").val(v.Category).select2();
            $("#popOrderDetail #Number").val(v.Number);
            $("#popOrderDetail #StockNumber").val(v.StockNumber);
            $("#popOrderDetail #Price").val(v.Price);
            $("#popOrderDetail #Amount").val(v.Amount);
            $("#popOrderDetail #Memo").val(v.Memo);
            $("#popOrderDetail #Id").val(v.Id);
            $("#popOrderDetail #MaterialId").val(v.MaterialId).select2();
            $("#popOrderDetail #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: "/Order/GetOrderHistoryByCategoryAndCustomer",
        type: 'GET',
        cache: false,
        dataType: 'json',
        async: false,
        data: { CustomerNo: $("#CustomerNo").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].CustomerShortName);
                    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 newCustomer() {
    $("#CustomerFullName").val("");
    $('#divCustomer').dialog('open');
}

function newContact() {

    if (!$("#CustomerNo").val()) {
        return alert("请先选择客户");
    }

    $("#ContactName").val("");
    $("#Phone").val("");
    $("#tdCustomerName").text($("#CustomerNo").find("option:selected").text());

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

function SaveContact() {

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

    var data = {};
    data.CustomerNo = $("#CustomerNo").val();
    data.ContactName = $("#ContactName").val();

    if ($("#Phone").val().substr(0, 1) == "1") {
        data.Mobile = $("#Phone").val();
    }
    else {
        data.Phone = $("#Phone").val();
    }

    $.ajax({
        url: "/Contact/Add",
        type: 'POST',
        cache: false,
        data: data,
        success: function (result) {
            if (result.code == 0) {
                $('#divContact').dialog('close');
                $("<option value='" + result.data.ContactNo + "'>" + result.data.ContactName + " " + $("#Phone").val() + "</option>").appendTo($("#ContactNo"));
                $("#ContactNo").val(result.data.ContactNo);

                $("#Contact").val($("#ContactName").val() + " " + $("#Phone").val());
            }
            else {
                SetErrorMsg(result.message, "divContact");
            }
        },
        error: function (e) {
            SetErrorMsg("添加联系人失败", "divContact");
        }
    })
}



function bindEvents() {

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

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

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

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


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

    FactoryPriceChange($(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)) {
        row.find("#Area").val(changeFourDecimal(width * height * number));
    }

    FactoryPriceChange(row);
}

function FillMaterialDdl(data) {
    var selMaterial = $("#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 FindMaterialName(id) {

    var result = "";
    console.log(allMaterials);
    $(allMaterials).each(function (i, v) {

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

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

    });

    return result;
}

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;

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

    stockFactor = result;
}


function getSailPrice(materialId, price) {

    var realPrice = 0;
    $(allMaterials).each(function (i, v) {
        $(v.List).each(function (x, y) {
            if (materialId == y.Id) {
                realPrice = price ? price : y.SailPrice;
                $("#popOrderDetail #hiddenSailPrice").val(realPrice);
                $("#popOrderDetail #PriceUnitId").val(y.PriceUnitId);
                $("#popOrderDetail #Price").val(realPrice == 0 ? "" : realPrice);
                $("#popOrderDetail #Price").change();
                return false;
            }
        });
    });
}

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

    return unitName;
}

function SetPopTechnics(technics) {

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

    divTechnics.empty();

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

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

function SetPopDetailMaterialTechnics(materialId) {

    divTechnics.empty();

    if (!materialId) {
        return;
    }

    $.ajax({
        url: "/Order/GetMaterialTechnicsWithCFPrice",
        type: 'GET',
        cache: false,
        data: { MaterialId: materialId, CustomerNo: $("#CustomerNo").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.cPrice) {
                    $("#popOrderDetail #hiddenSailPrice").val(result.cPrice);
                }
                else {
                    $("#popOrderDetail #hiddenSailPrice").val(getPriceFromLocal(materialId));
                }

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

function CreateTechnicDiv(v) {
    var div = $("<div></div>").attr("title", "销售价: " + v.SailPrice).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 #hiddenSailPrice").val()) + GetPopTechnicSailPrice();
    $("#popOrderDetail #Price").val(totalPrice == 0 ? "" : totalPrice);
    $("#popOrderDetail #Price").change();
}

function GetPopTechnicSailPrice() {
    var technicPrices = 0;

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

    return technicPrices;
}

function getPriceFromLocal(materialId) {

    var price = 0;
    $(allMaterials).each(function (i, v) {
        $(v.List).each(function (x, y) {
            if (materialId == y.Id) {
                price = y.SailPrice;
                return false;
            }
        });
    });

    return price;
}
