<%@ 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">

    /* *************************** 模块初始化 ***************************** */
    var editorAppService = {
        //form
        index:1,
        actionUrl:"${contextRoot}/app/addAppService",
        $condition: null,
        $valid:"${model.valid}",
        init: function () {
            this.bindEvents();
            this.initForm();
        },
        initForm: function () {
            var me = this;
           var data;
            var modelString = "${model.id}";
            if(modelString!=undefined && modelString!=null && modelString.length>0)
            {
                var valid = "${model.valid}";
                var healthReportType = "${model.healthReportType}";
                var metricsReportType = "${model.metricsReportType}";
                liger.get("txtValid").selectValue(valid);
                liger.get("healthReportType").selectValue(healthReportType);
                liger.get("metricsReportType").selectValue(metricsReportType);

                data={
                    id: "${model.id}",
                    name: "${model.name}",
                   code: "${model.code}",
                   appId: "${model.appId}",
                   valid: valid,
                   version: "${model.version}",
                   description: "${model.description}",
                   endpoint: "${model.endpoint}",
                   requestFormat: "${model.requestFormat}".replace(/<br>/ig,"\n"),
                   requestProtocol: "${model.requestProtocol}",
                   requesModule: "${model.requesModule}".replace(/<br>/ig,"\n"),
                   requestMethod: "${model.requestMethod}",
                   healthReportType: "${model.healthReportType}",
                   healthEndpoint: "${model.healthEndpoint}",
                   responeResult:"${model.responeResult}".replace(/<br>/ig,"\n"),
                   responeError: "${model.responeError}".replace(/<br>/ig,"\n"),
                   metricsReportType: "${model.metricsReportType}",
                    requestParameterList:'${model.requestParameterList}',
                   metricsEndpoint: "${model.metricsEndpoint}"
                };

                me.actionUrl = "${contextRoot}/app/updateAppService";
            }else{
                liger.get("txtValid").selectValue("1");//默认有效
                liger.get("healthReportType").selectValue("");
                liger.get("metricsReportType").selectValue("");
                data={
                    appId: "${appId}"
                };
            }
            $("#div_info_form").ligerAutoForm({
                data:data,
                validate:{
                    name:"required",
                    version:"required",
                    valid:"required",
                    endpoint: {
                        required:true
                    }
                },
            });
            me.resolveParam();
        },
        bindEvents: function () {
            var me = this;
            $(".m-form-bottom").on("click","#btnSave",function () {
                $("#btnSave").css("pointer-events","none");
                $(".param").each(function(){$(this).removeClass("paramRequired")});
                var flag = false;
                $(".param").each(function(){
                    if($(this).val()=="") {
                        flag = true;
                        $(this).addClass("paramRequired");
                    }
                });

                if(!$("#div_info_form").ligerAutoForm("validate")){
                    return;
                }
                if (flag) {
                    return;
                }
                me.spliceParams();
                var data = $("#div_info_form").ligerAutoForm("getData");
                $.ajax({ //ajax处理
                    type: "POST",
                    url : me.actionUrl,
                    dataType : "json",
                    data:data,
                    cache:false,
                    success :function(data){
                        if(data.successFlg) {
                            parent.appService.dialogSuccess(data.message);
                        }
                        else{
                            $.ligerDialog.error(data.message);
                        }
                        $("#btnSave").css("pointer-events","");
                    },
                    error :function(data){
                        $.ligerDialog.error("Status:"+data.status +"(" +data.statusText+")");
                        $("#btnSave").css("pointer-events","");
                    }
                });
            });

            /* 监控类型为拉取的时候需要填写地址*/
            $("#healthReportType").bind('change', function (){
                var type = liger.get("healthReportType").selectedValue;
                if(type==0){
                    $("#label_health").css("display","");
                    $("#healthEndpoint").show();
                }else{
                    $("#label_health").css("display","none");
                    $("#healthEndpoint").hide();
                }
            });

            $("#metricsReportType").bind('change', function (){
                var type = liger.get("metricsReportType").selectedValue;
                if(type==0){
                    $("#label_metrics").css("display","");
                    $("#metricsEndpoint").show();
                }else{
                    $("#label_metrics").css("display","none");
                    $("#metricsEndpoint").hide();
                }
            });

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

            $(".l-button").live("click","#menu_add_btn",function () {
                me.newItem();
            });

            $(".l-button").on("click","#menu_test",function () {
                me.spliceParams();
            });

            //下拉框值初始化
            $("#txtValid").ligerComboBox({data : [{"value":"有效","code":"1"},{"value":"无效","code":"0"}],
                cancelable:false,
                onSuccess:function(data){
                }});
            $("#healthReportType").ligerComboBox({data : [{"value":"请选择类型","code":""},{"value":"推送","code":"1"},{"value":"拉取","code":"0"}],
                cancelable:false,
                onSuccess:function(data){
                }});
            $("#metricsReportType").ligerComboBox({data : [{"value":"请选择类型","code":""},{"value":"推送","code":"1"},{"value":"拉取","code":"0"}],
                cancelable:false,
                onSuccess:function(data){
                }});

            $("#resourceCondition").css("height", (window.screen.height - 200) / 5).css("overflow", "auto");

            <%--editorAppService.$condition = $('#serviceCondition').ligerApp({--%>
                <%--stdDictUrl: "${contextRoot}/std/getDictByScheme",--%>
            <%--});--%>

        },
        newItem: function () {
            var index;
            var size = $(".params").length;
            if(size!="" && size>0){
                index=$("#"+$(".params")[size-1].id).attr("dataIndex");//获取参数的个数
                index++;
            }else{
                index=1;
            }
            var html = '<div class="params" dataIndex="'+index+'" id="paramGroup'+index+'">';
            html += '<div class="m-form-control" controlType="textbox" id="divName'+index+'_div" style="margin-left:0px;"><span class="red">*&nbsp;</span>参数'+index+' : ' +
                    '<input type="text" id="name'+index+'"  class="l-textbox param "/>' +
                    '<div class="m-from-error-msg imageRequired" style="float: right;display: none"></div></div>';
            html += '<div class="m-form-control" controlType="textbox" id="divType'+index+'_div" style="margin-left:0px;"><div class="l-text-wrapper"><p style="padding-left:10px;width: 100%;height: 100%;line-height:30px;"><span class="red">*&nbsp;</span>类型:</p></div>' +
                    '<input type="text" id="type'+index+'" data-type="select"  class="l-textbox required"/></div>';
            html += '<div class="m-form-control"><a class="m-btn-cancle" href="javascrip:void()" style="display:block;" onclick="$(\'#paramGroup'+index+'\').remove()"></a></div>';

            $("#paramDiv").append(html);

            $("#type"+index).ligerComboBox({data : [{"value":"String","code":"String"},{"value":"Integer","code":"Integer"},{"value":"Date","code":"Date"}],
                cancelable:false,
                onSuccess:function(data){
                }});
        },
        spliceParams: function () {
            //参数拼接成json
            var inputs = $("#paramDiv").find("div[class=m-form-group]");
            var params = {};
            for(var i =0 ; i < inputs.length ; i ++)
            {
                var id = $("#"+inputs[i].id).attr("dataIndex");
                var name = $("#name"+id).val();
                var type = $("#type"+id).val();
                params[name]=type;
            }
            $("#requestParameterList").val(JSON.stringify(params));
        },
        resolveParam: function () {
            //将json的参数列表解析出来
            var index = 1;
            var paramStr = $("#requestParameterList").val();
            if (paramStr != ""){
                var paramJson = $.parseJSON(paramStr);
            for (var name in paramJson) {
                var type = paramJson[name];
                //动态添加参数
                var html = '<div class="params" dataIndex="' + index + '" id="paramGroup' + index + '">';
                html += '<div class="m-form-control" controlType="textbox" id="divName' + index + '_div" style="margin-left:0px;">参数' + index + ' : ' +
                        '<input type="text" id="name' + index + '" value='+name+'  class="l-textbox"/></div>';
                html += '<div class="m-form-control" controlType="textbox" id="divType' + index + '_div" style="margin-left:0px;"><div class="l-text-wrapper"><div style="padding-left:10px;width: 100%;height: 100%;line-height:30px;"><span class="red">*&nbsp;</span> 类型:&nbsp;</div></div>' +
                        '<input type="text" id="type' + index + '" value='+type+' data-type="select"  class="l-textbox"/></div>';
                html += '<div class="m-form-control"><a class="m-btn-cancle" href="javascrip:void()" style="display:block;" onclick="$(\'#paramGroup' + index + '\').remove()"></a></div>';

                $("#paramDiv").append(html);

                $("#type" + index).ligerComboBox({
                    data: [{"value": "String", "code": "String"}, {
                        "value": "Integer",
                        "code": "Integer"
                    }, {"value": "Date", "code": "Date"}],
                    cancelable: false,
                    onSuccess: function (data) {
                    }
                });
                liger.get("type"+index).selectValue(type);
                index++;
            }
        }
        }
    };



    $(function () {
        editorAppService.init();

    });
</script>