var did = "";
var orderTemplate = {};
var allCustomer = [];
var WorkFlowIsNull = "";
var Detail = {}; // Store all order details
var customerRealChanged = false;

$(function () {

    $('#divClose').click(function () {
        //alert(window.location.href);
        window.location.href = "/App/Close";
    });


    $.blockUI({ message: '加载中...' });
    $.ajax({
        url: "/App/GetAutoCompleteCustomer?companyNo=" + $("#hCompanyNo").val(),
        type: 'GET',
        cache: false,
        dataType: 'json',
        async: false,
        success: function (result) {
            $.unblockUI();
            for (var i in result.data) {
                allCustomer.push({ label: result.data[i].ItemText, value: result.data[i].ItemValue });
            }
            console.log(allCustomer);
        },
        error: function (e) {
            $.unblockUI();
        }
    });

    WorkFlowIsNull = $("#WorkFlowIsNull").val();

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


    if ($("#Amount").val() == "0") {
        $("#Amount").val("");
    }
    if ($("#Number").val() == "0") {
        $("#Number").val("");
    }
    if ($("#Price").val() == "0") {
        $("#Price").val("");
    }

    $("#Amount").inputmask({ 'mask': "9{0,9}[.9{0,2}]", greedy: false });
    $("#Number").inputmask({ 'mask': "9{0,9}", greedy: false });
    $("#Price").inputmask({ 'mask': "9{0,9}[.9{0,2}]", greedy: false });

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

    $("#WorkFlowNo").change(function () {
        if ($("#WorkFlowNo").val() == "") {
            $("#divWorkFlow").hide();
            return;
        }
        else {
            if (WorkFlowIsNull == "1") {
                $("#divWorkFlow").show();
            }
            else {
                $("#divWorkFlow").hide();
            }
        }

        $("#WorkFlowStepNo").empty();
        //$("#WorkFlowStepNo").append("<option></option>");
        $("#WorkFlowUserId").empty();
        //$("#WorkFlowUserId").append("<option></option>");
        $.ajax({
            url: "/App/GetWorkFlowNextSteps",
            type: 'GET',
            cache: false,
            dataType: 'json',
            async: false,
            data: { WorkFlowNo: $("#WorkFlowNo").val(), WorkFlowStepNo: "0" },
            success: function (result) {
                if (result.code == 0) {
                    for (var r in result.data) {
                        $("#WorkFlowStepNo").append("<option value='" + result.data[r].ItemValue + "'>" + result.data[r].ItemText + "</option>");
                    }
                }
                else {

                }
            },
            error: function (e) {

            }
        });
    });

    $("#WorkFlowStepNo").change(function () {
        $("#WorkFlowUserId").empty();
        //$("#WorkFlowUserId").append("<option></option>");
        $("#isEndPoint").val("0");
        if ($("#WorkFlowStepNo").val() == "") {
            return;
        }

        $.ajax({
            url: "/App/GetWorkFlowStepUsers",
            type: 'GET',
            cache: false,
            dataType: 'json',
            async: false,
            data: { WorkFlowNo: $("#WorkFlowNo").val(), WorkFlowStepNo: $("#WorkFlowStepNo").val() },
            success: function (result) {
                if (result.code == 0) {
                    $("#isEndPoint").val(result.isEndPoint);
                    if (result.isEndPoint == "0") {
                        for (var r in result.data) {
                            $("#WorkFlowUserId").append("<option value='" + result.data[r].ItemValue + "'>" + result.data[r].ItemText + "</option>");
                        }
                    }
                }
                else {

                }
            },
            error: function (e) {

            }
        });
    });

    $('#IsDelivery').change(function () {
        
        if ($("#IsDelivery").prop("checked")) {
            $("#DeliveryAddress").attr("placeholder", "请填写收货地址");
            $("#DeliveryAddress").removeAttr("readonly");             
        }
        else {
            
            $("#DeliveryAddress").removeAttr("placeholder");
            $("#DeliveryAddress").attr("readonly", "readonly");
            $("#DeliveryAddress").val("");
        }
    });

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

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

                    if ($("#IsDelivery").prop("checked")) {                        
                        $("#DeliveryAddress").val(result.CustomerAddress);
                    }                 

                    $("#ContactNo").empty();
                   
                    $("#ContactNo").append("<option value=''>请选择</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();
                }
                else {
                }
            },
            error: function (e) {
            }
        });
    });   

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

        $("#divOrder").find("input").removeClass("redBorder");
        $("#divOrder").find("select").removeClass("redBorder");
        $("#divOrder").find("textarea").removeClass("redBorder");

        if ($("#CustomerNo").val() == "") {
            $("#CustomerNo").addClass("redBorder");
            alert("请选择客户");
            return;
        }

        if ($("#Content").val() == "") {
            $("#Content").addClass("redBorder");
            alert("请填写订单名称");
            return;
        }

        if ($("#Number").val() == "") {
            $("#Number").addClass("redBorder");
            alert("请填写数量");
            return;
        }

        if ($("#Price").val() == "") {
            $("#Price").addClass("redBorder");
            alert("请填写单价");
            return;
        }

        if ($("#Amount").val() == "") {
            $("#Amount").addClass("redBorder");
            alert("金额不能为空");
            return;
        }

        if ($("#PrePaid").val() && !isNaN($("#PrePaid").val())) {
            if (!$("#PrePaidPaymentType").val()) {
                $("#PrePaidPaymentType").addClass("redBorder");
                alert("必须选择支付类型");
                return;
            }
        }

        if (checkRequired('divOrder', 'errorMessage') == false) {
            alert("请检查详细信息是否填写完整");
            return;
        }

        if ($("#IsDelivery").prop("checked")) {
            if ($("#DeliveryAddress").val() == "") {
                $("#DeliveryAddress").addClass("redBorder");
                alert("请填写送货地址");
                return;
            }
        }

        if ($("#WorkFlowNo").val() == "") {
            $("#WorkFlowNo").addClass("redBorder");
            alert("请选择流程");
            return;
        }
        if ($("#WorkFlowStepNo").val() == "") {
            $("#WorkFlowStepNo").addClass("redBorder");
            alert("请选择流程下一步");
            return;
        }
        if ($("#isEndPoint").val() != "1") {
            if ($("#WorkFlowUserId").val() == "") {
                $("#WorkFlowUserId").addClass("redBorder");
                alert("请选择经办人");
                return;
            }
        }

        if (!confirm("确定保存订单吗？")) {
            return;
        }

        Detail = CreateNewDetailObject();

        $.blockUI({ message: '保存中...' });
        $.ajax({
            url: "/App/Add",
            type: 'POST',
            cache: false,
            dataType: 'json',
            data: { BasicInfo: GetBasicInfo(), DetailInfo: GetDetailInfo(),token:$("#hToken").val() },
            success: function (result) {
                $.unblockUI();
                if (result.code == 0) {
                    alert("保存成功");
                    window.location.href = "/App/Close";
                }
            },
            error: function (e) {
                $.unblockUI();
                alert("保存时发生错误");
            }
        });


    });


    if ($('#CustomerNo').val() != "") {
        $.ajax({
            url: "/App/GetContact",
            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) {
            }
        });
    }

    $("#ContactNo").val($("#hContactNo").val());

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

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

    CategoryChange();


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

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

    $('#IsDelivery').change();
});


function clearForm() {
    $("#divOrderDetail").find("input").removeClass("redBorder");
    $("#divOrderDetail").find("select").removeClass("redBorder");
    $("#divOrderDetail").find("input[type=text]").val("");
    $("#divOrderDetail").find("select").val("");
    $("#divOrderDetail").find("textarea").val("");
    $("#divOrderDetail").find(".errorSpan").html("");
    $("#divOrderDetail").find("#Category").change();
}

function GetBasicInfo() {
    var result = {};
    result.OrderNo = $("#OrderNo").val();
    result.OrderName = $("#OrderName").val();
    result.CustomerNo = $("#CustomerNo").val();
    result.ContactNo = $("#ContactNo").val();
    result.TemplateNo = $("#TemplateNo").val();
    result.Contact = $("#Contact").val();
    result.IsDelivery = $("#IsDelivery").prop("checked");
    result.DeliveryAddress = $("#DeliveryAddress").val();   

    return JSON.stringify(result);
}

function GetDetailInfo() {

    if (Detail.Detail != null) {
        Detail.Detail = JSON.stringify(Detail.Detail);
    }

    return JSON.stringify(Detail);
}

function CreateNewDetailObject() {
    var newDetail = {
        Content: $("#Content").val(),
        Category: $("#Category").val(),
        CategoryName: GetCategoryName($("#Category").val()),
        ReportCategory: $("#ReportCategory").val(),
        Detail: GetDetailDetail(),
        DetailText: GetDetailDetailText(),
        Number: $("#Number").val(),
        Price: $("#Price").val(),
        Amount: $("#Amount").val(),
        Memo: $("#Memo").val(),
        WorkFlowNo: $("#WorkFlowNo").val(),
        WorkFlowStepNo: $("#WorkFlowStepNo").val(),
        WorkFlowUserId: $("#WorkFlowUserId").val(),
       

    };

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


    newDetail.Amount = parseFloat(newDetail.Amount);

    if (isNaN(newDetail.Amount)) {
        newDetail.Amount = 0;
    }

    return newDetail;
}

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

    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 GetCategoryName(id) {
    for (var i in orderTemplate) {

        if (orderTemplate[i].id == id) {
            return orderTemplate[i].text;
            break;
        }
    }
    return "";
}

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

    var k = 0;
    var tr;
    var td;

    for (var i in orderTemplate) {
        if (orderTemplate[i].id == $('#Category').val()) {

            $("#ReportCategory").val(orderTemplate[i].reportCategory);
            for (var j in orderTemplate[i].fields) {

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

                    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].isRequired) {
                    $("<span class='redStar'>*</span>").appendTo(td);
                }
                td.appendTo(tr);
                tr.appendTo(table);

            }

            break;
        }
    }

    $("#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 fields = formular.split("*");

                        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;
                                    for (var s in fields) {
                                        var fieldValue = $(fieldPrefix + fields[s]).val();
                                        cresult = cresult * parseFloat(fieldValue);
                                    }

                                    $(e).val(FixTwoDecimal(cresult));
                                }
                                else {
                                    $(e).val("");
                                }
                            });
                        }
                    }
                }
            }
        }
    });


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

        if (!canCalculate) {
            $("#Price").val("");
        }
        else {
            $("#Price").val(FixTwoDecimal(result));
        }

    });
}

function PriceChange() {

    var price = $("#Price").val();
    var number = $("#Number").val();

    if (!isNaN(price) && !isNaN(number)) {
        $("#Amount").val(FixTwoDecimal(parseFloat(price) * parseFloat(number)));
    }
}

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

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

//重写alert样式
function alert(messa) {
    if ($("#dialogalert").length == 0) {
        $("body").append('<div id="dialogalert"></div>');
    }

    $("#dialogalert").dialog({
        autoOpen: false,
        title: '提示',
        model: true,
        width: 240,
        buttons: {
            '关闭': function () {
                $(this).dialog('close');
            }
        }
    });
    $("#dialogalert").html(messa);
    $("#dialogalert").dialog('open');
}