<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8" %>
<%@include file="/WEB-INF/ehr/commons/jsp/commonInclude.jsp" %>

<script type="text/javascript" src="${staticRoot}/lib/jquery/jqueryform.js"></script>
<script type="text/javascript" src="${staticRoot}/lib/webuploader/webuploader.js"></script>
<script type="text/javascript" src="${staticRoot}/lib/webuploader/upload.js"></script>
<script type="text/javascript">

    /* *************************** 模块初始化 ***************************** */
    var fileType;
    var oldFileId;
    var oldFlowClassList = [];
    var editorFlow = {
        //form
        actionUrl: "${contextRoot}/flow/addFlow",
        index: 1,
        $mun: 0,//保存节点数量
        flowClassData: [],//节点数据
        init: function () {
            this.bindEvents();
            this.initForm();
        },
        initForm: function () {
            var me = this;
            var data;
            var iconUrl;
            var modelString = "${model.id}";
            if (modelString != undefined && modelString != null && modelString.length > 0) {
                $("#fileType").attr("disabled", "disabled");
                var icon = $("#iconUrl").attr("data-id");
                if (icon != '' && icon != 'undefine') {
                    if (icon != "${model.chart}") {
                        iconUrl = icon;
                    } else {
                        iconUrl = "${model.chart}";
                    }
                } else {
                    iconUrl = "${model.chart}";
                }
                //旧的流程图ID
                oldFileId = iconUrl;
                <%--var flowArray = ${flowClass};--%>
                <%--for(var index in flowArray){--%>
                    <%--var classPath = flowArray[index]['classPath'];--%>
                    <%--oldFlowClassList.push(classPath);--%>
                <%--}--%>

                var valid = "${model.valid}";
                liger.get("valid").selectValue(valid);
                fileType = "${model.fileType}";
                liger.get("fileType").selectValue(fileType);
                data = {
                    id: "${model.id}",
                    name: "${model.name}",
                    code: "${model.code}",
                    path: "${model.path}",
                    chart: iconUrl,
                    valid: "${model.valid}",
                    fileType: "${model.fileType}",
                    flowClassList: '${flowClass}',
                    flowClassArray: '${model.flowClassArray}',
                    flowTempArray: '${model.flowTempArray}',
                    createDate: '${model.createDate}'
                };

                me.actionUrl = "${contextRoot}/flow/updateFlow";
            } else {
                liger.get("valid").selectValue("1");//默认有效
                liger.get("fileType").selectValue("java");//默认java文件类型
//                liger.get("type").selectValue("route");//默认route
            }

            $("#div_info_form").ligerAutoForm({
                data: data,
                validate: {
                    name: "required",
                    code: "required"
                },

            });
            me.resolveFlow();
        },
        bindFlowClass: function (index) {
            var me = this;

            $("#type" + index).ligerComboBox({
                data: [ {"value": "processor", "code": "processor"},{"value": "route", "code": "route"}],
                cancelable: false,
                onSuccess: function (data) {
                }
            });

            var type = $("#type" + index).val();
            if (!type || type == '') {
                type = "route";
            }
            liger.get("type" + index).selectValue(type);
            if ("class" == fileType) {
                me.flowClassData[me.$mun] = {
                    "packageName": $("#packageName" + index).val(),
                    "className": $("#className" + index).val(),
                    "classPath": $("#classPath" + index).val(),
                    "flowId": $("#flowId").val(),//流程id
                    "type": $("#type" + index).val(),
                    "id": $("#classId" + index).val(),
                    "isUpdate": $("#isUpdate" + index).val()
                }
            } else if ("java" == fileType) {
                me.flowClassData[me.$mun] = {
                    "packageName": $("#packageName" + index).val(),
                    "className": $("#className" + index).val(),
                    "classPath": $("#classPath" + index).val(),
                    "flowId": $("#flowId").val(),//流程id
                    "type": $("#type" + index).val(),
                    "id": $("#classId" + index).val(),
                    "isUpdate": $("#isUpdate" + index).val()
                }
            }
            me.$mun += 1;
        },
        bindEvents: function () {
            var me = this;

            $(".m-form-bottom").on("click", "#btnSave", function () {
                fileType = liger.get("fileType").selectedValue;
                if ($("#iconUrl").val().indexOf("fakepath")>0) {
                    $.ligerDialog.error("请上传您选择的图片");
                    $("#iconUrl").addClass("required");
                    if (!$("#div_info_form").ligerAutoForm("validate")) {
                        return;
                    }
                    return;
                }

                if (!$("#div_info_form").ligerAutoForm("validate")) {
                    return;
                }
                var index = newMaxFormIndex();
                debugger
                for (var i = index; i > 0; i--) {
                    me.bindFlowClass(i);
                }

                var data = $("#div_info_form").ligerAutoForm("getData");
                delete data.file;
                var dataList;
                if ("java" == fileType) {
                    data.flowTempArray = me.flowClassData;
                    dataList = {"flowClass": JSON.stringify(data)}
                } else if ("class" == fileType) {
                    data.flowClassArray = me.flowClassData;
                    dataList = {"flowClass": JSON.stringify(data)}
                }

                var code = $("#code").val();
                var reg = /^[0-9a-zA-Z]+$/;
                if(!reg.test(code)){
                    return false;
                }

                $.ajax({ //ajax处理
                    type: "POST",
                    url: me.actionUrl,
                    dataType: "json",
                    data: dataList,
                    cache: false,
                    success: function (data) {
                        if (data.successFlg) {
                            parent.flow.dialogSuccess(data.message);
                        }
                        else {
                            $.ligerDialog.error(data.message);
                        }
                    },
                    error: function (data) {
                        $.ligerDialog.error("valid:" + data.valid + "(" + data.statusText + ")");
                    }
                });
            });

            $(".m-form-bottom").on("click", "#btnCancel", function () {
                parent.flow.dialog.close();
            });

            $("#valid").ligerComboBox({
                data: [{"value": "有效", "code": "1"}, {"value": "无效", "code": "0"}],
                cancelable: false,
                onSuccess: function (data) {
                }
            });
            $("#type").ligerComboBox({
                data: [{"value": "processor", "code": "processor"},{"value": "route", "code": "route"}],
                cancelable: false,
                onSuccess: function (data) {
                }
            });
            $("#fileType").ligerComboBox({
                data: [{"value": "java文件", "code": "java"}, {"value": "class文件", "code": "class"}],
                cancelable: false,
                onSuccess: function (data) {
                }
            });
            /* =====================添加新节点========================= */
            $(".m-form-group").on("click", "#btnAddClass", function () {
                var index = newMaxFormIndex();
                index++
                var html = '<div class="flows"  dataIndex="' + index + '" id="paramGroup' + index + '">' +
                        '<form id="form' + index + '" action="${contextRoot}/flow/parseFile" method="post" enctype="multipart/form-data">';

                html += '<div class="m-form-group" dataIndex="' + index + '"  ><label>类别 : </label><div class="m-form-control ">' +
                        '<div class="l-text"><input type="text" id="type' + index + '" class="l-text-field required" name="type"></div>' +
                        '</div></div>';

                html += '<div class="m-form-group" ><label>包名' + index + ' : </label><div class="m-form-control"  controlType="textbox" id="packName' + index + '_div" style="margin-left:0px;">' +
                        '<input type="text" id="packageName' + index + '"  class="l-textbox"/></div></div>';

                html += '<div class="m-form-group"   dataIndex="' + index + '" id="paramGroup' + index + '"><label>类名' + index + ' :</label>' +
                        '<div class="m-form-control"  controlType="textbox" id="className' + index + '_div" style="margin-left:0px;"> ' +
                        '<input type="text" id="className' + index + '"  class="l-textbox"/></div></div>';


                html += ' <div class="m-form-group"><label>源代码' + index + ' : </label><div class="m-form-control">';
                html += ' <input name="isUpdate" type="text" id="isUpdate' + index + '"   class="isUpdate" hidden="hidden"/>';
                html += ' <input type="text"  id="classPath' + index + '" name="classPath" class="l-textbox btnGrayUp" style="width: 144px;"  placeholder="点击选择源代码文件" readonly="readonly" data-id="">' +
                        ' <div style="float: right;">' +
                        ' <div  class="l-button l-button-no btnGrayDo' + index + '" data-id="' + index + '">' +
                        ' <span style="background-color: rgb(240, 240, 240);">导入</span> </div>' +
                        '<label id="say' + index + '"  class="say' + index + '" style="display: inline-block;width: 70px;"></label>' +
                        '</div><input type="file" name="file" style="display: none" id="file' + index + '" /></form>' +
                        '</div></div>';
                html += '<div class="m-form-group"><div class="m-form-control"><a class="m-btn-cancle" href="javascrip:void()" style="display:block;" onclick="$(\'#paramGroup' + index + '\').remove()"></a></div></div>';

                $("#classDiv").append(html);
                $("#type" + index).ligerComboBox({
                    data: [{"value": "processor", "code": "processor"},{"value": "route", "code": "route"}],
                    cancelable: false,
                    onSuccess: function (data) {
                    }
                });

                var type = $("#type" + index).val();
                if (!type || type == '') {
                    type = "processor";
                }

                liger.get("type" + index).selectValue(type);
                bindForm(index);
                bindUpload(index);
            });

            $("#formIcon").on("click", ".btnIconGrayUp", function () {
                var inputVal = $(this).closest("div").find("input[type=text]");
                var obj = $(this).closest("div").find("input[type=file]")
                obj.change(function () {
                    inputVal.val(obj.val());
                })
                obj.click();
            });

            $(".formIcon").bind("click", function () {
                var formId = '#formIcon';
                var formObj = $(formId);//要提交的表单
                var Obj = $(".formIcon");
                var upObj = formObj.closest("input").find(".btnIconGrayUp");//浏览的按钮
                var formsay = formObj.find(".sayformIcon");//提示文字
                if (formObj.closest("div").find("input[type=text]").val().length != 0 && formObj.closest("div").find("input[type=text]").val().indexOf("fakepath")>0) {//判断是否选择了文件
                    formsay.attr("class", "say true").html("上传中");
                    formObj.ajaxForm({
                        dataType: 'text',
                        type: "POST",
                        success: function processJson(data) {
                            debugger
                            formsay.attr("class", "say true").html("上传成功");
                            formObj.find("input[type=text]").attr("data-id", data)//设置已上传的文件的ID
                            formObj.find("input[type=text]").val(data)//设置已上传的文件的ID
                            formObj.closest("div").find("span").html("重新导入<i></i>");
                            // 上传成功后删除旧的
                            _deleteFileAfterUpdate(oldFileId);
                        },
                        error: function processJson(data) {
                            debugger
                            formsay.attr("class", "say false").html("上传失败");
                        }
                    });
                    formObj.submit();
                } else {
                    $.ligerDialog.error("请选择要上传的文件");
                }
            });

            /* ===================== 文件预览 动态绑定事件========================== */

            /* =====================上传文件 原数据绑定=========================== */
            var index = newMaxFormIndex();
            for (var i = index; i > 0; i--) {
                bindForm(i);
//                    bindUpload(i);
            }


//            $("#form"+index).on("click",".btnGrayDo",function(){
//            $(".btnGrayDo").bind("click",function(){
//                var id = $(this).attr("data-id");
//                alert(id);
//                var formId = '#form'+id;
//                var formObj=$(formId);//要提交的表单
//                var Obj=$(".btnGrayDo");
//                var upObj=formObj.closest("input").find(".btnGrayUp");//浏览的按钮
//                var formsay=formObj.find(".say"+id);//提示文字
//                if(formObj.closest("div").find("input[type=text]").val().length!=0){//判断是否选择了文件
//                    formsay.attr("class","say true").html("上传中");
//                    formObj.ajaxForm({
//                        dataType: 'json',
//                        success:  function processJson(data){
//                            if(data.successFlg){
//                                formsay.attr("class","say true").html("上传成功");
//                                formObj.find("input[type=text]").attr("data-id",data.message)//设置已上传的文件的ID
//                                formObj.find(".btnDel").css("display","inline-block")
//                                formObj.closest("div").find("span").html("重新导入<i></i>");
//                            }else{
//                                $.ligerDialog.error("上传格式有问题");
//                                Obj.css("background","#ebebeb").html("导入");
//
//                            }
//                            //console.log(eval('('+data.data+')'));
//                        },
//                        error: function processJson(data){
//                            formsay.attr("class","say false").html("上传失败");
//                        }
//                    });
//                    formObj.submit();
//                }else{
//                    $.ligerDialog.error("请选择要上传的文件");
//                }
//            });


        },
        resolveFlow: function () {
            var index = 1;
            var flowStr = '${flowClass}';
            if (flowStr != "") {
                flowStr = flowStr.replace(/\\/g, "\\\\");
                var flowJson = $.parseJSON(flowStr);
                $.each(flowJson, function (i, data) {
                    var html = '<div class="flows"  dataIndex="' + index + '" id="paramGroup' + index + '">' +
                            '<form id="form' + index + '" action="${contextRoot}/flow/parseFile" method="post" enctype="multipart/form-data">';

                    html += '<div class="m-form-group" dataIndex="' + index + '"  ><label>类别 :</label><div class="m-form-control "> ' +
                            '<div class="l-text"><input type="text" id="type' + index + '" value="' + data.type + '" class="l-text-field required" name="type"></div>' +
                            '</div></div>';

                    html += '<div class="m-form-group" ><label>包名' + index + ' : </label><div class="m-form-control"  controlType="textbox" id="packName' + index + '_div" style="margin-left:0px;">' +
                            '<input type="text" name="packageName" id="packageName' + index + '" value="' + data.packageName + '" class="l-textbox"/></div></div>';

                    html += '<div class="m-form-group"   dataIndex="' + index + '" id="paramGroup' + index + '"><label>' +
                            '类名' + index + ' : </label><div class="m-form-control"  controlType="textbox" id="className' + index + '_div" style="margin-left:0px;">' +
                            '<input type="text" name="className" id="className' + index + '" value="' + data.className + '"  class="l-textbox"/></div></div>';


                    html += ' <div class="m-form-group"><label>源代码' + index + ' : </label><div class="m-form-control">';
                    html += ' <input type="text" name="isUpdate" id="isUpdate' + index + '" class="isUpdate" hidden="hidden"/>';

                    html += ' <input type="text"  id="classPath' + index + '" value="' + data.classPath + '" data-oldFile="'+data.classPath+'"  name="classPath" class="l-textbox btnGrayUp" style="width: 144px;"  placeholder="点击选择源代码文件" readonly="readonly" data-id="">' +
                            ' <div style="float: right;">' +
                            ' <div  class="l-button l-button-no btnGrayDo' + index + '" data-id="' + index + '">' +
                            ' <span style="background-color: rgb(240, 240, 240);">导入</span> </div>' +
                            '<label  id="say' + index + '"  class="say' + index + '" style="display: inline-block;width: 70px;"></label>' +
                            '</div><input type="file" name="file" style="display: none" id="file' + index + '" /></form>' +
                            '</div></div>';
                    html += ' <input name="id" value="' + data.id + '" id="classId' + index + '" hidden="hidden"/>';
                    html += '<div class="m-form-group"><div class="m-form-control"><a class="m-btn-cancle" href="javascrip:void()" style="display:block;" onclick="$(\'#paramGroup' + index + '\').remove()"></a></div></div>';

                    $("#classDiv").append(html);
                    $("#type" + index).ligerComboBox({
                        data: [ {"value": "processor", "code": "processor"},{"value": "route", "code": "route"}],
                        cancelable: false,
                        onSuccess: function (data) {
                        }
                    });

                    var type = data.type;
                    if (!type || type == '') {
                        type = "route";
                    }

                    liger.get("type" + index).selectValue(type);
                    bindForm(index);
                    bindUpload(index);
                    index++;
                });
            }

        }
    };

    function bindForm(index) {
        $("#form" + index).on("click", ".btnGrayUp", function () {
            var inputVal = $(this).closest("div").find("input[type=text]");
            var obj = $(this).closest("div").find("input[type=file]");
            obj.change(function () {
                inputVal.val(obj.val());
            })
            obj.click();
        });
    }

    function bindUpload(index) {
        $(".btnGrayDo" + index).bind("click", function () {
            var formId = '#form' + index;
            var formObj = $(formId);//要提交的表单
            var Obj = $(".btnGrayDo" + index);
            var upObj = formObj.closest("input").find(".btnGrayUp");//浏览的按钮
            var formsay = $("#say" + index);//提示文字
            if (formObj.closest("div").find("input[type=text]").val().length != 0) {//判断是否选择了文件
                formsay.attr("class", "say true").html("上传中");
                formObj.ajaxForm({
                    dataType: 'json',
                    type: "POST",
                    success: function processJson(data) {
                        debugger
                        if(data.successFlg){
                            formsay.attr("class", "say true").html("上传成功");
                            formObj.find("input[type=text]").filter(".btnGrayUp").attr("data-id", data.data.path)//设置已上传的文件的ID
                            var inputVal = formObj.closest("div").find("input[type=text]").filter(".btnGrayUp");
                            // 设置值之前删除旧的
                            var oldFileId = $(inputVal).attr("data-oldFile");
                            if(oldFileId){
                                _deleteFileAfterUpdate(oldFileId);
                            }
                            // 设置值之前删除旧的
                            inputVal.val(data.data.path);
                            $(inputVal).attr("data-oldFile", data.data.path);
                            $("#packageName"+index).val(data.data.package);
                            $("#className"+index).val(data.data.class);
                            formObj.closest("div").find("span").html("重新导入<i></i>");
                            var isUpdate = formObj.find(".isUpdate");//是否有上传过
                            isUpdate.val("1");//上传过
                        }else{
                            $.ligerDialog.error("上传格式有问题");
                            Obj.css("background","#ebebeb").html("导入");
                        }
                    },
                    error: function processJson(data) {
                        formsay.attr("class", "say false").html("上传失败");
                    }
                });
                formObj.submit();
            } else {
                $.ligerDialog.error("请选择要上传的文件");
            }
        });
    }

    function getFilePath(input) {
        if (input) {//input是<input type="file">Dom对象
            if (window.navigator.userAgent.indexOf("MSIE") >= 1) {  //如果是IE
                input.select();
                return document.selection.createRange().text;
            }
            else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {  //如果是火狐  {
                if (input.files) {
                    return input.files.item(0).getAsDataURL();
                }
                return input.value;
            }
            return input.value;
        }
    }

    //获取动态添加的form的最大值。
    function newMaxFormIndex() {
        var index;
        var size = $(".flows").length;
        if (size != "" && size > 0) {
            index = $("#" + $(".flows")[size - 1].id).attr("dataIndex");//获取参数的个数
        } else {
            index = 0;
        }
        return index;
    }

    $("#code").blur(function(){
        var reg = /^[0-9a-zA-Z]+$/;
        var code = document.getElementById("code").value;
        if(!reg.test(code)){
            $(".code-input-span").css("display","block");
            $(this).addClass("btnIconGrayUp");
        }
    });

    //删除旧文件
    function _deleteFileAfterUpdate(fileId){
        if(null == fileId || fileId.length == 0){
            return;
        }
        var url = "${dfs}/" + fileId;
        $.ajax({
            url: url,
            type: 'DELETE',
            async: false,
            success: function(){
                console.log("旧文件删除成功");
            }
        });
    }

    $(function () {
        editorFlow.init();
    });
</script>