var allAvailableCooperators = [];

$(function () {
    $('#divNextStep').dialog({
        width: 560,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });

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

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

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

    $("input[name=NextType]").click(function () {
        $("select").removeClass("redBorder");
        switch ($("input[name=NextType]:checked").attr("id")) {
            case "NextType1":
                $("#divNextStep #NextStep").show();
                $("#divNextStep #NextStep").change();
              
                break;
            case "NextType2":
                $("#divNextStep #NextStep").hide();
                $("#divNextStep #UserId").show();
                $("#divNextStep #trCooperators").hide();
                if (teamUsers != null) {
                    $("#divNextStep #UserId").empty();
                    $("#divNextStep #UserId").append("<option></option>");

                    for (var r in teamUsers) {
                        $("#divNextStep #UserId").append("<option value='" + teamUsers[r].ItemValue + "'>" + teamUsers[r].ItemText + "</option>");
                    }
                }
                break;
            default:
                break;
        }
    });

    $("#btnNextStepSave").click(function () {
        $("select").removeClass("redBorder");
        var nextType = $("input[name=NextType]:checked").val();
        var isEndPoint = $("#isEndPoint").val();

        if (nextType == "1") {
            if ($("#divNextStep #NextStep").val() == "") {
                $("#divNextStep #NextStep").addClass("redBorder");
                return;
            }

            if (isEndPoint == "0" && $("#divNextStep #UserId").val() == "") {
                $("#divNextStep #UserId").addClass("redBorder");
                return;
            }
        }
        else {
            if ($("#divNextStep #UserId").val() == "") {
                $("#divNextStep #UserId").addClass("redBorder");
                return;
            }
        }     

        var data = { NextType: nextType, WorkFlowStepNo: $("#divNextStep #NextStep").val(), UserId: $("#divNextStep #UserId").val(), cooperators:JSON.stringify(getExistedCooperators()) };
        if (isMultiple) {
             
            data.OrderNo = GetSelectedIds();
            data.checkMain = true;
        }
        else {
            data.OrderNo = $("#OrderNo").val();
            data.checkMain = false;
        }
        
        $("#btnNextStepSave").attr("disabled", "disabled"); 

        $.blockUI({ message: '<h5>请稍候...</h5>' });
        $.ajax({
            url: "/Order/OrderFlowToNext",
            type: 'POST',
            cache: false,
            dataType: 'json',
            async: false,
            data: data,
            success: function (result) {
                $.unblockUI();
                $("#btnNextStepSave").removeAttr("disabled"); 
                if (result.code == 0) {
                    $('#divNextStep').dialog('close');
                    window.location.reload();
                }
                else {
                    SetErrorMsg(result.message, "divNextStep");                    
                }
            },
            error: function (e) {
                $.unblockUI();
                 $("#btnNextStepSave").removeAttr("disabled"); 
                SetErrorMsg("保存失败", "divNextStep");                 
            }
        });
    });

    $("#NextStep").change(function () {
        $("select").removeClass("redBorder");
        $("#divNextStep #UserId").empty();
        $("#divNextStep #UserId").append("<option></option>");
        $("#divNextStep #isEndPoint").val("0");
        if ($("#divNextStep #NextStep").val() == "") {
            $("#divNextStep #UserId").hide();
            $("#divNextStep #trCooperators").hide();
            return;
        }

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

                }
            },
            error: function (e) {

            }
        });
    });

    $("#btnCurrentStepSave").click(function () {
        $("select").removeClass("redBorder");   

        var data = {cooperators: JSON.stringify(getExistedCurrentCooperators()) };        
        data.OrderNo = $("#OrderNo").val();     

        $.ajax({
            url: "/Order/ChangeCurrentStepCooperators",
            type: 'POST',
            cache: false,
            dataType: 'json',
            async: false,
            data: data,
            success: function (result) {
              
                if (result.code == 0) {
                    $('#divCurrentStep').dialog('close');
                    window.location.reload();
                }
                else {
                    SetErrorMsg("保存失败", "divNextStep");
                     
                }
            },
            error: function (e) {
                
                SetErrorMsg("保存失败", "divNextStep");
                
            }
        });
    });

});

function NextStep(id, multiple) {
    ClearErrorMsg();
    isMultiple = multiple;
    $("select").removeClass("redBorder");
    $("#OrderNo").val(id);
    $.ajax({
        url: "/Order/GetOrderNextStep",
        type: 'GET',
        cache: false,
        data: { OrderNo: id },
        success: function (result) {
            if (result.code == 0) {
               
                $("#divNextStep #NextStep").empty();
                $("#divNextStep #NextStep").append("<option></option>");
                $("#divNextStep #tdCurrentUser").text(result.data.UserName);
                $("#divNextStep #tdCurrentStep").text(result.data.StepName);
                $("#divNextStep #UserId").empty();

                teamUsers = result.data.TeamUserIds;
                for (var r in result.data.FollowUps) {
                    $("#divNextStep #NextStep").append("<option value='" + result.data.FollowUps[r].ItemValue + "'>" + result.data.FollowUps[r].ItemText + "</option>");
                }
                
                $("input[name='NextType']").eq(0).prop("checked",true); 
                $("input[name='NextType']").eq(1).prop("checked",false); 
                $("input[name='NextType']").eq(0).click();              

                var users = [];
                $(result.data.Cooperators).each(function (i, v) {
                    users.push(v.ItemText);
                });                

                $("#divNextStep #td-current-cooperators").text(users.join(", "));

                $('#divNextStep').dialog('open');
            }
            else {
                alert("获取信息失败.");
            }

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


function addCooperators() {
    var tbody = $("#divNextStepCooperators #tbodyAvailableCooperators");
    tbody.empty();

    var userId = $("#divNextStep #UserId").val();

    var tr, td;
    $(allAvailableCooperators).each(function (i, v) {

        if (v.ItemValue == userId) {
            return true;
        }

        tr = $("<tr></tr>");

        td = $("<td class='text-center'><input type='checkbox' value='" + v.ItemValue + "' /></td>");

        td.appendTo(tr);

        td = $("<td></td>");
        td.html(v.ItemText);
        td.appendTo(tr);

        console.log(tr);
        tr.appendTo(tbody);
    });


    if (tbody.find("tr").length == 0) {
        tbody.parent().hide();
        $("#divNextStepCooperators .no-avaliable-cooperators").show();
        $("#divNextStepCooperators #btnSaveCooperators").hide();
    }
    else {
        tbody.parent().show();
        $("#divNextStepCooperators .no-avaliable-cooperators").hide();
        $("#divNextStepCooperators #btnSaveCooperators").show();
    }

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

function getSelectedCooperators() {
    var result = [];
    
    var chks = $("#divNextStepCooperators #tbodyAvailableCooperators input[type=checkbox]");
    chks.each(function (i, v) {
        if ($(this).prop("checked")) {
            
            result.push({ ItemText: $(this).parent().parent().find("td:eq(1)").html(), ItemValue: $(this).val() });
        }
    });

    console.log(result);
    return result;
}

function getExistedCooperators() {
    var result = [];
    var users = $("#divNextStep #td-cooperators >div >span");
    $(users).each(function (i, v) {
        result.push({ ItemText: $(v).text(), ItemValue: $(v).attr("data-userId") });
    });

    return result;
}

function SaveCooperators() {
    var cooerators = getSelectedCooperators();
    var existed = getExistedCooperators();
    var container = ("#divNextStep #td-cooperators > div");
       
    $(cooerators).each(function (i, v) {

        var checkExisted = false;
        $(existed).each(function (x, y) {
            if (y.ItemValue == v.ItemValue) {
                checkExisted = true;
                return false;
            }
        });

        if (checkExisted) {
            return true;
        }

        var im = $("<i class='fa fa-minus-square' title='移除' style='cursor:pointer'></i>");

        im.click(function () {
            $(this).parent().remove();
        });       

        var span = $("<span></span>");
        span.text(v.ItemText);
        span.attr("data-userId", v.ItemValue);
        im.appendTo(span);
        span.appendTo(container);
    });

    $('#divNextStepCooperators').dialog('close');
}

function CurrentStep(id) {
    ClearErrorMsg();
    
    $("select").removeClass("redBorder");
    $("#OrderNo").val(id);

    $.ajax({
        url: "/Order/GetOrderCurrentStep",
        type: 'GET',
        cache: false,
        data: { OrderNo: id },
        success: function (result) {
            if (result.code == 0) {
               
                $("#divCurrentStep #tdCurrentUser").attr("data-userId",result.data.UserId);
                $("#divCurrentStep #tdCurrentUser").text(result.data.UserName);
                $("#divCurrentStep #tdCurrentStep").text(result.data.StepName); 

                teamUsers = result.data.TeamUserIds;
               
                GenerateCurrentCooperators(result.data.Cooperators); 

                $('#divCurrentStep').dialog('open');
            }
            else {
                alert("获取信息失败.");
            }

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

function GenerateCurrentCooperators(cooerators) {
  
    var container = $("#divCurrentStep #td-cooperators > div");
    container.empty();

    $(cooerators).each(function (i, v) {
      
        var im = $("<i class='fa fa-minus-square' title='移除' style='cursor:pointer'></i>");

        im.click(function () {
            $(this).parent().remove();
        });

        var span = $("<span></span>");
        span.text(v.ItemText);
        span.attr("data-userId", v.ItemValue);
        im.appendTo(span);
        span.appendTo(container);
    });
}

function addCurrentStepCooperators() {                        
    var tbody = $("#divCurrentStepCooperators #tbodyAvailableCooperators");
    tbody.empty();

    var userId = $("#divCurrentStep #tdCurrentUser").attr("data-userId");

    var tr, td;
    $(teamUsers).each(function (i, v) {

        if (v.ItemValue == userId) {
            return true;
        }

        tr = $("<tr></tr>");

        td = $("<td class='text-center'><input type='checkbox' value='" + v.ItemValue + "' /></td>");

        td.appendTo(tr);

        td = $("<td></td>");
        td.html(v.ItemText);
        td.appendTo(tr);
 
        tr.appendTo(tbody);
    });


    if (tbody.find("tr").length == 0) {
        tbody.parent().hide();
        $("#divCurrentStepCooperators .no-avaliable-cooperators").show();
        $("#divCurrentStepCooperators #btnSaveCooperators").hide();
    }
    else {
        tbody.parent().show();
        $("#divCurrentStepCooperators .no-avaliable-cooperators").hide();
        $("#divCurrentStepCooperators #btnSaveCooperators").show();
    }

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

function getSelectedCurrentCooperators() {
    var result = [];

    var chks = $("#divCurrentStepCooperators #tbodyAvailableCooperators input[type=checkbox]");
    chks.each(function (i, v) {
        if ($(this).prop("checked")) {

            result.push({ ItemText: $(this).parent().parent().find("td:eq(1)").html(), ItemValue: $(this).val() });
        }
    });

    
    return result;
}

function getExistedCurrentCooperators() {
    var result = [];
    var users = $("#divCurrentStep #td-cooperators >div >span");
    $(users).each(function (i, v) {
        result.push({ ItemText: $(v).text(), ItemValue: $(v).attr("data-userId") });
    });

    return result;
}

function SaveCurrentCooperators() {
    var cooerators = getSelectedCurrentCooperators();
    var existed = getExistedCurrentCooperators();
    var container = ("#divCurrentStep #td-cooperators > div");
         
    $(cooerators).each(function (i, v) {

        var checkExisted = false;
        $(existed).each(function (x, y) {
            if (y.ItemValue == v.ItemValue) {
                checkExisted = true;
                return false;
            }
        });

        if (checkExisted) {
            return true;
        }

        var im = $("<i class='fa fa-minus-square' title='移除' style='cursor:pointer'></i>");

        im.click(function () {
            $(this).parent().remove();
        });

        var span = $("<span></span>");
        span.text(v.ItemText);
        span.attr("data-userId", v.ItemValue);
        im.appendTo(span);
        span.appendTo(container);
    });

    $('#divCurrentStepCooperators').dialog('close');
}