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

$(function () {

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

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

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

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

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

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

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

    constructDetail();

    generateDetailTable();

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

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

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


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

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

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

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

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

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

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

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

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

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

    });

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

        ClearErrorMsg();

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

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

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

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

            if (!$(v).find("#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;
        }

        $($("#simpleOrderTr tr")).each(function (i, v) {
            CalcSimpleStockNumber(v);
        });
        
        orderDetails = GetOrderDetails();

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

        if (isOrderAdd) {

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

        }
        else {
            var additonMessage = "";

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

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


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

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

    if ($("#QuotationId").val() == "0" && $("#simpleOrderTr tr").length < 1) {
        addOrderDetailRow(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,
                DetailText: v.DetailText,
                Category: v.Category,
                ReportCategory: v.ReportCategory,
                Number: v.Number,
                StockNumber: v.StockNumber,
                Price: v.Price,
                Amount: v.Amount,
                PriceUnitId: v.PriceUnitId,
                Width: d.Width,
                Height: d.Height,
                Area: d.Area,
                Memo: v.Memo,
                MaterialId: v.MaterialId,
                Technic: v.Technic,
                TechnicText: v.TechnicText == null ? '' : v.TechnicText,
            });
        });
    }


    InitialCategoryDropdown();
}

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 #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").unbind("change").change(function () {
        SimplePriceChange($(this).parent().parent());
    });

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

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

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

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

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

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

    $("#simpleOrderDetail #MaterialId").hover(function () {
        if ($(this).val() != "") {
            $(this).attr("title", $(this).find("option:selected").text());
        }
        else {
            $(this).removeAttr("title");
        }

    });

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


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

        var d = {
            Id: $(v).find("#Id").val(),
            QuotationName: $(v).find("#QuotationName").val(),
            Detail: JSON.stringify(GetDetailObject(v)),
            DetailText: GetDetailText(v),
            Number: $(v).find("#Number").val(),
            Price: $(v).find("#Price").val(),
            Amount: $(v).find("#Amount").val(),
            StockNumber: $(v).find("#StockNumber").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 InitialCategoryDropdown() {
    $("<option value=''>&nbsp;</option>").appendTo($("#Category"));

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

function CategoryChange(c) {

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

    var cv = $(c).val();
    var cms = null;
    if (cv) {
        var guid;
        $(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 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 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.DeliveryType = $("#DeliveryType").val(),
        result.DeliveryAddress = $("#DeliveryAddress").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.TemplateNo = $("#TemplateNo").val();
    result.WidthUnit = $("#WidthUnit").val();

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

    return JSON.stringify(result);
}



function addOrderDetailRow(rowData) {

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

        };
    }

    var tBody = $("#simpleOrderTr");
    var tr, td, input, select, hidden;
    var inputStock;
    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 hiddenSailPrice = $("<input type='hidden' id='hiddenSailPrice'></input>").val("0");


    inputStock = $("<input type=hidden value='" + rowData.StockNumber + "' id='StockNumber' />");
    inputStock.val(rowData.StockNumber);

    td = $("<td></td>");
    inputStock.appendTo(td); 
    hiddenId.appendTo(td);
    hiddenTechnic.appendTo(td);
    hiddenSailPrice.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='QuotationName' value='" + rowData.QuotationName + "'></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 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 td1 = tr.find("td:eq(1)");
    var sel1 = td1.find("select");
    td1.empty();
    $(sel1).appendTo(td1);

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


    $(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 newCustomer() {
    ClearErrorMsg();
    $("#CustomerFullName").val("");
    $('#divCustomer').dialog('open');
}

function newContact() {

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

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

    ClearErrorMsg();
    $('#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 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 MaterialChange(m) {

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

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

    if (materialId) {

        $.ajax({
            url: "/Order/GetCustomerPrice",
            type: 'GET',
            cache: false,
            data: { CustomerNo: $('#CustomerNo').val(), MaterialId: materialId },
            success: function (result) {
                if (result.code == 0) {
                    getLocalPrice(m, materialId, result.price);
                }
                else {
                    getLocalPrice(m, materialId, 0);
                }

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


    }
}

function getLocalPrice(m, materialId, cPrice) {
    console.log(cPrice);
    $(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 realCPrice = cPrice == 0 ? y.SailPrice : cPrice;
                $(m).parent().parent().find("#Price").val(realCPrice == 0 ? "" : realCPrice);

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

    });
}

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

    return div;
}

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

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

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

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

        $(v.List).each(function (x, y) {
            if (y.Id == materialId) {
                price = y.SailPrice;
                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 GetTotalSailTechnicPrice(m) {
    var totalTechnicPrice = 0;
    var selecteTechnics = $(m).parent().parent().find("#hiddenTechnic").val();

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

    return totalTechnicPrice;
}

function setSimplePrice(m) {

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

    var technicSailPrice = GetTotalSailTechnicPrice(m);
    var totalSailPrice = parseFloat(tr.find("#hiddenSailPrice").val()) + technicSailPrice;
    tr.find("#Price").val(totalSailPrice == 0 ? "" : totalSailPrice);

    WidthHeightChange(m);
}

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

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

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

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