//ajax请求后台数据
//url:请求地址
//data:请求参数
//successDo:请求成功后执行的方法
//backDo:请求成功后的回调方法
var gParaJson;//操作交互
var gOpenJson;//open之后的参数,打开后不变化
function ajax(url,data,successDo,callBackDo){
    $.ajax({
        url: url,
        data:data,
        cache:false,
        dataType:'json',
        async: true,
        success:function(data){
            ajaxSuccessDo(data,successDo,callBackDo);
        },
        error:function(re,err){
            alert("error:"+err);
        }
    });
}
//ajax调用成功后执行的默认方法
function ajaxSuccessDo(data,successDo,callBackDo){
    closeInteractive();
    successDo(data);
    refresh(data);

    if(callBackDo != undefined){
        callBackDo(data);
    }
}

//创建流程实例
function startInstance(paraJson,callBack){
    var url="/hz7sp2/horizon/workflow/support/startInstance.wf";//请求地址,确定的地址
    // http://192.168.2.63:9000/hz7sp2/horizon/workflow/support/startInstance.wf?flowId=SUB02
    ajax(url,paraJson,startInstanceSuccessDo,callBack);
}
//打开流程实例
function openInstance(paraJson,callBack){
    var url="/hz7sp2/horizon/workflow/support/openInstance.wf";//请求地址,确定的地址
    ajax(url,paraJson,openInstanceSuccessDo,callBack);
}
//实例操作
function operatorInstance(paraJson,callBack) {
    var url="/hz7sp2/horizon/workflow/support/easyaction.wf";
    ajax(url,paraJson,operatorInstanceSuccessDo,callBack);
}

//创建流程实例返回结果处理
function startInstanceSuccessDo(data){
    gOpenJson = data;
    //从返回值中获取workid
    valueToInput();
    //显示按钮
    $("#divBtns").html("");//清空显示区域
    makeBtnHtml();
    //显示执行信息
    showInteractive(gOpenJson['flowMsg'] );
}

//创建流程实例返回结果处理
function openInstanceSuccessDo(data){
    gOpenJson = data;
    //从返回值中获取按钮信息并显示在divBtns中
    //也可能是返回选择路径的信息
    //判断openType
    if(gOpenJson['openType'] == "false"){
        makeOpenSel();
        return;
    }
    valueToInput();
    //显示按钮
    $("#divBtns").html("");//清空显示区域
    makeBtnHtml();
    showInteractive("打开完毕!");
}
//打开实例有多个分支时,选择处理
function makeOpenSel() {
    var selNodes = gOpenJson['selectNodes'];
    var sHtml = "请选择打开的节点:";
    for(var i=0,n=selNodes.length;i<n;i++){
        sHtml += '<br><input type="radio" name="selTrackId" value="'+selNodes[i]['nodeId']+'">'
            + showSelectText(selNodes[i]['nodeName']);
    }
    sHtml += '<br><input type="button" value="确定" onclick=okSel()>';
    $("#divBtns").html(sHtml);
}
//多个活动节点时的选择确定
function okSel() {
    var trackId = $('input:radio[name="selTrackId"]:checked').val();
    gOpenJson['trackId'] = trackId;
    openInstance(gOpenJson);
}
//存储信息到页面上
function valueToInput() {
    // $('input[name="workId"]').val(gOpenJson['workId']);
    // $('input[name="trackId"]').val(gOpenJson['flowNode']['trackId']);
    // $('input[name="nodeId"]').val(gOpenJson['flowNode']['nodeId']);
}
//打开实例后的操作按钮生成
function makeBtnHtml() {
    var btns =gOpenJson['flowButtons'];
    if(btns == null){
        return;
    }
    for(var i=0,n=btns.length;i<n;i++){
        var btn = btns[i];
        var btnHtml = '<input type="button" value="'+btn['buttonName']
            +'" onclick="actionClick(this)" ' +
            ' btnid="'+btn['buttonId']+'" buttonclass="'+btn['buttonClass']+'">';
        $("#divBtns").append(btnHtml);
    }
//    隐藏启动按钮
    $('#divStart').hide();
}
//按钮操作点击时执行
function actionClick(obj) {
    //把打开后的json赋值给操作交互用的json
    gParaJson = JSON.parse(JSON.stringify(gOpenJson));
    //操作id
    var btnId = obj.getAttribute('btnid');
    //操作执行类名称
    var btnClass = obj.getAttribute('buttonclass');

    //转换为json对象,方便获取信息
    gParaJson["operate"]=btnId;
    gParaJson["operateClazz"]=btnClass;
    gParaJson["operateFlag"]= 0;
    //此处需要对操作进行分类处理,有些操作需要先进行人员选择或者是
    if(btnId == "freesubmit"){
        freeSubmitHtml();
        return;
    }
    processOk();
}
//操作过程中的参数整合
function processOk(){
    var paraJson = {
        workId:gOpenJson['workId'],
        userId:gOpenJson['flowUser']['userId'],
        nodeId:gOpenJson['flowNode']['nodeId'],
        nodeName:gOpenJson['flowNode']['nodeName'],
        trackId:gOpenJson['flowNode']['trackId'],
        authorKey:gOpenJson['authorKey'],
        actionData: JSON.stringify(gParaJson)
    };

    operatorInstance(paraJson);
}
//创建流程实例返回结果处理
function operatorInstanceSuccessDo(data){
    gParaJson = data;
    showInteractive(gParaJson['operateMsg']);
    //根据返回值,进行交互信息的处理
    if(gParaJson['operateStatus'] == 'success'){
        $("#divBtns").html("");
        $('#divStart').show();
        return;
    }
    else if(gParaJson['operateStatus'] == 'error') {

        return;
    }
    if(gParaJson['operateStatus'] == 'selectSubflow'){
        makeSelectSubFlowHtml();
        return;
    } else if(gParaJson['operateStatus'] == 'showSubflow'){
        makeSelectSubFlowHtml();
        return;
    }

    makeSelectNodeHtml();

}
//需要选择节点/选择办理人时的处理
function makeSelectNodeHtml() {
    var nodes = gParaJson['nextNodes'];
    // $('#divInteractive').html(gParaJson['operateMsg']);//清空交互区
    var groups = "";
    var hasCheck = false;
    for(var i=0,n=nodes.length;i<n;i++){
        var selHtml = "";
        var group = nodes[i]['nodeGroup'];
        if(group ==""){
            hasCheck = true;
            selHtml += '<br><input type="checkbox" name="ckSelectNode" value="'+
                nodes[i]['selectId']+'" '+(nodes[i]['isSelect'] == 'true'?'checked disabled':'')+
                ' onclick="ckCheck(this,'+i+')" />'
                + showSelectText(nodes[i]['selectName']) ;
        }
        else{
            if(groups.indexOf(group+";") == -1){
                groups += group + ";";
            }
            selHtml += '<br><input type="radio" name="'+group+'" value="'+
                nodes[i]['selectId']+'" '+(nodes[i]['isSelect'] == 'true'?'checked disabled':'')+
                ' pos="'+i+'"/>'
                + showSelectText(nodes[i]['selectName']);
        }
        if(nodes[i]['isSelect'] == "true"){
            selHtml += makeNodeAuthor(nodes[i],i);
        }

        $('#divInteractive').append(selHtml);
    }

    $('#divInteractive').append('<br><input type="button" value="确定" onclick=okSet(\"'+groups+'\")>');
}
//选择节点的下一步
function okSet(groups) {
    checkRadioNextNodeids(groups);

    processOk();
}
//多选时,点击执行,直接修改json
function ckCheck(tar,index) {
    var selNode = gParaJson['nextNodes'][index];
    selNode['isSelect'] = ""+tar.checked;
    refresh(gParaJson);
}
//单选在确定后执行修改json
function checkRadioNextNodeids(groups) {
    if(groups != ""){
        var groupA = groups.split(";");
        for(var i=0,n=groupA.length;i<n;i++){
            if(groupA[i] == ""){
                continue;
            }
            var index = $('input:radio[name=\"'+groupA[i]+'\"]:checked').attr('pos');
            if(index != null){
                gParaJson['nextNodes'][index]['isSelect'] = "true";
            }
            else{
                //是否必须选择,可以修改为return来处理
            }
        }
    }
}
//办理人的显示处理
function makeNodeAuthor(node,i) {
    var sHtml = "";
    //只显示主办,如果需要读者和协办,请自行添加
    var author = node['authors']['Author'];
    if(author == undefined){//阅知时,只有reader
        author = node['authors']['Reader'];
    }
    var authorId = author['selectAuthor'];
    var authorName = author['selectAuthorName'];
    if(author['isSelect'] == "true"){
        sHtml += '<br>请指定'+author['authorName']+'(';
        sHtml += (author['selectType']=='checkbox'?'可指定多个':'只允许一个') ; //selectType标记是否允许多个
        sHtml += (author['isUser']=='true'?'人':'组织或者人');                 //isUser标记是否只能指定人,
        sHtml +=  author['isFree'] == 'true'?',可以从所有组织列表中选择'         //isFree 标记是否允许选择任何组织
            :author['isDefUser'] == 'true'?',仅允许从下面列表中选择':'';//isDefUser标记是否有指定的范围
        sHtml += ')';
        //从流程定义中获取到的可选列表
        if(author['isDefUser'] == 'true'){
            sHtml += '<br>可供选择的列表如下:';
            var initAuthors = author['initAuthor']['others'];
            for(var k=0,n=initAuthors.length;k<n;k++){
                sHtml += '<br>==>' + initAuthors[k]['name']+'('+initAuthors[k]['userFromName']+')['
                    + initAuthors[k]['id']+'/'+initAuthors[k]['userFromId'] +']';
            }
        }

        //人员临时存放的地方,如果挂接选择人员的插件,则可以使用hidden,并从插件中接收返回值
        sHtml += ')<br><input type="text" value="'+(authorId!=null?authorId:"")+'" name="'+node['nodeKey']
            +'"  onchange="chgAuthor(this,\'Author\','+i+')">';
    }
    else{
        sHtml += "<br>主办人:"+authorName;//不需要选择人员时,只显示
    }
    return sHtml;
}
//办理人变化时的处理
function chgAuthor(tar,authorType,index) {
    var selNode = gParaJson['nextNodes'][index];
    var author = selNode['authors'][authorType];
    author['selectAuthor'] = tar.value;

    refresh(gParaJson);
}

//自由提交时需要先确定节点名称和位置,以及办理人
function freeSubmitHtml() {
    var  sHtml = "<br>请指定节点名称:<input type='text' name='nodename' value=''>";
    sHtml += '<br>请指定办理人:<input type="text" name="author" value="">';
    sHtml += '<br><input type="button" onclick="freeOk()" value="确定">';
    showInteractive(sHtml);
}
function freeOk() {
    var nodeName = $('input[name="nodename"]').val();
    var author = $('input[name="author"]').val();
    if(nodeName == "" || author ==""){
        alert("请输入节点名称和办理人.");
        return;
    }
    var freeNode =
        {
            nodeName:nodeName,
            axisX: '',                  //下一节点坐标设置,默认为x向右移动150
            axisTypeX: 'absolute-x',
            axisY: '',
            axisTypeY: 'absolute-y',
            authors:{Author:{authorId:'Author',selectAuthor:author}}
        };

    //设置自由提交时的参数
    gParaJson['freeNode'] = freeNode;
    processOk();
}

//=====================================================================================
//启动子流程时,选择子流程处理
function makeSelectSubFlowHtml() {
    var subFlows = gParaJson['subFlows'];
    var sHtml = "请选择要启动的子流程";
    for(var i=0,n=subFlows.length;i<n;i++){
        if(subFlows[i]['selectType'] =='radio') {
            sHtml += '<br><input type="radio" name="selSubFlow" value="' + subFlows[i]['subFlowId']
                + '" pos="' + i + '">'
                + showSelectText(subFlows[i]['subFlowName']);
        }
        else{
            numCheck = 0;   //记录多选时的数量
            sHtml += '<br><input type="checkbox" name="selSubFlow" value="' + subFlows[i]['subFlowId']
                + '"  onclick="ckSelSubFlow(this,'+i+')">'
                + showSelectText(subFlows[i]['subFlowName']);
        }
        if(subFlows[i]['authors']['isSelect'] == "true"){
            sHtml += '<br>指定启动子流程的人员id[';
            sHtml += subFlows[i]['authors']['selectType'] == 'checkbox' ?'可指定多个':'仅可指定一个';
            sHtml += subFlows[i]['authors']['isUser'] == 'false'?'组织或者人]':'人]';
            sHtml += '<br><input type="text" name="'+subFlows[i]['subFlowId']+'" value=""' +
                ' onchange="startAuthor(this,'+i+')">'
        }

        //已经启动的子流程列表
        var subWorks = subFlows[i]['subWorks'];
        if(subWorks != null){
            sHtml += "<br>已经启动的子流程实例列表:";
            for(var work in subWorks){
                sHtml += "<br>"+subWorks[work] +"[wokid:" + work+"]";
            }
        }
    }

    sHtml += '<br><input type="button" value="确定" onclick=okSubFlow()>';

    $('#divInteractive').append(sHtml);
}
function startAuthor(tar,index) {
    var subFlow = gParaJson['subFlows'][index];
    subFlow['authors']['selectAuthor'] = tar.value;

    refresh(gParaJson);
}
var numCheck = 0;   //记录多选时的数量
function ckSelSubFlow(tar,index) {
    gParaJson['subFlows'][index]['isSelect'] = tar.checked;
    tar.checked ? numCheck ++ : numCheck --;

    refresh(gParaJson);
}
function ckSingleSubFlow() {
    var pos = $('input:radio[name="selSubFlow"]:checked').attr('pos');
    if(pos == null){
        //没有单选的情况下,判断checkbox是否有选中
        if(numCheck ==0){
            alert("请选择子流程");
            return false;
        }
        return true;
    }
    gParaJson['subFlows'][pos]['isSelect'] = true;
    return true;
}
function okSubFlow() {
    if(!ckSingleSubFlow()){
        return;
    }
    var paraJson = {
        workId:gParaJson['workId'],
        nodeId:gParaJson['nodeId'],
        trackId:gParaJson['trackId'],
        actionData: JSON.stringify(gParaJson)
    };
    operatorInstance(paraJson);
}
function showSelectText(txt) {
    return '<span onclick="this.previousSibling.click()">'+txt+'</span>';
}

//为了显示交互时的变化
function  refresh(json) {
    $("#resultJson").val(JSON.stringify(json));
}
//清空交互区域,意味这结束,如果是弹出或者浮动则需要关闭或者隐藏
function closeInteractive() {
    $('#divInteractive').html("");
}
//重新赋值,意味着要显示此区域
function showInteractive(html) {
    $('#divInteractive').html(html);
}

//===============================================================
//页面启动流程按钮调用
function startClick(){
    var sHtml = '<br>请输入要启动的流程ID:<input type="text" name="flowId" value="" >';
    sHtml += '<input type=button value="确定" onclick="startOk()">';

    $('#divInteractive').html(sHtml);
}
function startOk(){
    var flowId = $('input[name="flowId"]').val();
    if(flowId == null || flowId == undefined){
        alert("请输入流程id");
        return;
    }
    var paraJson = {flowId:flowId,
        userId:$('input[name="userId"]').val(),
        userName:$('input[name="userName"]').val(),
        subjection:$('input[name="subjection"]').val(),
        deptName:$('input[name="deptName"]').val()
    };//参数JSON
    startInstance(paraJson,startAfter);
}
//如果需要获取其他信息,可以指定回调方法
function startAfter(data){
    //data为创建实例返回的json数据,从中可以获取到需要的信息
    // alert(data['flowId']+"实例创建成功!");
    $('#divInteractive').html(data['workId']+"实例创建成功!");
}
//页面打开实例按钮调用
function openClick() {
    var sHtml = '<br>请输入要操作的实例ID:<input type="text" name="workId" value="" style="width: 300px">';
    sHtml += '<input type=button value="确定" onclick="openOk()">';

    $('#divInteractive').html(sHtml);
}
function openOk(){
    var workId = $('input[name="workId"]').val();
    if(workId == null || workId == undefined){
        alert("请输入要打开操作的实例id");
        return;
    }
    var paraJson = {workId:workId,
        userId:$('input[name="userId"]').val(),
        userName:$('input[name="userName"]').val(),
        subjection:$('input[name="subjection"]').val(),
        deptName:$('input[name="deptName"]').val()
    };
    openInstance(paraJson,openAfter);
}
//如果需要获取其他信息,可以指定回调方法
function openAfter(data){
    //data为打开实例返回的json数据,从中可以获取到需要的信息
    // alert(data['workId']+"实例打开成功!");
}

function clearDefault() {
    $('input[type=text]').val('');
}

function reDefault() {
    $('input[name="userId"]').val('HZ28821856ef63420156ef6342a20002');
    $('input[name="userName"]').val('用户01');
    $('input[name="subjection"]').val('D_HZ28821856ef63420156ef6342a20001');
    $('input[name="deptName"]').val('测试部门01');
}