var customerNo = "";
var trId = "";
var isAdd = true;

function EditCustomer(customerNo) {     

    isAdd = false;

    clearForm();   

    $("#trPassword").hide();
    $("#trLoginId").hide();
    $("#trContact").hide();

    $.ajax({
        url: "/Customer/GetCustomer",
        type: 'GET',
        cache: false,
        data: { customerNo: customerNo },
        success: function (result) {
            if (result.code == 0) {
                $("#CustomerNo").val(result.data.CustomerNo);
                $("#CustomerFullName").val(result.data.CustomerFullName);
                $("#CustomerShortName").val(result.data.CustomerShortName);
                $("#Address").val(result.data.Address);
                $("#Phone").val(result.data.Phone);
                $("#SearchKey").val(result.data.SearchKey);
                $("#Description").val(result.data.Description);
                $("#LoginId").val(result.data.LoginId);
                $("#IsActive").prop("checked", result.data.IsActive);
                $("#UseBalanceFirst").prop("checked", result.data.UseBalanceFirst);    
                $("#CategoryId").val(result.data.CategoryId);
                
                if (result.data.CanLogin) {
                    $("#CanLogin").prop("checked", true);                   
                    $("#trLoginId").show();
                }
                else {
                    $("#CanLogin").prop("checked", false);
                }

                showCustomer();
                $("#CustomerFullName").focus();
            }

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

    return false;
}

function DeleteCustomer(customerNo) {

    ClearErrorMsg();     

    synConfirm("确定删除吗？<br>提醒：该客户的报价记录，联系人等将一并删除。", function () {
        $.ajax({
            url: "/Customer/Delete",
            type: 'POST',
            cache: false,
            data: { customerNo: customerNo },
            success: function (result) {
                if (result.code == 0) {
                    $("#tCustomer").find("tr[id='" + result.id + "']").remove();
                }
                else if (result.code == 1) {
                    alert(result.message);
                }
                else {
                    alert('删除失败：该客户已产生业务数据，无法删除');
                }

            },
            error: function (e) {
                alert('删除失败：该客户已产生业务数据，无法删除1');
            }
        });
    });    

    return false;
}

function ShowDetail(id) {
    ClearErrorMsg();
    $("#OrderNo").val(id);
    $.ajax({
        url: "/Customer/GetCustomer",
        type: 'POST',
        cache: false,
        data: { customerNo: id },
        success: function (result) {
            if (result.code == 0) {
                $("#dCustomerFullName").html(result.data.CustomerFullName);
                $("#dCustomerShortName").html(result.data.CustomerShortName);
                $("#dSearchKey").html(result.data.SearchKey);                
                $("#dAddress").html(result.data.Address);
                $("#dPhone").html(result.data.Phone);
                $("#dUseBalanceFirst").html(result.data.UseBalanceFirst ? "是" : "否");
                $("#dBalance").html(FixTwoDecimal(result.data.Balance));
                $("#dLoginId").html(result.data.CanLogin? result.data.LoginId:"");
                $("#dDescription").html(result.data.Description);
                $("#dStatus").html(result.data.IsActive?"已启用":"已停用");
                $("#dCategoryName").html(result.data.CategoryName);
                $('#divDetail').dialog('open');
            }
            else {
                alert("获取信息失败.");
            }

        },
        error: function (e) {
            alert("获取信息失败.");
        }
    });
}

function setColor() {
    var spans = $("#tCustomer span");
    $(spans).each(function (i, v) {
        if ($(v).text() == "已停用") {
            $(v).parent().parent().addClass("tr-gray");
        }
        else {
            $(v).css("color", "#3c8dbc");
        }
    });
 
}

function GetPY() {
    $.ajax({
        url: "/Home/GetPYSZM",
        type: 'GET',
        cache: false,
        data: {
            value: $("#CustomerShortName").val()
        },
        success: function (result) {
            if (result.code == 0) {
                $("#SearchKey").val(result.data);
            }
        },
        error: function (e) {

        }
    });
}

$(function () {

    $("#CustomerShortName").keyup(function () {
        //GetPY();
    }).change(function () {
        GetPY();

    });
    $("#tCustomer .specify td").click(function () {
        console.log(1);
        if ($(this).parent().hasClass("totalTd") ||
            $(this).hasClass("td-last") ||
            $(this).hasClass("td-checkbox") ||
            $(this).hasClass("td-contact"))
           {
            return;
        }
        else {
            ShowDetail($(this).parent().attr("id"));
        }
    });

    setOperationBtns();

    TdRowOverOutSpecify("tCustomer");
    TdRowOverOut("tContact");
    setColor();

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

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

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


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

    $("#CanLogin").change(function () {
      
        if ($(this).prop("checked")) {
            $("#trLoginId").show();
            if (!isAdd) {
                $("#trPassword").hide();
            }
            else {
                $("#trPassword").show();
            }
            
        }
        else {
            $("#trLoginId").hide();
            $("#trPassword").hide();
        }
    });

    $('#btnNew').click(function () {
        isAdd = true;
        clearForm();
        $("#trPassword").hide();
        $("#trLoginId").hide();
        $("#trContact").show();
        $("#IsActive").prop("checked", true);        
        showCustomer();
        $("#CustomerNo").focus();
    });

    $('#btnImport').click(function () {
        location.href = "/Customer/Import";
    });

    

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


    $('#btnNameCheck').click(function () {
        location.href = "/Customer/DuplicatedNameCheck";      
    });
    

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

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

            if ($("#CanLogin").prop("checked")) {
                
                if ($("#Password").val() == "") {
                    $("#Password").addClass("redBorder");
                    SetErrorMsg("请填写初始登录密码","divCustomer");
                    return;
                }

            }
            synConfirm("确定保存吗？", function () {

                $.ajax({
                    url: "/Customer/Add",
                    type: 'POST',
                    cache: false,
                    data: {
                        CanLogin: $("#CanLogin").prop("checked"),
                        CustomerFullName: $("#CustomerFullName").val(),
                        CustomerShortName: $("#CustomerShortName").val(),
                        Address: $("#Address").val(),
                        Phone: $("#Phone").val(),
                        SearchKey: $("#SearchKey").val(),
                        Description: $("#Description").val(),
                        CustomerNo: $("#CustomerNo").val(),
                        LoginId: $("#LoginId").val(),
                        Password: $("#Password").val(),
                        UseBalanceFirst: $("#UseBalanceFirst").prop("checked"),
                        IsActive: $("#IsActive").prop("checked"),
                        contactName: $("#Contact").val(),
                        CategoryId: $("#CategoryId").val()

                    },
                    success: function (result) {
                        if (result.code == 0) {
                            closeCustomer();                           
                            location.href = location.href.replace("#", "");
                        }
                        else {
                            SetErrorMsg(result.message,"divCustomer");
                        }
                    },
                    error: function (e) {                        
                        SetErrorMsg("保存失败", "divCustomer");
                    }
                })
            });     
        }
        else {
            if (!checkRequired('divCustomer', 'errorMessage')) {
                return;
            }

            synConfirm("确定保存修改吗？", function () {
                $.ajax({
                    url: "/Customer/Update",
                    type: 'POST',
                    cache: false,
                    data: {
                        CanLogin: $("#CanLogin").prop("checked"),
                        CustomerFullName: $("#CustomerFullName").val(),
                        CustomerShortName: $("#CustomerShortName").val(),
                        Address: $("#Address").val(),
                        Phone: $("#Phone").val(),
                        SearchKey: $("#SearchKey").val(),
                        Description: $("#Description").val(),
                        CustomerNo: $("#CustomerNo").val(),
                        UseBalanceFirst: $("#UseBalanceFirst").prop("checked"),
                        IsActive: $("#IsActive").prop("checked"),
                        CategoryId: $("#CategoryId").val()
                    },
                    success: function (result) {
                        if (result.code == 0) {
                            closeCustomer();
                            location.href = location.href.replace("#", "");
                        }
                        else {
                            SetErrorMsg(result.message, "divCustomer");                             
                        }
                    },
                    error: function (e) {
                        SetErrorMsg("保存失败.","divCustomer");
                    }
                });
            });

           
        }
    });
});

function showCustomer() {
    $('#divCustomer').dialog('open');
}

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

function clearForm() {
    ClearErrorMsg();
    $("#divCustomer input").removeClass("redBorder");  
    $("#divCustomer input[type=text]").val("");       
    $("#divCustomer textarea").val("");  
    $("#divCustomer input[type=checkbox]").prop("checked", false);     
   
    $("#CustomerFullName").focus();
}
 
function ResetPassword(no,name) {
    $("#CustomerNo").val(no);
    $('#newPassword').val("");
    $('#divPassword').dialog('open');     
}

function SavePassword() {

    ClearErrorMsg("divPassword");

    if (checkRequired('divPassword', 'error-msg') == false) {
        return;
    }

    $.ajax({
        url: "/Customer/ResetPassword",
        type: 'POST',
        cache: false,
        data: { CustomerNo: $("#CustomerNo").val(), Password: $("#newPassword").val() },
        success: function (result) {
            if (result.code == 0) {
                $('#divPassword').dialog('close');
            }
            else {
                SetErrorMsg(result.message, "divPassword");
            }

        },
        error: function (e) {
            SetErrorMsg("密码重置失败", "divPassword");
        }
    });
}

function ShowContact(customerNo) {
    $.ajax({
        url: "/Customer/GetContactByCustomerNo",
        type: 'GET',
        cache: false,
        dataType: 'json',
        async: false,
        data: { CustomerNo: customerNo },
        success: function (result) {
            if (result.code == 0) {
                $('#divContact').dialog('open');
                var tbody = $("#contactList");
                $("#contactList").empty();
                var tr;
                var td;

                for (var r in result.data) {
                    tr = $("<tr></tr>");
                    td = $("<td></td>");
                    td.html(result.data[r].ContactName);
                    td.appendTo(tr);

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

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

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

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

                    td = $("<td></td>");
                    if (result.data[r].IsMain) {
                        td.html("是");
                        tr.css("background-color", "#2aaf59");
                        tr.css("color", "white");
                    }
                    else {
                        td.html("");
                    }

                    td.appendTo(tr);

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

                    tr.appendTo(tbody);
                }

            }
            else {
                alert("获取数据失败");
            }
        },
        error: function (e) {
            alert("获取数据失败");
        }
    });
}

function DeleteContact(ContactNo, t,customerNo) {

    synConfirm("确定删除联系人吗？", function () {
        $.ajax({
            url: "/Contact/Delete",
            type: 'POST',
            cache: false,
            data: { ContactNo: ContactNo },
            success: function (result) {
                if (result.code == 0) {
                    $(t).parent().parent().parent().find("tr[id='" + result.id + "']").remove();

                    var tList = $($("#C_" + customerNo).find("#contactList"));
                  
                    var contactNames = [];
                    $(tList.find("tr")).each(function () {
                        console.log(this);
                        contactNames.push($(this).find("td:eq(0)").html().trim());
                    });
               
                    JoinContactName(customerNo);
                }
                else {
                    alert(result.message);
                }

            },
            error: function (e) {
                alert('删除失败');
            }
        });
    });
    return false;
}

function clearContactForm() {
    ClearErrorMsg();

    $("#divContact #IsMain").click(function () { });
    $("#divContact input").removeClass("redBorder");
    $("#divContact input[type=text]").val("");    
}

function EditContact(ContactNo,CustomerNo,CustomerName) {
    isAdd = false;
    customerNo = CustomerNo;
    clearContactForm();

    $.ajax({
        url: "/Contact/GetContact",
        type: 'GET',
        cache: false,
        data: { ContactNo: ContactNo },
        success: function (result) {
            if (result.ContactNo != "") {
                $("#divContact #CustomerName").text(CustomerName);
                $("#divContact #ContactName").val(result.ContactName);
                $("#divContact #Phone").val(result.Phone);
                $("#divContact #Mobile").val(result.Mobile);
                $("#divContact #Email").val(result.Email);
                $("#divContact #CustomerNo").val(result.CustomerNo);
                $("#divContact #SearchKey").val(result.SearchKey);
                $("#divContact #ContactNo").val(result.ContactNo);
                $("#divContact #QQ").val(result.QQ);
                $("#divContact #Other").val(result.Other);

                if (result.IsMain) {
                    $("#IsMain").prop("checked", true);
                    //$("#IsMain").click(function (val) { return false; });
                }
                else {
                    $("#IsMain").prop("checked", false);
                }

                $('#divContact').dialog('open');
                $("#ContactName").focus();
            }

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

    return false;
}

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

        synConfirm("确定保存吗？", function () {

            $.ajax({
                url: "/Contact/Add",
                type: 'POST',
                cache: false,
                data: $('#formContact').serialize(),
                success: function (result) {
                    if (result.code == 0) {

                        
                        $('#divContact').dialog('close');

                        var tList =$($("#C_" + result.data.CustomerNo).find("#contactList"));
                                       

                        if (result.data.IsMain) {
                            $(tList.find("tr")).each(function () {
                                $($(this).find("td").get(5)).text("否");
                            });
                        }

                        var tr = $("<tr id='" + result.data.ContactNo + "'></tr>")
                        $("<td>" + CheckNull(result.data.ContactName) + "</td>").appendTo(tr);
                        $("<td>" + CheckNull(result.data.Phone) + "</td>").appendTo(tr);
                        $("<td>" + CheckNull(result.data.Mobile) + "</td>").appendTo(tr);
                        $("<td>" + CheckNull(result.data.Email) + "</td>").appendTo(tr);
                        $("<td>" + CheckNull(result.data.QQ) + "</td>").appendTo(tr);
                        $("<td>" + (result.data.IsMain ? "是" : "否") + "</td>").appendTo(tr);
                        $("<td>" + CheckNull(result.data.Other) + "</td>").appendTo(tr);

                        var td = $("<td></td>")
                        var btn = $('<a href="javascript:void(0);">[编辑] </a>');
                        btn.click(function () {
                            EditContact(result.data.ContactNo, result.data.CustomerNo, $("#divContact #CustomerName").text());
                        });

                        btn.appendTo(td);

                        btn = $('<a href="javascript:void(0);">[删除]</a>');
                        btn.click(function () {
                            DeleteContact(result.data.ContactNo, btn);
                        });
                        btn.appendTo(td);
                        td.appendTo(tr);
                        tr.appendTo(tList);

                        TdRowOverOut("tContact");

                        JoinContactName(result.data.CustomerNo);    

                        $("#C_" + result.data.CustomerNo).show();
                    }
                    else {
                        SetErrorMsg(result.message, "divContact");                        
                    }
                },
                error: function (e) {
                    SetErrorMsg("保存失败", "divContact");                    
                }
            });
        });  
    }
    else {
        if (!checkRequired('divContact', 'errorMessage')) {
            return;
        }

        synConfirm("确定保存吗？", function () {
            $.ajax({
                url: "/Contact/Update",
                type: 'POST',
                cache: false,
                data: $('#formContact').serialize(),
                success: function (result) {
                    if (result.code == 0) {
                        $('#divContact').dialog('close');
                        var tr = $("#contactList tr[id='" + $("#ContactNo").val() + "']")[0];

                        if (result.data.IsMain) {
                            $($(tr).parent().find("tr")).each(function () {
                                $($(this).find("td").get(5)).text("否");
                            });
                        }

                        $($(tr).find("td").get(0)).html(result.data.ContactName);
                        $($(tr).find("td").get(1)).html(result.data.Phone);
                        $($(tr).find("td").get(2)).html(result.data.Mobile);
                        $($(tr).find("td").get(3)).html(result.data.Email);
                        $($(tr).find("td").get(4)).html(result.data.QQ);
                        $($(tr).find("td").get(5)).html(result.data.IsMain ? "是" : "否");
                        $($(tr).find("td").get(6)).html(result.data.Other);

                        JoinContactName(result.data.CustomerNo);
                    }
                    else {
                        SetErrorMsg(result.message, "divContact");
                    }
                },
                error: function (e) {
                    SetErrorMsg("保存失败", "divContact");
                }
            });
        });       
    }
}

function AddContact(CustomerNo,CustomerShortName) {
    isAdd = true;
    customerNo = CustomerNo;

    $("#divContact #CustomerNo").val(CustomerNo);
    $("#CustomerName").text(CustomerShortName);

    clearContactForm();    

    $('#divContact').dialog('open');
    $("#ContactName").focus();
}
 

function showContact(customerNo) {
    var tr = $("#C_" + customerNo);

    if (tr.css("display") == "none") {
        tr.show();    
    }
    else {
        tr.hide();       
    }    
}


function hideContact(customerNo) {
    var tr = $("#C_" + customerNo);

    tr.hide();
}

function downExcel() {
    location.href = "/Customer/GetCustomerExcel?Keywords=" + $("#Keywords").val() + "&sCategory=" + $("#sCategory").val() ;     
}

function JoinContactName(customerNo) {
    var tList = $($("#C_" + customerNo).find("#contactList"));

    var contactNames = [];
    $(tList.find("tr")).each(function () {
        console.log(this);
        contactNames.push($(this).find("td:eq(0)").html().trim());
    });       

     
    $("tr[id='" + customerNo + "'").find(".td-contact").find("a").text(contactNames.join('，'));    


}