var allCustomer = [];
var bodySteps ;
var bodyUsers;

$(function () {

    bodySteps = $("#tbody-step");
    bodyUsers = $("#tbody-user");

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

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

    $.ajax({
        url: "/Order/GetAutoCompleteCustomer",
        type: 'GET',
        cache: false,
        dataType: 'json',
        async: false,
        success: function (result) {
            for (var i in result.data) {
                allCustomer.push({ label: result.data[i].ItemText, value: result.data[i].ItemValue });
            }
        },
        error: function (e) {
        }
    });

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

    $("#tOrder tr td").click(function () {
        if ($(this).hasClass("text-center")) {
            return;
        }        
        else if ($(this).hasClass("td-last") || $(this).hasClass("td-checkbox")) {
            return;
        }
        else {
            ShowDetail($(this).parent().attr("id"));
        }
    });

    $("#divCT #orderCtRatio").change(function () {
        OrderCtRatioChange();
    });

    $("#divCT input[name=orderCtType]").change(function () {
        OrderCtRatioChange();
    });

    $("#divCT #orderCtAmount").change(function () {
        TotalCtAmountChange();
    }); 
    
    TdRowOverOut("tOrder");      
    SetSpanColor("tOrder"); 

});

function CtSetting(orderNo) {
    ClearErrorMsg("divCT");
    $("#divCT #orderNo").val(orderNo);
    $.ajax({
        url: "/Finance/GetOrderPerformance",
        type: 'GET',
        cache: false,
        dataType: 'json',
        data:{orderNo:orderNo},
        success: function (result) {
            if (result.code == 0) {
                FillTable(result.data);
                setUserColor();
                setCtStatus();
                fillDropdownList(result.data);
                fillMemo(result.data.Memo);

                $('#divCT').dialog('open');
            }
           
        },
        error: function (e) {
        }
    }); 
} 


function showMemo() {

    var tbody = $("#tbody-memo");
    if (tbody.css("display") == "none") {
        tbody.css("display", "");
        $("#tr-memo").css("display", "");
        $("#img-memo").attr("src", "../../Images/grid/ExpandedBlockStart.gif");
    }
    else {
        tbody.css("display", "none");
        $("#tr-memo").css("display", "none");
        $("#img-memo").attr("src", "../../Images/grid/ContractedBlock.gif");
    }
}

function fillMemo(memo) {
    var tbody = $("#tbody-memo");
    tbody.empty();

    $("#img-memo").attr("src", "../../Images/grid/ContractedBlock.gif");
    $("#tr-memo").css("display", "none");
    tbody.css("display", "none");

    $(memo).each(function (i, v) {
        var tr = NewTr();
        var td = NewTd().html(v.ItemText);
        td.appendTo(tr);
        td = NewTd().html(v.ItemValue);
        td.appendTo(tr);
        td = NewTd().html(v.Addition1);
        td.appendTo(tr);

        tr.appendTo(tbody);

    });
}

function getAutoCt() {
    ClearErrorMsg("divCT");
    var orderNo = $("#divCT #orderNo").val();
   
    $.ajax({
        url: "/Finance/GetAutoPerformance",
        type: 'GET',
        cache: false,
        dataType: 'json',
        data: { orderNo: orderNo },
        success: function (result) {
            if (result.code == 0) {
                FillTable(result.data);
                setUserColor();
                setCtStatus();
                fillDropdownList(result.data);                 
            }           

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

function FillTable(data) {     

    $("#divCT #orderNo").text(data.OrderNo);
    $("#divCT #customerName").text(data.CustomerName);
    $("#divCT #transactionDate").text(data.TransactionDate);    
    $("#divCT #completeDate").text(data.CompleteDate);
    $("#divCT #orderName").text(data.OrderName);
    $("#divCT #orderAmount").text(data.OrderAmount);
    $("#divCT #orderProfit").text(data.OrderProfit); 

    $("#divCT #orderCtRatio").val(data.CtRatio); 
    $("#divCT #orderCtAmount").val(data.CtAmount);     

    if (data.CtType == 1) {
        $("#divCT input[name=orderCtType][value='1']").prop("checked",true);
    }
    else {
        $("#divCT input[name=orderCtType][value='2']").prop("checked", true);
    }

    bodySteps.empty();
    bodyUsers.empty();

    $(data.Steps).each(function (i, v) {
        var tr = NewTr().attr("id",v.StepNo);
        NewTd().text(v.StepName).appendTo(tr);

        var td = NewTd().addClass("text-center");
        var chk = NewCheckbox().prop("checked", v.CtInvolved);
        chk.click(function () {
            stepCtStatusChange(v.StepNo, $(this).prop("checked"));            
        });
        chk.appendTo(td);
        td.appendTo(tr);

        td = NewTd().addClass("text-center");
        var text = NewTextbox().addClass("ct-ratio").val(v.CtRatio);
        text.appendTo(td);
        text.change(function () {
            StepCtRatioChange(this);
        });
        $("<span> %</span>").appendTo(td);
        td.appendTo(tr);

        td = NewTd().addClass("text-center");
        text = NewTextbox().addClass("ct-amount").val(v.CtBase);
        text.change(function () {
            StepCtAmountChange(this);
        });
        text.appendTo(td);
        td.appendTo(tr);
       
        tr.appendTo(bodySteps);
        

    });

    $(data.Users).each(function (i, v) { 
        AddUserTr(v).appendTo(bodyUsers);
       
    });

    setInputMask();

    CalculateTotalCtAmout();
}

function AddUserTr(v) {

    var tr = NewTr().attr("id", v.OrderUserId).attr("data-step", v.StepNo).
        attr("data-user", v.UserId).
        attr("data-is-main", v.IsMain);
    NewTd().text(v.StepName).appendTo(tr);
    NewTd().text(v.UserName).appendTo(tr);

    var td = NewTd().addClass("text-center");
    var chk = NewCheckbox().prop("checked", v.CtInvolved);
    chk.click(function () {
        userCtStatusChange(v.StepNo, v.UserId, $(this).prop("checked"));
    });
    chk.appendTo(td);
    td.appendTo(tr);

    td = NewTd().addClass("text-center");
    var text = NewTextbox().addClass("ct-ratio").val(v.CtRatio);
    text.appendTo(td);
    text.change(function () {
        UserCtRatioChange(this);
    });
    $("<span> %</span>").appendTo(td);
    td.appendTo(tr);

    td = NewTd().addClass("text-center");
    text = NewTextbox().addClass("ct-amount").val(v.CtAmount);
    text.change(function () {
        CalculateTotalCtAmout();
    });
    text.appendTo(td);
    td.appendTo(tr);

    var aDelete = $("<a href='#'>删除</a>");
    aDelete.click(function () {
        if ($(this).parent().parent().attr("data-is-main") == "true") {
            alert("只能删除协作者，经办人无法删除");
            return;
        }
        if ($(this).parent().parent().attr("id")=="0") {
            $(this).parent().parent().remove();
        }
        else {
            $(this).parent().parent().css("display", "none");
        }        

        CalculateTotalCtAmout();
    });
    var td = NewTd().addClass("text-center");
    aDelete.appendTo(td);
    td.appendTo(tr);

    return tr;
}

function setCtStatus() {

    var trs= $("#divCT #tbody-step tr");
    $(trs).each(function (i, v) {
        var status = $(v).find("input[type='checkbox']").prop("checked");
        if (status) {
            $(v).find("input[type='text']").removeAttr("readonly");
        }
        else {
            $(v).find("input[type='text']").attr("readonly", "readonly");
        }
    });

    trs = $("#divCT #tbody-user tr");
    $(trs).each(function (i,v) {
        var status = $(v).find("input[type='checkbox']").prop("checked");
        if (status) {
            $(v).find("input[type='text']").removeAttr("readonly");
        }
        else {
            $(v).find("input[type='text']").attr("readonly", "readonly");
        }
    });
}

function fillDropdownList(data) {
    var selStep = $("#divCooperators #selStep");
    var seleUser = $("#divCooperators #selUser");

    selStep.empty();
    seleUser.empty();

    $("<option value=''> </option>").appendTo(selStep);
    $("<option value=''> </option>").appendTo(seleUser);

    $(data.Steps).each(function (i, v) {
        $("<option></option>").val(v.StepNo).text(v.StepName).appendTo(selStep);
    });

    $(data.AvailableUsers).each(function (i, v) {
        $("<option></option>").text(v.ItemText).val(v.ItemValue).appendTo(seleUser);
    });
}

function SaveCooperator() {
    if (!checkRequired("divCooperators", "error-msg")) {
        return;
    }

    var userId = $("#divCooperators #selUser").val();
    var stepNo = $("#divCooperators #selStep").val();

    if (checkUserEixsted(userId, stepNo)) {
        SetErrorMsg("协作者已存在，无需重复添加","divCooperators");
        return;
    }

    var newUser = {
        OrderUserId: 0, StepNo: stepNo, StepName: $("#divCooperators #selStep option:selected").text(),
        UserId: userId, UserName: $("#divCooperators #selUser option:selected").text(),
        IsMain: false, IsCooperator: true, CtRatio: null, CtBase: null, CtAmount: null, StepSN: '', CtInvolved: true
    };
    
    var trs = $("#divCT #tbody-user tr");
    $(trs).each(function (i, v) {
        if ($(v).attr("data-step") == newUser.StepNo) {
            AddUserTr(newUser).insertAfter($(v));
            $('#divCooperators').dialog('close');
            setUserColor();
            return false;
        }
    });

    setInputMask();
}

function checkUserEixsted(userId,stepNo) {
    var trs = $("#divCT #tbody-user tr");
    var existed = false;
    $(trs).each(function (i, v) {
        if ($(v).attr("data-step") == stepNo && $(v).attr("data-user")==userId && $(v).css("display")!="none") {
            existed = true;
            return false;
        }       
    });

    return existed;
}

function addCooperator() {
    $("#divCooperators #selStep").val("");
    $("#divCooperators #selUser").val("");

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

function setUserColor() {
    var trs = $("#divCT #tbody-user tr");
    var stepNo = "";
    var colors = ["tr-color-0", "tr-color-1"]; 
    var colorIndex = 0;
    trs.removeClass(colors[0]);
    trs.removeClass(colors[1]);

    $(trs).each(function (i, v) {
        if (i == 0) {
            $(v).addClass(colors[colorIndex]);
            stepNo = $(v).attr("data-step");
            return true;
        }

        if ($(v).attr("data-step") == stepNo ) {
            $(v).addClass(colors[colorIndex]);
        }
        else {
            colorIndex = colorIndex == 0 ? 1 : 0;
            $(v).addClass(colors[colorIndex]);
        }
        stepNo = $(v).attr("data-step");
    })
}

function setInputMask() {
    $("#divCT input[type=text]").inputmask({ 'mask': "9{0,9}[.9{0,2}]", greedy: false });
}

function stepCtStatusChange(stepNo,status) {
    var stepTr = bodySteps.find("tr[id='" + stepNo + "']");
    var stepTexts = stepTr.find("input[type=text]");
    if (status) {
        stepTexts.removeAttr("readonly");
    }
    else {
        stepTexts.attr("readonly", "readonly");
        stepTexts.val("");
        var userTrs = bodyUsers.find("tr[data-step='" + stepNo + "']");
        $(userTrs).each(function (i, v) {
            $(v).find("input[type=checkbox]").prop("checked", false);
            userCtStatusChange($(v).attr("data-step"), $(v).attr("data-user"), false);
        });
        
    }
}

function userCtStatusChange(stepNo, userId, status) {
    
    var userTr = bodyUsers.find("tr[data-user='" + userId + "'][data-step='" + stepNo + "']");
    var userTexts = userTr.find("input[type=text]");
    if (status) {
        userTexts.removeAttr("readonly");       
    }
    else {
        userTexts.attr("readonly", "readonly");
        userTexts.val("");
    }
}

function TotalCtAmountChange() {
    var stepRatios = bodySteps.find(".ct-ratio");
    $(stepRatios).each(function (i, v) {
        StepCtRatioChange(v);
    });
}

function StepCtRatioChange(textbox) {
    var orderCtAmount = $("#divCT #orderCtAmount").val();
    if (orderCtAmount=="") {
        return;
    }

    if (!$(textbox).parent().parent().find("input[type=checkbox]").prop("checked")) {
        return;
    }

    orderCtAmount = parseFloat(orderCtAmount);    

    var ratio = $(textbox).val();
    if (ratio == "") {
        ratio = 0;      
    }
    else {
        ratio = parseFloat(ratio);
    }

    var stepCtAmountText = $(textbox).parent().parent().find(".ct-amount");
    if (ratio) {
        stepCtAmountText.val(FixTwoDecimal(orderCtAmount * ratio / 100.0));
        StepCtAmountChange(stepCtAmountText);
    }
    else {
        stepCtAmountText.val("");
        StepCtAmountChange(stepCtAmountText);
    }
}

function StepCtAmountChange(textbox) {

    var stepNo = $(textbox).parent().parent().attr("id");
    var stepCtAmount = $(textbox).val();

    if (stepCtAmount=="") {
        stepCtAmount = 0;
    }    
    else {
        stepCtAmount = parseFloat(stepCtAmount);
    }

    var userTrs = bodyUsers.find("tr[data-step='" + stepNo + "']");
    $(userTrs).each(function (i, v) {
        if ($(v).css("display") == "none") {
            return;
        }
        if (!$(v).find("input[type=checkbox]").prop("checked")) {
            return;
        }

        var userCtRatio = $(v).find(".ct-ratio").val();
        if (userCtRatio=="") {
            return;
        }

        userCtRatio = parseFloat(userCtRatio);

        if (stepCtAmount && userCtRatio) {
            $(v).find(".ct-amount").val(FixTwoDecimal(stepCtAmount * userCtRatio /100.0) )
        }
        else {
            $(v).find(".ct-amount").val("");
        }
    });

    CalculateTotalCtAmout();
}

function UserCtRatioChange(textbox) {
    var stepNo = $(textbox).parent().parent().attr("data-step");
    var stepCtBase = GetStepCtBase(stepNo);
    console.log(stepCtBase);   

    var ratio = $(textbox).val();
    if (ratio == "") {
        ratio = 0;
    }
    else {
        ratio = parseFloat(ratio);
    }
    
    if (ratio && stepCtBase) {
        $(textbox).parent().parent().find(".ct-amount").val(FixTwoDecimal(stepCtBase * ratio / 100.0));       
    }
    else {
        $(textbox).parent().parent().find(".ct-amount").val("");
    }

    CalculateTotalCtAmout();
}

function OrderCtRatioChange() {
   
    var orderAmount = $("#divCT #orderAmount").text();
    var orderProfit = $("#divCT #orderProfit").text();
    var orderCtType = $("#divCT input[name=orderCtType]:checked").val();
    var orderCtRatio = $("#divCT #orderCtRatio").val();

    if (orderAmount == "") {
        orderAmount = 0;
    }
    else {
        orderAmount = parseFloat(orderAmount);
    }

    if (orderProfit == "") {
        orderProfit = 0;
    }
    else {
        orderProfit = parseFloat(orderProfit);
    }

    if (orderCtRatio == "") {
        orderCtRatio = 0;
    }
    else {
        orderCtRatio = parseFloat(orderCtRatio);
    }

    if (orderCtRatio) {
        console.log(1);
        if (orderCtType == "1") {
            if (orderAmount) {
                $("#divCT #orderCtAmount").val(FixTwoDecimal(orderAmount * orderCtRatio / 100.0));
            }
            else {
                $("#divCT #orderCtAmount").val("");
            }
            
        }
        else {
            if (orderProfit) {
                $("#divCT #orderCtAmount").val(FixTwoDecimal(orderProfit * orderCtRatio / 100.0));
            }
            else {
                $("#divCT #orderCtAmount").val("");
            }            
        }
    }
    else {
        $("#divCT #orderCtAmount").val("");
    }

    TotalCtAmountChange();
}
     
function CalculateTotalCtAmout() {
    
    var totalAmount = 0;
    var texts = bodyUsers.find(".ct-amount");
    $(texts).each(function (i, v) {
        if ($(v).parent().parent().css("display") == "none") {
            return true;
        }
        if (!$(v).parent().parent().find("input[type=checkbox]").prop("checked")) {
            return true;
        }
        var amount = $(v).val();
        if (amount == "") {
            amount = 0;
        }
        amount = parseFloat(amount);
        totalAmount += amount;
    });

    totalAmount = totalAmount == 0 ? null : totalAmount;
    
    if (totalAmount != null) {
        $("#divCT #totalCtAmout").text(FixTwoDecimal(totalAmount));
    }
    else {
        $("#divCT #totalCtAmout").text("");
    }
    
}
 
function GetStepCtBase(stepNo) {
    var trs = $("#divCT #tbody-step tr");
    var result = null;
    $(trs).each(function (i, v) {
        if ($(v).attr("id") == stepNo) {
            result = $(v).find(".ct-amount").val();
            if (result && !isNaN(result)) {
                result = parseFloat(result);
            }
        }
    });

    return result;
}

function GetStepCtRatio(stepNo) {
    var trs = $("#divCT #tbody-step tr");
    var result = null;
    $(trs).each(function (i, v) {
        if ($(v).attr("id") == stepNo) {
            result = $(v).find(".ct-ratio").val();
            if (result && !isNaN(result)) {
                result = parseFloat(result);
            }
        }
    });

    return result;
}


function Save() {
    var model = {};

    model.OrderNo = $("#divCT #orderNo").val();
    model.CtType = $("#divCT input[name=orderCtType]:checked").val();
    model.CtRatio = $("#divCT #orderCtRatio").val();
    model.CtAmount = $("#divCT #orderCtAmount").val();

    model.Steps = [];
    model.Users = [];

    var trs = bodyUsers.find("tr");
    $(trs).each(function (i, v) {
        var u = {};
        u.OrderUserId = $(v).attr("id");
        u.StepNo = $(v).attr("data-step");
        u.UserId = $(v).attr("data-user");
        u.CtRatio = $(v).find(".ct-ratio").val();
        u.CtAmount = $(v).find(".ct-amount").val();
        u.CtBase = GetStepCtBase(u.StepNo);
        u.CtStepRatio = GetStepCtRatio(u.StepNo);
        u.CtInvolved = $(v).find("input[type=checkbox]").prop("checked");
        u.IsDeleted = $(v).css("display") == "none";

        model.Users.push(u);
    });

    $.ajax({
        url: "/Finance/SaveOrderPerformance",
        type: 'POST',
        cache: false,
        dataType: 'json',
        data: model,
        success: function (result) {
            if (result.code == 0) {
                $('#divCT').dialog('close');
                $("#tOrder tr[id='" + model.OrderNo + "']").find("#ct-status span").text("已分配");
                SetSpanColor();
            }
            else {
                SetErrorMsg("保存失败，请稍后再试", "divCT");
            }
        },
        error: function (e) {
            SetErrorMsg("保存失败，请稍后再试", "divCT");
        }
    });
}

function BatchProcess() {

    if (SelectedNumber() < 2) {
        alert('批量分配需要选择多条记录');
        return;
    }    

    synConfirm("确定批量分配绩效吗？<br>提示：所选记录将全部重新分配绩效。",
        function () {
            $.blockUI({ message: '<h5>处理中...</h5>' });
            $.ajax({
                url: "/Finance/BatchProcessOrderPerformance",
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: {
                    OrderNos: GetSelectedIds()                     
                },
                success: function (result) {
                    $.unblockUI();                    
                    if (result.code == 0) {
                        location.reload();
                    }
                    else {
                        alert("分配失败：<br>请在[系统参数]页面设置绩效提成比例。");
                    }
                },
                error: function (e) {
                    $.unblockUI();
                    alert("批量分配绩效失败，请稍后再试");
                }
            });
        });
}