var did = "";
var isOrderAdd;
var orderTemplate = {};

$(function () {

    $("#Number").inputmask({ 'mask': "9{0,9}", greedy: false });

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

    $('#btnCancel').click(function () {
        if (confirm("确定要放弃修改吗？")) {
            location.href = "/Portal/Index";
        }
    });    

    $('#btnSave').click(function () {
        ClearErrorMsg();
        if (isOrderAdd) {
            if (checkRequired('divOrder', 'errorMessage') == false) {
                return;
            }
          
            if (!confirm("确定保存订单吗？")) {
                return;
            }

            $.ajax({
                url: "/Portal/CreateNewOrder",
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: { BasicInfo: GetBasicInfo()},
                success: function (result) {
                    if (result.code == 0) {
                        location.href = "/Portal/Index";
                    }
                    else {
                        SetErrorMsg(result.message);
                    }
                },
                error: function (e) {
                    SetErrorMsg('保存失败.');
                }
            });
        }
        else {
            if (!checkRequired('divOrder', 'errorMessage')) {
                return;
            }

            var additonMessage = "";

            if (confirm(additonMessage + '确定保存修改吗？')) {
                $.ajax({
                    url: "/Portal/UpdateOrder",
                    type: 'POST',
                    cache: false,
                    dataType: 'json',
                    data: { BasicInfo: GetBasicInfo()},
                    success: function (result) {
                        if (result.code == 0) {
                            location.href = "/Portal/Index";
                        }
                        else {
                            SetErrorMsg(result.message);                            
                        }
                    },
                    error: function (e) {
                        SetErrorMsg('保存失败.'); 
                    }
                });
            }
        }
    });


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

    if ($("#IsAdd").val() == "1") {
        isOrderAdd = true;
        $("#Number").val("");
    }
    else {
        isOrderAdd = false;      
        $("#Category").val($("#hCategory").val());       
    }

    CategoryChange();

    if ($("#Detail").val()) {
        SetDetailDetail(JSON.parse($("#Detail").val()));
    }
 
});

function SetDetailDetail(obj) {
    
    var objNew = obj;
    for (var i in objNew) {
        if ($("#" + i).length > 0) {
            $("#" + i).val(objNew[i]);
        }
    }
}

function GetBasicInfo() {
    var result = {};
    result.OrderNo = $("#OrderNo").val();
    result.OrderName = $("#OrderName").val();
    result.ContactNo = $("#ContactNo").val();
    result.Contact = $("#Contact").val();

    result.Category = $("#Category").val();
    result.ReportCategory = $("#ReportCategory").val();
    result.Number = $("#Number").val();
    result.Memo = $("#Memo").val();

    result.Detail = JSON.stringify(GetDetailDetail());
    result.DetailText = GetDetailDetailText();
    result.TemplateNo = $("#TemplateNo").val();


    return JSON.stringify(result);
}

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." + id + "='" + $(t).val() + "';");
    });
    $("#tableDetail").find("select[id^='f']").each(function (i, t) {
        id = t.id.replace(/\(/g, "");
        id = id.replace(/\)/g, "");
        eval("result." + id + "='" + $(t).val() + "';");
    });

    console.log("123");
    console.log(result);
    return result;
}

function GetDetailDetailText() {
    var result = "";
    $("#tableDetail").find("input[id^='f'],select[id^='f']").each(function (i, t) {
        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;
    $("<tr class='title'><td colspan='6'>明细</td></tr>").appendTo(table);
    for (var i in orderTemplate) {
        if (orderTemplate[i].id == $('#Category').val()) {

            $("#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) {
                    // textbox
                    var textbox = $("<input type='text' id='" + fieldId + "' />");
                    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>");
                    }
                    ddl.appendTo(td);
                }
                else {
                    // TBD
                    // editable dropdownlist
                }
                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);
            }

            break;
        }
    }
}