<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="utf-8"%>
<%@include file="/WEB-INF/ehr/commons/jsp/commonInclude.jsp" %>
<link href="${contextRoot}/develop/lib/select2/select2.min.css" rel="stylesheet">
<script src="${contextRoot}/develop/lib/select2/select2.js"></script>
<script >
      /* ************************** 全局变量定义 **************************** */
      $importData=$("#importData");
      var status = $("#publish_status").val();
      var Util = $.Util;
      var retrieve = null;
      var master = null;
      var conditionArea = null;
      var adapterPlanId = "";
      var entryRetrieve = null;
      var entryMaster = null;
      var datasourceRetrieve = null;
      var datasourceMaster = null;
      var cfgModel = 0;
      var changeFlag=false;
      var orgList = [];
      var datasourceList = [];
      var cfg = [
        {
          left:{title:'数据集', cls:'', search:'/standardCenter/searchDatasetList', goAdd:'/integration/updateDataset',del:'/standardCenter/delDataset',delLs:'/standardCenter/delDataset'},
          right:{title:'数据元', cls:'', search:'/standardCenter/searchMetadataList', goAdd:'/integration/updateMetadata',del:'/standardCenter/delMetaData',delLs:'/standardCenter/delMetaData'}
        },
        {
          left:{title:'字典', cls:'', search:'/standardCenter/searchDictList', goAdd:'/integration/updateDict',del:'/standardCenter/delDict',delLs:'/standardCenter/delDict'},
          right:{title:'字典项', cls:'', search:'/standardCenter/searchDictEntryList', goAdd:'/integration/updateDictEntry', del:'/standardCenter/delDictEntry',delLs:'/standardCenter/delDictEntry'}
        }
      ];
      /* *************************** 函数定义 ******************************* */
      function pageInit() {
        if(status=="1"){//已发布
          $(".div-btn").hide();
        }else{//未发布
          $(".div-btn").show();
        }
        resizeContent();
        retrieve.init();
        conditionArea.init();
        entryRetrieve.init();
        master.init();
        master.reloadGrid();
        entryMaster.init();
        datasourceRetrieve.init();
        datasourceMaster.init();
        $('#div_datasource').hide();
      }

      $importData.bind("click",function(){
        var version =$("#version").val();
        var standardId = $("#standard_id").val();
        var url = "${contextRoot}/integration/importData?version="+version+"&standardId="+standardId;;
        var importDataDialog = $.ligerDialog.open({
          title: "导入数据",
          url: url,
          height: 250,
          width: 650,
          cls:"closeCls"
        });
        $(document).on("click",".closeCls",function(){
          master.reloadGrid();
        });
      });

      function reloadGrid (url, params, columns) {
        if(columns)
          this.grid.set({
            columns:columns,
            url: url,
            parms: params
          });
        else
          this.grid.set({
            url: url,
            parms: params
          });
//        this.grid.reload();
      }

      function resizeContent(){
        var contentW = $('#grid_content').width();
        var leftW = $('#div_left').width();
        var div_wrapper = $("#div_wrapper").width();
        if($("#type").val()=="0"){//集成标准
          $(".btn-group").css("margin-left",(div_wrapper-200)/2);
        }else{//应用标准
          $(".btn-group").css("margin-left",(div_wrapper-300)/2);
          $(".btn-group").append($("#switch_datasource"));
          $("#switch_datasource").show();
        }
        $('#div_right').width(contentW-leftW-20);
      }
      /* *************************** title模块初始化 ***************************** */
      conditionArea = {
        $element: $('#conditionArea'),
        $adapter_plan_name :$('#adapter_plan_name'),
        $adapter_plan_parent :$('#adapter_plan_parent'),
        $adapter_plan_type :$('#adapter_plan_type'),
        $adapter_plan_org :$('#adapter_plan_org'),
        $btn_switch_dataSet :$('#switch_dataSet'),
        $btn_switch_dict :$('#switch_dict'),
        $btn_switch_datasource :$('#switch_datasource'),
        $div_left :$('#div_left'),
        $div_right :$('#div_right'),
        $div_datasource:$('#div_datasource'),
        init : function () {
         // this.initAdapterOrg();
          
          this.$element.show();
          this.bindEvents();
        },
        initAdapterOrg: function () {
          var self = this;
          var dataModel = $.DataModel.init();

          dataModel.fetchRemote("${contextRoot}/adapter/getAdapterPlanById",{
            data:{id:adapterPlanId},
            success: function(data) {
              var model = data.obj;
              self.$adapter_plan_name.val(model.name);
              self.$adapter_plan_parent.val(model.parentName);
              self.$adapter_plan_type.val(model.typeValue);
              self.$adapter_plan_org.val(model.orgValue);
            },
            error: function () {
              // alert(1)
            }
          });
        },
        bindEvents : function () {
          this.$btn_switch_dataSet.click(function () {
            if(cfgModel==0)
              return;
            conditionArea.$div_left.show();
            conditionArea.$div_right.show();
            conditionArea.$div_datasource.hide();
            cfgModel = 0;
            retrieve.setTitle();
            entryRetrieve.setTitle();
            changeFlag=true;
            master.reloadGrid();
            $(".btn-default").removeClass("active");
            conditionArea.$btn_switch_dataSet.addClass("active");
          });

          this.$btn_switch_dict.click(function () {
            if(cfgModel==1)
              return;
            conditionArea.$div_left.show();
            conditionArea.$div_right.show();
            conditionArea.$div_datasource.hide();
            cfgModel = 1;
            retrieve.setTitle();
            entryRetrieve.setTitle();
            changeFlag=true;
            master.reloadGrid();
            $(".btn-default").removeClass("active");
            conditionArea.$btn_switch_dict.addClass("active");
          });

          this.$btn_switch_datasource.click(function () {
            if(cfgModel==2)
              return;
            conditionArea.$div_left.hide();
            conditionArea.$div_right.hide();
            conditionArea.$div_datasource.show();
            cfgModel = 2;
            changeFlag=true;
            datasourceMaster.reloadGrid();
            $(".btn-default").removeClass("active");
            conditionArea.$btn_switch_datasource.addClass("active");
          });
        }

      };

      /* *************************** left模块初始化 ***************************** */
      retrieve = {
        $element: $('#retrieve'),
        $searchNm: $('#searchNm'),
        $addBtn: $('#btn_create'),
        $title :$('#left_title'),
        init: function () {
          this.$searchNm.ligerSearch({onClick: function (value) {
            master.reloadGrid();
          }});

          this.$element.show();
        },
        setTitle: function () {
          this.$title.html(cfg[cfgModel].left.title);
        }
      };

      master = {
        infoDialog: null,
        grid: null,
        init: function () {
          if(this.grid)
            return;
          this.grid = $("#div_left_grid").ligerGrid({
            url: '${contextRoot}'+cfg[cfgModel].left.search,
            columns: this.getColumn(),
            delayLoad:true,
            selectRowButtonOnly: true,
            allowHideColumn:false,
            validate : true,
            unSetValidateAttr:false,
            onSuccess: function (data,grid) {
              if(data.detailModelList.length==0){
                entryMaster.reloadGrid('');
              }
            },
            onAfterShowData: function () {
              this.select(0);
            },
            onSelectRow: function(row){
              
              entryMaster.reloadGrid(row.id);
            }
          });
          this.bindEvents();
        },
        bindEvents: function () {
          //窗体改变大小事件
          $(window).bind('resize', function() {
            resizeContent();
          });
          $('#btn_create').click(function () {
            master.open('','add');
          });

          $("#searchNm").keyup(function (e) {
            if (e.keyCode == 13) {
              master.reloadGrid();
            }
          });

        },
        reloadGrid: function () {
          var searchNm = $("#searchNm").val();
          var values = {
            stdVersion: $("#version").val(),
            condition: JSON.stringify({"name":searchNm}),
          };
          if (changeFlag){
            var url = '${contextRoot}' + cfg[cfgModel].left.search;
            reloadGrid.call(this, url, values, this.getColumn());
          }else{
            this.grid.setOptions({parms: $.extend({},values),newPage: 1});
            //重新查询
            this.grid.loadData(true);
          }
        },
        open:function(id,mode){
          var title;
          if(mode=="add"){
            title="新增";
          }else if(mode=="modify"){
            title="修改";
          }else{
            title="查看";
          }
          title += cfg[cfgModel].left.title;
          var url = '${contextRoot}'+cfg[cfgModel].left.goAdd;
          if (mode == 'modify' || mode=="") {
            url = url + "?type="+mode+"&id=" +id+"&version="+$("#version").val()+"&standardId="+ $("#standard_id").val();;
          } else {
            url = url + "?type="+mode+"&version="+$("#version").val()+"&standardId="+ $("#standard_id").val();
          }
          master.entryInfoDialog = $.ligerDialog.open({
            height:500,
            width: 500,
            title : title,
            url: url
          });
        },
        delete:function(ids){
          if(ids=='' || ids=='undefined'){
            var rows = master.grid.getSelectedRows();
            if(rows.length==0){
              $.ligerDialog.warn( '请选择要删除的数据行！');
              return;
            }
            for(var i=0;i<rows.length;i++){
              ids += ','+rows[i].id;
            }
            ids = ids.length>0?ids.substring(1, ids.length):ids;
          }

          var toData = null;
          if(cfgModel==0){//数据集
            toData={datasetId:ids, stdVersion:$("#version").val()};
          }else if(cfgModel==1){//字典
            toData={dictId:ids, stdVersion:$("#version").val()};
          }
          $.ligerDialog.confirm('确认删除所选数据？', function (r) {
            if(r){
              $.ajax({
                url: '${contextRoot}'+cfg[cfgModel].left.delLs,
                type: "get",
                dataType: "json",
                data:toData,
                success: function (data) {
                  if(data.successFlg){
                    $.ligerDialog.success(data.message);
                    master.reloadGrid();
                  }else{
                    $.ligerDialog.error(data.message);
                  }

                },
                error: function (jqXHR, textStatus, errorThrown) {
                  $.ligerDialog.error("删除数据集信息失败！")
                }
              });
            }
          })
        },
        getColumn: function () {
          
          var code = 'code';
          var name = 'name';
          var columnCfg = [
            { display: 'id', name: 'id', hide:true },
            { display: '代码', name: code,width: '33%', isAllowHide: false, align: 'center' },
            { display: '名称',name: name, width: '34%',isAllowHide: false, align: 'center'},
            { display: '操作', name: 'operator', width: '33%',  align: 'center',render: function (row) {
              if(status=="1") {//已发布
                var html = '<div class="m-inline-buttons" style="width:40px;">';
                 html += '<a href="#" class="m-btn-view" onclick="master.open(\''+row.id+'\',\'\')"></a>';
                return html;
              }else{//未发布
                var html = '<div class="m-inline-buttons" style="width:80px;">';
                 html +=  '<a href="#" class="m-btn-edit" onclick="javascript:master.open(\''+row.id+'\',\'modify\')"></a>';
                 html += '<a href="#" class="m-btn-delete" onclick="javascript:master.delete(\''+row.id+'\')"></a>';
                return html;
              }

            }}
          ];
          return columnCfg;
        }
      };

      /* *************************** right模块初始化 ***************************** */
      entryRetrieve = {
        $element: $('#entryRetrieve'),
        $searchNm: $('#searchNmEntry'),
        $title: $('#right_title'),
        init: function () {
          this.$searchNm.ligerSearch({onClick: function () {
            var row = master.grid.getSelectedRow();
            var parentId = "";
            if(row){
              parentId = row.id;
            }
            entryMaster.reloadGrid(parentId);
          }});

          this.$element.show();
        },
        setTitle: function () {
          this.$title.html(cfg[cfgModel].right.title);
        }
      };

      entryMaster = {
        entryInfoDialog: null,
        grid: null,
        init: function (dictId) {
          if(this.grid)
            return;
          this.grid = $("#div_relation_grid").ligerGrid({
            url: '${contextRoot}'+cfg[cfgModel].right.search,
            columns: this.getColumn(),
            delayLoad:true,
            selectRowButtonOnly: true,
            allowHideColumn:false,
            validate : true,
            unSetValidateAttr:false,
            checkbox:false,
            onDblClickRow : function (row){
              //$.publish('grid:right:open',[row.id, 'modify']);
            }
          });
          this.bindEvents();
        },
        reloadGrid: function (parentId) {

          var searchNmEntry = $("#searchNmEntry").val();

          var values = {
            datasetId:parentId,
            dictId:parentId,
            stdVersion:$("#version").val(),
            condition: JSON.stringify({"name":searchNmEntry})
          };
          if (changeFlag){
            reloadGrid.call(this, '${contextRoot}'+cfg[cfgModel].right.search, values, this.getColumn());
          }else{
            this.grid.setOptions({parms: $.extend({},values),newPage: 1});
            //重新查询
            this.grid.loadData(true);
          }
          changeFlag=false;
        },
        open:function(id,mode){
          
          var title;
          if(mode=="add"){
            title="新增";
          }else if(mode=="modify"){
            title="修改";
          }else{
            title="查看";
          }
          title += cfg[cfgModel].right.title;
          var url = '${contextRoot}'+cfg[cfgModel].right.goAdd;
          var row = master.grid.getSelectedRow();
          if (mode == 'modify' || mode=="") {
            url = url + "?type="+mode+"&id=" +id+"&version="+$("#version").val()+"&pid="+ row.id+"&standardId="+ $("#standard_id").val();
          } else {
            url = url + "?type="+mode+"&version="+$("#version").val()+"&pid="+ row.id+"&standardId="+ $("#standard_id").val();
          }

          if(cfgModel==1){//字典项
            entryMaster.entryInfoDialog = $.ligerDialog.open({
              height:400,
              width: 500,
              title : title,
              url: url
            });
          }else{//数据元
            entryMaster.entryInfoDialog = $.ligerDialog.open({
              height:550,
              width: 750,
              title : title,
              url: url
            });
          }

        },
        delete:function(ids){
          if(ids ==''|| ids==undefined){
            var rows = entryMaster.grid.getSelectedRows();
            if(rows.length==0){
              $.ligerDialog.warn( '请选择要删除的数据行！');
              return;
            }
            for(var i=0;i<rows.length;i++){
              ids += ','+rows[i].id;
            }
            ids = ids.length>0?ids.substring(1, ids.length):ids;
          }
          var toData = null;
          if(cfgModel==0){//数据元
            toData={metadataId:ids, stdVersion:$("#version").val()};
          }else if(cfgModel==1){//字典项
            toData={dictEntryId:ids, stdVersion:$("#version").val()};
          }

          $.ligerDialog.confirm('确认删除所选数据？', function (r) {
            var row = master.grid.getSelectedRow();
            var parentId = "";
            if(row){
              parentId = row.id;
            }
            if(r){
              $.ajax({
                url: '${contextRoot}'+cfg[cfgModel].right.delLs,
                type: "get",
                dataType: "json",
                data:toData,
                success: function (data) {
                  if(data.successFlg){
                    $.ligerDialog.success( data.message);
                    entryMaster.reloadGrid(parentId);
                  }else{
                    $.ligerDialog.error(data.message);
                  }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                  $.ligerDialog.error("删除失败！")
                }
              });
            }
          })
        },
        bindEvents: function () {
          //窗体改变大小事件
          $(window).bind('resize', function() {
            resizeContent();
          });

          $('#btn_create_relation').click(function () {
            entryMaster.open('','add');
          });


          $("#searchNmEntry").keyup(function (e) {
            if (e.keyCode == 13) {
              entryMaster.reloadGrid();
            }
          });
        },

        getColumn: function () {
          var columnCfg =[];
          if(cfgModel==0){
            columnCfg = [
              { display: 'id', name: 'id', hide:true },
              { display: '数据元编码', name: 'code',width: '20%', isAllowHide: false ,align:'center' },
              { display: '数据元名称',name: 'name', width: '20%',isAllowHide: false  ,align:'center'},
              { display: '数据类型', name: 'type',width: '20%', isAllowHide: false  ,align:'center'},
              { display: '表示格式',name: 'format', width: '20%',isAllowHide: false  ,align:'center'},
              { display: '操作', name: 'operator', width: '20%',align:'center', render: function (row) {
                if(status=="1") {//已发布
                  var html = '<div class="m-inline-buttons" style="width:40px;">';
                   html += '<a href="#" class="m-btn-view" onclick="entryMaster.open(\''+row.id+'\',\'\')"></a>';
                  return html;
                }else{//未发布
                  var html = '<div class="m-inline-buttons" style="width:80px;">';
                   html +=  '<a href="#" class="m-btn-edit" onclick="entryMaster.open(\''+row.id+'\',\'modify\')"></a>';
                   html +=  ' <a href="#" class="m-btn-delete" onclick="entryMaster.delete(\''+row.id+'\')"></a>';
                  return html;
                }
              }}
            ]
          }
          else{
            columnCfg = [
              { display: 'id', name: 'id', hide:true },
              { display: '值域编码', name: 'code',width: '40%', isAllowHide: false ,align:'center' },
              { display: '值域名称',name: 'value', width: '40%',isAllowHide: false  ,align:'center'},
              { display: '操作', name: 'operator', width: '20%', align:'center',render: function (row) {
                if(status=="1") {//已发布
                  var html = '<div class="m-inline-buttons" style="width:40px;">';
                   html += '<a href="#" class="m-btn-view" onclick="entryMaster.open(\''+row.id+'\',\'\')"></a>';
                  return html;
                }else{//未发布
                  var html = '<div class="m-inline-buttons" style="width:80px;">';
                   html +=  '<a href="#" class="m-btn-edit"  onclick="entryMaster.open(\''+row.id+'\',\'modify\')"></a>';
                   html +=   ' <a href="#" class="m-btn-delete" onclick="entryMaster.delete(\''+row.id+'\')"></a>';
                  return html;
                }

              }}
            ]
          }
          return columnCfg;
        }
      };

      /* *************************** datasource模块初始化 ***************************** */
      datasourceRetrieve = {
        $element: $('#div_datasource'),
        grid: null,
        init: function () {
          this.$element.show();
        }
      };

      datasourceMaster = {
        infoDialog: null,
        grid: null,
        init: function () {
          if(this.grid)
            return;
          $.ajax({
            url: '${contextRoot}/org/getOrgList',
            type: "get",
            dataType: "json",
            data:{activityFlag:'1'},
            success: function (data) {
              
              if(data.successFlg && !Util.isStrEmpty(data.detailModelList)){
                orgList = data.detailModelList;
              }else{
                $.ligerDialog.error(data.message);
              }
            },
            error: function (jqXHR, textStatus, errorThrown) {
              $.ligerDialog.error("获取机构信息列表失败！")
            }
          });

          $.ajax({
            url: '${contextRoot}/datasource/getDatasourceByOrg',
            type: "get",
            dataType: "json",
            success: function (data) {

              if(data.successFlg && !Util.isStrEmpty(data.detailModelList)){
                datasourceList = data.detailModelList;
              }else{
                $.ligerDialog.error("数据源未配置");
              }

            },
            error: function (jqXHR, textStatus, errorThrown) {
              $.ligerDialog.error("获取数据源信息列表失败！")
            }
          });


          this.grid = $("#div_datasource_grid").ligerGrid({
            url: '${contextRoot}/datacollect/getDatasetSource',
            parms:{stdVersion:'${version}'},
            columns: this.getColumn(),
            usePager: false,
            onAfterShowData: function (gridData) {//显示完数据事件

              //【应用数据元编码】change事件
              $(".sel-org-id").on("change", function(event,msg) {
                var rowIndex = $(this).attr("id").replace("orgId","");
                var option = '<option value="">请选择</option>';
                for(var i=0;i<datasourceList.length;i++){
                  if(datasourceList[i].orgId==$(this).val()){
                    option+='<option value="'+datasourceList[i].id+'">'+datasourceList[i].name+'</option>';
                  }
                }

                $("#datasourceId"+rowIndex).html("");
                $("#datasourceId"+rowIndex).append(option);
              });

            }
          });

            this.bindEvents();

        },
        bindEvents: function () {

          $('#btn_save_datasource').click(function () {

            var dataResult = new Array();
            var rowData = datasourceMaster.grid.getData();
            for (var i = 0; i < rowData.length; i++) {
              var ob = new Object();
              ob.id = rowData[i].id == undefined ? "" : rowData[i].id;
              ob.datasetId = rowData[i].datasetId == undefined ? "" : rowData[i].datasetId;
              ob.datasourceId = $("#datasourceId"+i).val()==undefined ? "":$("#datasourceId"+i).val();
              ob.stdVersion = '${version}';
              ob.stdId = '${stdId}';
              ob.orgId = $("#orgId"+i).val()==undefined ? "":$("#orgId"+i).val();

              dataResult.push(ob);
            }
            

            $.ajax({ //ajax处理
              type: "POST",
              url : '${contextRoot}/datacollect/saveDatasetSource',
              dataType : "json",
              data:{stdVersion:'${version}',json:JSON.stringify(dataResult)},
              cache:false,
              success :function(data){
                if(data.successFlg) {
                  $.ligerDialog.success(data.message);
                  datasourceMaster.reloadGrid();
                }
                else {
                  $.ligerDialog.error(data.message);
                }
              },
              error :function(data) {
                $.ligerDialog.error("Status:"+data.status +"(" +data.statusText+")");
              }
            });
          });
        },
        reloadGrid: function () {
          var values = {
            stdVersion:'${version}',
          };
          if (changeFlag){
            reloadGrid.call(this, '${contextRoot}/datacollect/getDatasetSource', values, this.getColumn());
          }else{
            this.grid.setOptions({parms: $.extend({},values),newPage: 1});
            //重新查询
            this.grid.loadData(true);
          }
          changeFlag=false;
        },
        getColumn: function () {
          if(status=="1") {//已发布
            var columnCfg = [
              { display: 'id', name: 'id', hide:true },
              { display: '数据集名称', name: 'datasetName',width: '25%', isAllowHide: false ,align:'left' },
              { display: '数据集代码',name: 'datasetCode', width: '25%',isAllowHide: false  ,align:'left'},
              {display:'机构名称',name:'orgId', width: '25%',align:'left',dict:true,dictName:"SYSTEM_ORGANIZATION"},
              { display: '数据源名称',name: 'datasourceId', width: '25%',align:'left',dict:true,dictName:"SYSTEM_DATASOURCE"},
            ]
            return columnCfg;
          }else{//未发布
            var columnCfg = [
              { display: 'id', name: 'id', hide:true },
              { display: '数据集名称', name: 'datasetName',width: '20%', isAllowHide: false ,align:'left' },
              { display: '数据集代码',name: 'datasetCode', width: '20%',isAllowHide: false  ,align:'left'},
              {display:'机构名称',name:'orgId', width: '25%',align:'left',render: function (row, rowindex, value, column) {
                var select= '<select class="sel-org-id form-control"  id="orgId'+rowindex+'" style="margin-top:3px;font-size:12px;"><option value="">请选择</option>';
                for(var i=0;i<orgList.length;i++){
                  select+='<option value="'+orgList[i].id+'">'+orgList[i].fullName+'</option>';
                }
                select = $(select+"</select>");
                $('option[value="'+value+'"]',select).attr('selected',true);

                return  select.prop("outerHTML");
              }},
              { display: '数据源名称',name: 'datasourceId', width: '25%',align:'left',render: function(row, rowindex, value, column) {
                var select= '<select class="sel-datasource-id form-control"  id="datasourceId'+rowindex+'" style="margin-top:3px;font-size:12px;"><option value="">请选择</option>';
                for(var i=0;i<datasourceList.length;i++){
                  if(datasourceList[i].orgId==row.orgId){
                    select+='<option value="'+datasourceList[i].id+'">'+datasourceList[i].name+'</option>';
                  }
                }
                select = $(select+"</select>");
                $('option[value="'+value+'"]',select).attr('selected',true);

                return  select.prop("outerHTML");
              }},
              { display: '操作', name: 'operator', width: '10%', render: function (row, rowindex, value, column) {
                var html = '<div class="m-inline-buttons" style="width:40px;">';
                html +=  ' <a href="#" class="m-btn-delete" onclick="datasourceMaster.delete(\''+rowindex+'\')"></a>';
                return html;
              }}
            ]
            return columnCfg;
          }

        },
        delete:function(rowindex){
          $.ligerDialog.confirm('确定删除该数据源配置？', function (r) {
            if(r){
              
              $("#orgId"+rowindex).val("");
              $("#datasourceId"+rowindex).val("");
            }
          })
        }
      };



      /* *************************** 页面初始化功能 **************************** */
        $(function () {
          pageInit();
        });
</script>
