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


  /* ************************** 全局变量定义 **************************** */
  var status = $("#publish_status").val();
  var Util = $.Util;
  var retrieve = null;
  var master = null;
  var conditionArea = null;
  var entryRetrieve = null;
  var entryMaster = null;
  var cfgModel = 0;
  var changeFlag=false;
  var dataRows =0;
  var dataFlag = true;
  var cfg = [
    {
      left:{title:'数据集', cls:'', search:'/standardCenter/searchDatasetList', del:''},
      right:{title:'数据元', cls:'', search:'/adapterCenter/searchMetadataList', del:'',delLs:'/adapterCenter/delMetadata'}
    },
    {
      left:{title:'字典', cls:'', search:'/standardCenter/searchDictList', del:''},
      right:{title:'字典项', cls:'', search:'/adapterCenter/searchDictEntryList', del:'',delLs:'/adapterCenter/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();

  }

  function reClass(){
    $(".l-grid-row-alt").each(function(){
      $(this).removeChild("l-grid-row-alt");
    })
  }

  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();
    $('#div_right').width(contentW-leftW-20);
    $(".btn-group").css("margin-left",(div_wrapper-200)/2);
  }
  /* *************************** 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'),
    init : function () {
      // this.initAdapterOrg();
      this.bindEvents();
      this.$element.show();

    },
    bindEvents : function () {
      this.$btn_switch_dataSet.click(function () {

        $("#btn_aoto_adpat").css("display","block");
        $("#btn_aoto_adpat_dic").css("display","none");

        if(cfgModel==0)
          return;
        cfgModel = 0;
        $("#btn_add_relation").hide();
        $("#isDataSet").val("1");//该input框为1时,代表此时显示字典
        retrieve.setTitle();
        entryRetrieve.setTitle();
        changeFlag=true;
        master.reloadGrid();
        $(".btn-default").removeClass("active");
        conditionArea.$btn_switch_dataSet.addClass("active");
        $("#searchNmEntry").attr("placeholder","请输入编码或名称")
      });

      this.$btn_switch_dict.click(function () {

        $("#btn_aoto_adpat").css("display","none");
        $("#btn_aoto_adpat_dic").css("display","block");

        if(cfgModel==1)
          return;
        cfgModel = 1;
//            $("#btn_add_relation").show();
        $("#isDataSet").val("0");//该input框为0时,代表此时显示数据集
        retrieve.setTitle();
        entryRetrieve.setTitle();
        changeFlag=true;
        master.reloadGrid();
        $(".btn-default").removeClass("active");
        conditionArea.$btn_switch_dict.addClass("active");
        $("#searchNmEntry").attr("placeholder","请输入编码或值");
      })
    }
  };

  /* *************************** left模块初始化 ***************************** */
  retrieve = {
    $element: $('#retrieve'),
    $searchNm: $('#searchNm'),
    $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,
    stdIdStrLs:"",
    init: function () {
      var me = this;
      var stdVersion = $("#std_version").val();
      var adapterStdVersion = $("#adapter_std_version").val();
      var version = $("#version").val(); //adapter version
      var schemeId = $("#scheme_id").val();
      schemeId = schemeId.replace("scheme","");
      $("#version").val(version);
      $("#adapter_std_version").val(adapterStdVersion);
      $("#std_version").val(stdVersion);
      $("#scheme_id").val(schemeId);
      if(this.grid)
        return;
      var version = $("#version").val();
      var url = '${contextRoot}'+'/adapterCenter/searchDatasetList?adapterVersion=' + version;
      $.ajax({
        url: url,
        type:"post",
        dataType:"json",
        success:function (data) {
          if(data.successFlg) {
            for (var i=0; i<data.detailModelList.length;i++){
              var stdDatasetId = data.detailModelList[i].stdDatasetId;
              me.stdIdStrLs += stdDatasetId + ",";
            }

            me.initGrid(me.stdIdStrLs);
          }
        }
      });
      this.bindEvents();


    },
    initGrid: function (stdIdStrLs) {

      var me = this;
      this.grid = $("#div_left_grid").ligerGrid({
        url: '${contextRoot}'+cfg[cfgModel].left.search,
        parms:{stdVersion: $("#std_version").val(),condition: JSON.stringify({"name":"","stdId": stdIdStrLs})},
        columns: me.getColumn(),
        selectRowButtonOnly: true,
        allowHideColumn:false,
        validate : true,
        unSetValidateAttr:false,
        onBeforeShowData: function (data) {

          if(data.detailModelList.length==0){
            entryMaster.reloadGrid('');
          }
        },
        onAfterShowData: function () {
          this.select(0);
        },
        onSelectRow: function(row){
          dataRows = 0;
          dataFlag = true;
          $("#std_dict_id").val(row.id);
          entryMaster.reloadGrid(row.id);
        }
      });
    },
    bindEvents: function () {
      $("#searchNm").keyup(function (e) {
        if (e.keyCode == 13) {
          master.reloadGrid();
        }
      });

    },
    reloadGrid: function () {

      var me = this;
      var searchNm = $("#searchNm").val();
      var values = {
        stdVersion: $("#std_version").val(),
        condition: JSON.stringify({"name":searchNm,"stdId":me.stdIdStrLs})
      };
      if (changeFlag){
        var url = '${contextRoot}' + cfg[cfgModel].left.search;
        reloadGrid.call(this, url, values, this.getColumn());
      }else{
        me.grid.setOptions({parms: $.extend({},values),newPage: 1});
        //重新查询
        me.grid.loadData(true);
      }
    },
    getColumn: function () {
      var columnCfg =[];
      var stdId = 'id';
      var stdCode = 'code';
      var stdName = 'name';
      var codeDisplay = '目标标准数据集编码';
      var nameDisplay = '目标标准数据集名称';
      if(cfgModel==1){
        stdId = 'id';
        stdCode = 'code';
        stdName = 'name';
        codeDisplay = '目标标准字典编码';
        nameDisplay = '目标标准字典名称';
      }
      columnCfg = [
        { display: 'id', name: 'id', hide:true },
        { display: stdId, name: stdId, hide:true },
        { display: codeDisplay, name: stdCode, width: '50%',isAllowHide: false ,align:'left' },
        { display: nameDisplay, name: stdName, width: '50%',isAllowHide: false ,align:'left' }
      ];
      return columnCfg;
    }
  };

  /* *************************** right模块初始化 ***************************** */
  entryRetrieve = {
    $element: $('#entryRetrieve'),
    $searchNm: $('#searchNmEntry'),
    $title: $('#right_title'),
    init: function () {
      this.$searchNm.ligerSearch({onClick: function (value) {
        entryMaster.reloadGrid();
      }});

      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']);
        },
        rowClsRender:function (rowdata,rowid){
          if(rowdata.adapterInfo=="0"){//疑似适配
            return "unadapt";
          }
          if(rowdata.adapterInfo=="1"){//疑似适配
            return "ysadapt";
          }
          if(rowdata.adapterInfo=="2"){//完全适配
            return "alladapt";
          }
        },
        _getHtmlFromData: function (data, frozen)
        {
          if (!data) return "";
          var g = this, p = this.options;
          var gridhtmlarr = [];
          for (var i = 0, l = data.length; i < l; i++)
          {
            var item = data[i];
            var rowid = item['__id'];
            if (!item) continue;
            gridhtmlarr.push('<tr');
            gridhtmlarr.push(' id="' + g._getRowDomId(item, frozen) + '"');
            gridhtmlarr.push(' class="l-grid-row'); //class start
            if (!frozen && g.enabledCheckbox() && p.isChecked && p.isChecked(item))
            {
              g.select(item);
              gridhtmlarr.push(' l-selected');
            }
            else if (g.isSelected(item))
            {
              gridhtmlarr.push(' l-selected');
            }
            else if (p.isSelected && p.isSelected(item))
            {
              g.select(item);
              gridhtmlarr.push(' l-selected');
            }
            if (p.rowClsRender)
            {
              var rowcls = p.rowClsRender(item, rowid);
              rowcls && gridhtmlarr.push(' ' + rowcls);
            }
            gridhtmlarr.push('" ');  //class end
            if (p.rowAttrRender) gridhtmlarr.push(p.rowAttrRender(item, rowid));
            if (p.tree && g.collapsedRows && g.collapsedRows.length)
            {
              var isHide = function ()
              {
                var pitem = g.getParent(item);
                while (pitem)
                {
                  if ($.inArray(pitem, g.collapsedRows) != -1) return true;
                  pitem = g.getParent(pitem);
                }
                return false;
              };
              if (isHide()) gridhtmlarr.push(' style="display:none;" ');
            }
            gridhtmlarr.push('>');
            $(g.columns).each(function (columnindex, column)
            {
              if (frozen != column.frozen) return;
              gridhtmlarr.push('<td');
              gridhtmlarr.push(' id="' + g._getCellDomId(item, this) + '"');
              //如果是行序号(系统列)
              if (this.isrownumber)
              {
                gridhtmlarr.push(' class="l-grid-row-cell l-grid-row-cell-rownumbers" style="width:' + this.width + 'px"><div class="l-grid-row-cell-inner"');
                if (p.fixedCellHeight)
                  gridhtmlarr.push(' style = "height:' + p.rowHeight + 'px;" ');
                else
                  gridhtmlarr.push(' style = "min-height:' + p.rowHeight + 'px;" ');
                gridhtmlarr.push('>' + (parseInt(item['__index']) + 1) + '</div></td>');
                return;
              }
              //如果是复选框(系统列)
              if (this.ischeckbox)
              {
                gridhtmlarr.push(' class="l-grid-row-cell l-grid-row-cell-checkbox" style="width:' + this.width + 'px"><div class="l-grid-row-cell-inner"');
                if (p.fixedCellHeight)
                  gridhtmlarr.push(' style = "height:' + p.rowHeight + 'px;" ');
                else
                  gridhtmlarr.push(' style = "min-height:' + p.rowHeight + 'px;" ');
                gridhtmlarr.push('>');
                gridhtmlarr.push('<span class="l-grid-row-cell-btn-checkbox"></span>');
                gridhtmlarr.push('</div></td>');
                return;
              }
              //如果是明细列(系统列)
              else if (this.isdetail)
              {
                gridhtmlarr.push(' class="l-grid-row-cell l-grid-row-cell-detail" style="width:' + this.width + 'px"><div class="l-grid-row-cell-inner"');
                if (p.fixedCellHeight)
                  gridhtmlarr.push(' style = "height:' + p.rowHeight + 'px;" ');
                else
                  gridhtmlarr.push(' style = "min-height:' + p.rowHeight + 'px;" ');
                gridhtmlarr.push('>');
                if (!p.isShowDetailToggle || p.isShowDetailToggle(item))
                {
                  gridhtmlarr.push('<span class="l-grid-row-cell-detailbtn"></span>');
                }
                gridhtmlarr.push('</div></td>');
                return;
              }
              var colwidth = this._width;
              gridhtmlarr.push(' class="l-grid-row-cell ');
              if (g.changedCells[rowid + "_" + this['__id']]) gridhtmlarr.push("l-grid-row-cell-edited ");
              if (this.islast)
                gridhtmlarr.push('l-grid-row-cell-last ');
              gridhtmlarr.push('"');
              //if (this.columnname) gridhtmlarr.push('columnname="' + this.columnname + '"');
              gridhtmlarr.push(' style = "');
              gridhtmlarr.push('width:' + colwidth + 'px; ');
              if (column._hide)
              {
                gridhtmlarr.push('display:none;');
              }
              gridhtmlarr.push(' ">');
              gridhtmlarr.push(g._getCellHtml(item, column));
              gridhtmlarr.push('</td>');
            });
            gridhtmlarr.push('</tr>');
          }
          return gridhtmlarr.join('');
        },
        onAfterShowData: function () {//显示完数据事件
          //【应用数据元编码】初始化注册select2（下拉框带查询）事件
          $(".sel-adapter-metadata-code").each(function(){
            comAdapterMetaData($(this),"init","adapterMetadataCode","adapterMetadataName");
          });
          //【应用数据元名称】初始化注册select2（下拉框带查询）事件
          $(".sel-adapter-metadata-name").each(function(){
            comAdapterMetaData($(this),"init","adapterMetadataName","adapterMetadataCode");
          });
          //【源数据集编码】初始化注册select2（下拉框带查询）事件
          $(".sel-adapter-dataset-code").each(function(){
            comAdapterDataset($(this),"init","adapterDatasetCode","adapterDatasetName");
          });
          //【源数据集名称】初始化注册select2（下拉框带查询）事件
          $(".sel-adapter-dataset-name").each(function(){
            comAdapterDataset($(this),"init","adapterDatasetName","adapterDatasetCode");
          });
          //【目标字典项编码】初始化注册select2（下拉框带查询）事件
          $(".sel-std-dictEntry-code").each(function(){
            comStdDictEntry($(this),"init","stdEntryCode","stdEntryValue");
          });
          //【目标字典项名称】初始化注册select2（下拉框带查询）事件
          $(".sel-std-dictEntry-value").each(function(){
            comStdDictEntry($(this),"init","stdEntryValue","stdEntryCode");
          });
          //【应用字典编码】初始化注册select2（下拉框带查询）事件
          $(".sel-adapter-dict-code").each(function(){
            comAdapterDict($(this),"init","adapterDictCode","adapterDictName");
          });
          //【应用字典名称】初始化注册select2（下拉框带查询）事件
          $(".sel-adapter-dict-name").each(function(){
            comAdapterDict($(this),"init","adapterDictName","adapterDictCode");
          });
          //【应用字典项编码】初始化注册select2（下拉框带查询）事件
          $(".sel-adapter-dictEntry-code").each(function(){
            comAdapterDictEntry($(this),"init","adapterEntryCode","adapterEntryValue");
          });
          //【应用字典名称】初始化注册select2（下拉框带查询）事件
          $(".sel-adapter-dictEntry-value").each(function(){
            comAdapterDictEntry($(this),"init","adapterEntryValue","adapterEntryCode");
          });

          //【源数据集编码】change事件
          $(".sel-adapter-dataset-code").on("change", function(event,msg) {
            var index = $(this).attr("id").replace("adapterDatasetCode","");
            var select2 =  comAdapterDataset($(this),"change","adapterDatasetCode","adapterDatasetName");
            comAdapterMetaData($("#adapterMetadataCode"+index),"change","adapterMetadataCode","adapterMetadataName");


            var datasetCodeOption = $(this).find("option");
            var datasetNameOption = $("#adapterDatasetName"+index).find("option");

            if(dataRows == entryMaster.grid.getData().length){
              if(dataFlag){
                $(".sel-adapter-dataset-code").each(function(){
                  var index = $(this).attr("id").replace("adapterDatasetCode","");
                  $(this).append(datasetCodeOption);
                  $("#adapterDatasetName"+index).append(datasetNameOption);
                  comAdapterDataset($(this),"change","adapterDatasetCode","adapterDatasetName");
                  comAdapterDataset($("#adapterDatasetName"+index),"change","adapterDatasetName","adapterDatasetCode");
                  comAdapterMetaData($("#adapterMetadataCode"+index),"change","adapterMetadataCode","adapterMetadataName");
                  comAdapterMetaData($("#adapterMetadataName"+index),"change","adapterMetadataName","adapterMetadataCode");
                });
                dataFlag = false;
              }
            }
            if(msg!="adapterDatasetCode"){//当【源数据集编码】联动时，【源数据集名称】不触发联动
              $("#adapterDatasetName"+index).trigger("change",["adapterDatasetName"]);
            }

            select2.select2("open");
            select2.select2("close");
          });
          //【源数据集名称】change事件
          $(".sel-adapter-dataset-name").on("change", function(event,msg) {

            var index = $(this).attr("id").replace("adapterDatasetName","");
            var select2 =  comAdapterDataset($(this),"change","adapterDatasetName","adapterDatasetCode");
            comAdapterMetaData($("#adapterMetadataCode"+index),"change","adapterMetadataCode","adapterMetadataName");
            comAdapterMetaData($("#adapterMetadataName"+index),"change","adapterMetadataName","adapterMetadataCode");
            if(msg!="adapterDatasetName"){//当【源数据集名称】联动时，【源数据集编码】不触发联动
              $("#adapterDatasetCode"+index).trigger("change","adapterDatasetCode");
            }
            select2.select2("open");
            select2.select2("close");
          });

          //【源数据元编码】change事件
          $(".sel-adapter-metadata-code").on("change", function(event,msg) {
            var index = $(this).attr("id").replace("adapterMetadataCode","");
            var select2 = comAdapterMetaData($(this),"change","adapterMetadataCode","adapterMetadataName");
            if(msg!="adapterMetadataCode"){//当【源数据元编码】联动时，【源数据元名称】不触发联动
              $("#adapterMetadataName"+index).trigger("change",["adapterMetadataName"]);
            }
            select2.select2("open");
            select2.select2("close");
          });
          //【源数据元名称】change事件
          $(".sel-adapter-metadata-name").on("change", function(event,msg) {

            var index = $(this).attr("id").replace("adapterMetadataName","");
            var select2 = comAdapterMetaData($(this),"change","adapterMetadataName","adapterMetadataCode");
            if(msg!="adapterMetadataName"){//当【源数据元名称】联动时，【源数据元编码】不触发联动
              $("#adapterMetadataCode"+index).trigger("change","adapterMetadataCode");
            }
            select2.select2("open");
            select2.select2("close");
            var selectValue = $("#adapterMetadataName"+index).val();
            if(selectValue!=null&&selectValue!=''&&selectValue!=undefined){
              $("#adapterInfo"+index).html("<option value='1' >疑似适配</option><option value='2' >完全适配</option>")
            }else{
              $("#adapterInfo"+index).html("<option value='0' >未适配</option>");
            }
          });
          //---------------------------------------------------------------------
          //【目标字典项编码】change事件
          $(".sel-std-dictEntry-code").on("change", function(event,msg) {
            var index = $(this).attr("id").replace("stdEntryCode","");//取出当前机构适配值的索引
            var select2 =  comStdDictEntry($(this),"change","stdEntryCode","stdEntryValue");
            if(msg!="stdEntryCode"){//当机构适配值联动时，机构适配名称不触发联动
              $("#stdEntryValue"+index).trigger("change",["stdEntryValue"]);
            }
            select2.select2("open");
            select2.select2("close");
          });
          //【目标字典项名称】change事件
          $(".sel-std-dictEntry-value").on("change", function(event,msg) {
            var index = $(this).attr("id").replace("stdEntryValue","");//取出当前机构适配名称的索引
            var select2 =  comStdDictEntry($(this),"change","stdEntryValue","stdEntryCode");
            if(msg!="stdEntryValue"){//当机构适配名称联动时，机构适配值不触发联动
              $("#stdEntryCode"+index).trigger("change","stdEntryCode");
            }
            select2.select2("open");
            select2.select2("close");
          });

          //【源字典编码】change事件
          $(".sel-adapter-dict-code").on("change", function(event,msg) {

            var index = $(this).attr("id").replace("adapterDictCode","");//取出当前机构适配值的索引
            var select2 =  comAdapterDict($(this),"change","adapterDictCode","adapterDictName");
            comAdapterDictEntry($("#adapterEntryCode"+index),"change","adapterEntryCode","adapterEntryValue");

            var dictCodeOption = $(this).find("option");
            var dictEntryOption = $("#adapterDictName"+index).find("option");
            if(dataRows == entryMaster.grid.getData().length){
              if(dataFlag){
                $(".sel-adapter-dict-code").each(function(){
                  var index = $(this).attr("id").replace("adapterDictCode","");
                  $(this).append(dictCodeOption);
                  $("#adapterDictName"+index).append(dictEntryOption);
                  comAdapterDict($(this),"change","adapterDictCode","adapterDictName");
                  comAdapterDict($("#adapterDictName"+index),"change","adapterDictName","adapterDictCode");
                  comAdapterDictEntry($("#adapterEntryCode"+index),"change","adapterEntryCode","adapterEntryValue");
                  comAdapterDictEntry($("#adapterEntryValue"+index),"change","adapterEntryValue","adapterEntryCode");
                });
                dataFlag = false;
              }
            }
            if(msg!="adapterDictCode"){//当机构适配值联动时，机构适配名称不触发联动
              $("#adapterDictName"+index).trigger("change",["adapterDictName"]);
            }
            select2.select2("open");
            select2.select2("close");
          });
          //【源字典名称】change事件
          $(".sel-adapter-dict-name").on("change", function(event,msg) {
            var index = $(this).attr("id").replace("adapterDictName","");//取出当前机构适配名称的索引
            var select2 =  comAdapterDict($(this),"change","adapterDictName","adapterDictCode");
            comAdapterDictEntry($("#adapterEntryCode"+index),"change","adapterEntryCode","adapterEntryValue");
            comAdapterDictEntry($("#adapterEntryValue"+index),"change","adapterEntryValue","adapterEntryCode");
            if(msg!="adapterDictName"){//当机构适配名称联动时，机构适配值不触发联动
              $("#adapterDictCode"+index).trigger("change","adapterDictCode");
            }
            select2.select2("open");
            select2.select2("close");
          });

          //【源字典项编码】change事件
          $(".sel-adapter-dictEntry-code").on("change", function(event,msg) {
            var index = $(this).attr("id").replace("adapterEntryCode","");//取出当前机构适配值的索引
            var select2 =  comAdapterDictEntry($(this),"change","adapterEntryCode","adapterEntryValue");
            if(msg!="adapterEntryCode"){//当机构适配值联动时，机构适配名称不触发联动
              $("#adapterEntryValue"+index).trigger("change",["adapterEntryValue"]);
            }
            select2.select2("open");
            select2.select2("close");
          });
          //【源字典项名称】change事件
          $(".sel-adapter-dictEntry-value").on("change", function(event,msg) {
            var index = $(this).attr("id").replace("adapterEntryValue","");//取出当前机构适配名称的索引
            var select2 =  comAdapterDictEntry($(this),"change","adapterEntryValue","adapterEntryCode");
            if(msg!="adapterEntryValue"){//当机构适配名称联动时，机构适配值不触发联动
              $("#adapterEntryCode"+index).trigger("change","adapterEntryCode");
            }
            select2.select2("open");
            select2.select2("close");
            debugger
            var selectValue = select2.val();
            if(selectValue!=null&&selectValue!=''&&selectValue!=undefined){
              $("#adapterInfo"+index).html("<option value='1' >疑似适配</option><option value='2' >完全适配</option>")
            }else{
              $("#adapterInfo"+index).html("<option value='0' >未适配</option>");
            }
          });
        }
      });

      this.bindEvents();
    },
    reloadGrid: function (parentId) {

      var searchNmEntry = $("#searchNmEntry").val();
      if(Util.isStrEmpty(parentId)){
        var row = master.grid.getSelectedRow();
        if(row != null){
          parentId = row.id;
        }
      }
      var values = {
        adapterVersion:$("#version").val(),
        condition: JSON.stringify({"name":searchNmEntry,"stdDatasetId":parentId,"stdDictId":parentId})
      };
      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;
    },
    add:function(){
      if(master.grid.getData().length==0){
        $.ligerDialog.error("没有目标字典，不能新增字典项！");
        return  false;
      }
      var dataRow = {
        stdDictId:$("#std_dict_id").val(),
        schemeId:$("#scheme_id").val(),
        adapterDictId:'',
        stdEntryId:'',
        adapterEntryId:'',
        adapterDictCode:'',
        adapterDictName:'',
        stdEntryCode:'',
        stdEntryValue:'',
        adapterEntryCode:'',
        adapterEntryValue:''
      };
      //参数1:rowdata(非必填)
      //参数2:插入的位置 Row Data
      var rowData = entryMaster.grid.getData();
      for (var i = 0; i < rowData.length; i++) {
        entryMaster.grid.rows[i].schemeId = $("#scheme_id").val();
        entryMaster.grid.rows[i].stdDictId = $("#std_dict_id").val();
        var stdEntryCodeArr = $("#stdEntryCode"+i).val()==undefined ? "":$("#stdEntryCode"+i).val().split(",");
        if(stdEntryCodeArr.length>0){
          entryMaster.grid.rows[i].stdEntryId = stdEntryCodeArr[0];
          entryMaster.grid.rows[i].stdEntryValue = stdEntryCodeArr[1];
        }else{
          entryMaster.grid.rows[i].stdEntryId = "";
          entryMaster.grid.rows[i].stdEntryValue = "";
        }
        entryMaster.grid.rows[i].stdEntryCode = $("#stdEntryCode"+i).text() == undefined ? "" : $("#stdEntryCode"+i).text();
        var adapterDictCodeArr = $("#adapterDictCode"+i).val()==undefined ? "":$("#adapterDictCode"+i).val().split(",");
        if(adapterDictCodeArr.length>0){
          entryMaster.grid.rows[i].adapterDictId = adapterDictCodeArr[0];
          entryMaster.grid.rows[i].adapterDictName = adapterDictCodeArr[1];
        }else{
          entryMaster.grid.rows[i].adapterDictId = "";
          entryMaster.grid.rows[i].adapterDictName = "";
        }
        entryMaster.grid.rows[i].adapterDictCode = $("#adapterDictCode"+i).text() == undefined ? "" : $("#adapterDictCode"+i).text();
        var adapterEntryCodeArr = $("#adapterEntryCode"+i).val()==undefined ? "":$("#adapterEntryCode"+i).val().split(",");
        if(adapterEntryCodeArr.length>0){
          entryMaster.grid.rows[i].adapterEntryId = adapterEntryCodeArr[0];
          entryMaster.grid.rows[i].adapterEntryValue = adapterEntryCodeArr[1];
        }else{
          entryMaster.grid.rows[i].adapterEntryId = "";
          entryMaster.grid.rows[i].adapterEntryValue = "";
        }
        entryMaster.grid.rows[i].adapterEntryCode = $("#adapterEntryCode"+i).text() == undefined ? "" : $("#adapterEntryCode"+i).text();
      }
      entryMaster.grid.addRow(dataRow);
    },
    delete:function(rowindex,flag){
      $.ligerDialog.confirm('确定清空该适配关系？', function (r) {
        if (r) {
          $("#adapterInfo"+rowindex).html("<option value='0'>未适配</option>");
          if(flag == "dataset"){//数据集
            $("#adapterDatasetCode"+rowindex).html("");
            $("#adapterDatasetName"+rowindex).html("");
            $("#adapterMetadataCode"+rowindex).html("");
            $("#adapterMetadataName"+rowindex).html("");
            comAdapterDataset($("#adapterDatasetCode"+rowindex),"change","adapterDatasetCode","adapterDatasetName");
            comAdapterDataset($("#adapterDatasetName"+rowindex),"change","adapterDatasetName","adapterDatasetCode");
            comAdapterMetaData($("#adapterMetadataCode"+rowindex),"change","adapterMetadataCode","adapterMetadataName");
            comAdapterMetaData($("#adapterMetadataName"+rowindex),"change","adapterMetadataName","adapterMetadataCode");

            //重新计算表格中的值是否都被清空
            dataRows = 0;
            $(".sel-adapter-dataset-code").each(function(){
              if(Util.isStrEmpty($(this).val())){
                dataRows ++;
              }
            });
            if(dataRows == entryMaster.grid.getData().length) {
              dataFlag = true;
            }
          }else{//字典
            $("#adapterDictCode"+rowindex).html("");
            $("#adapterDictName"+rowindex).html("");
            $("#adapterEntryCode"+rowindex).html("");
            $("#adapterEntryValue"+rowindex).html("");
            comAdapterDict($("#adapterDictCode"+rowindex),"change","adapterDictCode","adapterDictName");
            comAdapterDict($("#adapterDictName"+rowindex),"change","adapterDictName","adapterDictCode");
            comAdapterDictEntry($("#adapterEntryCode"+rowindex),"change","adapterEntryCode","adapterEntryValue");
            comAdapterDictEntry($("#adapterEntryValue"+rowindex),"change","adapterEntryValue","adapterEntryCode");

            //重新计算表格中的值是否都被清空
            dataRows = 0;
            $(".sel-adapter-dict-code").each(function(){
              if(Util.isStrEmpty($(this).val())){
                dataRows ++;
              }
            });
            if(dataRows == entryMaster.grid.getData().length) {
              dataFlag = true;
            }
          }

        }
      });
    },
    save:function(){
      if (cfgModel == 0) {
        var dataResult = new Array();
        var rowData = entryMaster.grid.getData();
        for (var i = 0; i < rowData.length; i++) {
          var ob = new Object();
          ob.id = rowData[i].id == undefined ? "" : rowData[i].id;
          ob.schemeId = rowData[i].schemeId == undefined ? "" : rowData[i].schemeId;
          ob.stdDatasetId = rowData[i].stdDatasetId == undefined ? "" : rowData[i].stdDatasetId;
          ob.stdMetadataId = rowData[i].stdMetadataId == undefined ? "" : rowData[i].stdMetadataId;
          ob.stdMetadataCode = rowData[i].stdMetadataCode == undefined ? "" : rowData[i].stdMetadataCode;
          ob.stdMetadataName = rowData[i].stdMetadataName == undefined ? "" : rowData[i].stdMetadataName;
          ob.adapterDataType = rowData[i].adapterDataType == undefined ? "" : $("#adapterDataType"+i).val();
          ob.adapterDatasetId = rowData[i].adapterDatasetId == undefined ? "" : rowData[i].adapterDatasetId;
          ob.adapterDatasetCode = rowData[i].adapterDatasetCode == undefined ? "" : rowData[i].adapterDatasetCode;
          ob.adapterDatasetName = rowData[i].adapterDatasetName == undefined ? "" : rowData[i].adapterDatasetName;
          ob.stdDictId = rowData[i].stdDictId == undefined ? "" : rowData[i].stdDictId;
          var adapterDatasetCodeArr = $("#adapterDatasetCode"+i).val()==undefined ? "":$("#adapterDatasetCode"+i).val().split(",");
          debugger
          if(adapterDatasetCodeArr.length>0){
            ob.adapterDatasetId = adapterDatasetCodeArr[0];
            ob.adapterDatasetName = adapterDatasetCodeArr[1];
          }else {
            ob.adapterDatasetId = "";
            ob.adapterDatasetName = "";
          }
          ob.adapterInfo  = $("#adapterInfo"+i).val();
          ob.adapterDatasetCode = $("#adapterDatasetCode"+i).text() == undefined ? "" : $("#adapterDatasetCode"+i).text();
          var adapterMetadataCodeArr = $("#adapterMetadataCode"+i).val()==undefined ? "":$("#adapterMetadataCode"+i).val().split(",");
          if(adapterMetadataCodeArr.length>0){
            ob.adapterMetadataId = adapterMetadataCodeArr[0];
            ob.adapterMetadataName = adapterMetadataCodeArr[1];
            if(adapterMetadataCodeArr.length >2){
              ob.adapterDictId = adapterMetadataCodeArr[2];
            }else {
              ob.adapterDictId = "";
            }
          }else {
            ob.adapterMetadataId = "";
            ob.adapterMetadataName = "";
          }
          ob.adapterMetadataCode = $("#adapterMetadataCode"+i).text() == undefined ? "" : $("#adapterMetadataCode"+i).text();
          debugger
          dataResult.push(ob)
        }
        //保存数据
        $.ajax({
          type : "POST",
          url: '${contextRoot}'+'/adapterCenter/updateMetadatas',
          data: 'list='+JSON.stringify(dataResult)+"&adapterVersion="+$("#version").val(),
          dataType : "json",
          async:false,
          success :function(data){
            if(data.successFlg){
              entryMaster.reloadGrid(); //重新查询，返回json记录集
              $.ligerDialog.success(data.message);
            }else{
              $.ligerDialog.error(data.message);
            }

          },
          error :function(data){
            $.ligerDialog.error("保存失败！");
          }
        });
      } else {
        var dataResult = new Array();
        var rowData = entryMaster.grid.getData();

        for (var i = 0; i < rowData.length; i++) {
          var ob = new Object();

          ob.id = rowData[i].id == undefined ? "" : rowData[i].id;
          ob.schemeId = $("#scheme_id").val();
          ob.stdDictId = $("#std_dict_id").val();
          var stdEntryCodeArr = $("#stdEntryCode"+i).val()==undefined ? "":$("#stdEntryCode"+i).val().split(",");
          if(stdEntryCodeArr.length>0){
            if(stdEntryCodeArr[0]=="" || stdEntryCodeArr[1]==""){
              $.ligerDialog.error("第"+Number(i+1)+"条记录：目标字典项编码和目标字典项值不能为空！");
              return false;
            }
            ob.stdEntryId = stdEntryCodeArr[0];
            ob.stdEntryValue = stdEntryCodeArr[1];
          }
          ob.stdEntryCode = $("#stdEntryCode"+i).text() == undefined ? "" : $("#stdEntryCode"+i).text();
          ob.adapterInfo  = $("#adapterInfo"+i).val();
          var adapterDictCodeArr = $("#adapterDictCode"+i).val()==undefined ? "":$("#adapterDictCode"+i).val().split(",");
          if(adapterDictCodeArr.length>0){
            ob.adapterDictId = adapterDictCodeArr[0];
            ob.adapterDictName = adapterDictCodeArr[1];
          }else{
            ob.adapterDictId = "";
            ob.adapterDictName = "";
          }
          ob.adapterDictCode = $("#adapterDictCode"+i).text() == undefined ? "" : $("#adapterDictCode"+i).text();
          var adapterEntryCodeArr = $("#adapterEntryCode"+i).val()==undefined ? "":$("#adapterEntryCode"+i).val().split(",");
          if(adapterEntryCodeArr.length>0){
            ob.adapterEntryId = adapterEntryCodeArr[0];
            ob.adapterEntryValue = adapterEntryCodeArr[1];
          }else{
            ob.adapterEntryId = "";
            ob.adapterEntryValue = "";
          }
          ob.adapterEntryCode = $("#adapterEntryCode"+i).text() == undefined ? "" : $("#adapterEntryCode"+i).text();

          dataResult.push(ob)
        }

        var uniqueArray = entryMaster.uniqueArray(dataResult);
        if(dataResult.length!==uniqueArray.length){
          $.ligerDialog.error("在同一个适配方案下，同一个目标标准字典对应的目标字典项和源字典项不可重复！");
          return false;
        }
        //保存数据
        $.ajax({
          type : "POST",
          url: '${contextRoot}'+'/adapterCenter/updateDictEntrys',
          data: 'list='+JSON.stringify(dataResult)+"&adapterVersion="+$("#version").val(),
          dataType : "json",
          async:false,
          success :function(data){

            if(data.successFlg){
              entryMaster.reloadGrid(); //重新查询，返回json记录集
              $.ligerDialog.success(data.message);
            }else{
              $.ligerDialog.error(data.message);
            }

          },
          error :function(data){
            $.ligerDialog.error("保存失败！");
          }
        });
      }
    },
    /**########数据集 BEGIN#########**/
    isAdaptationIng:function(){
      var version = $("#version").val();
      var self=this;//为了获取项目id
      var url="";//AdapterDatasetController
      var obj="";//为了获取进度条
      var isDataSet = $("#isDataSet").val();
      if(isDataSet!="0"){//数据集
        obj=self.$shujujiZdsp
        url="${contextRoot}/adapterCenter/isStrategy"
      }
      var isCanPlay= setInterval(function(){//判断 是否可以开始匹配了
        $.ajax({
          type:"POST",
          dataType:"",
          url:url,
          data:{version:version},
          success:function(res){
            var isPPing=JSON.parse(res.data).isAdapt//是否正在匹配
            if(isPPing=="false"){//如果不是正在匹配
              self.pipeiDo();//开始匹配
            }else{//如果正在匹配
              self.autoAdaptation(obj);//显示进度
              clearInterval(isCanPlay)
            }
          }
        })
      },3000)
    },
    pipeiDo:function(){
      var std_version = $("#std_version").val();
      var version = $("#version").val();
      var adapter_std_version = $("#adapter_std_version").val();
      var parmas = {std_version:std_version,version:version,adapter_std_version:adapter_std_version};
      var self=this;
      var obj;//当前属于字典还是数据集对象,赋值匹配中
      var btnObj//自动匹配的按钮
      var url//链接
      var isDataSet = $("#isDataSet").val();
      if(isDataSet=="0"){//字典
        obj=$("#zidian .boxleft");
        url="${contextRoot}/adapterCenter/strategyDic"
      }else{//数据集
        obj=$("#shujuji .boxleft");
        url="${contextRoot}/adapterCenter/strategy"
      }
      $("#btn_aoto_adpat span").html("匹配中...");
      $.ajax({
        type:"POST",
        dataType:"json",
        url:url,
        data:parmas,
        success:function(data){
          $("#btn_aoto_adpat span").html("自动适配");
        },
        error:function(){

        }
      })
    },//开始匹配
    autoAdaptation:function(){
      var self=this;
      var url=""//进度
      var isDataSet = $("#isDataSet").val();
      var version = $("#version").val();
      if(isDataSet=="0"){//字典
        url="${contextRoot}/adapterCenter/getStrategyDicSize"
      }else{//数据集
        url="${contextRoot}/adapterCenter/getStrategySize"
      }
      var timeIng =setInterval(function(){
        var ver =
                $.ajax({
                  type:"POST",
                  dataType:"json",
                  url:url,
                  data:{version:version},
                  success:function(res){
                    if(res.data==undefined){
                      $("#btn_aoto_adpat span").html("请求中");
                    }else{
                      if(res.data.all==0){//如果判断被除数不能为0  如果为0 直接清空
                        $("#btn_aoto_adpat span").html("匹配完成");
                        clearInterval(timeIng);
                        self.ppeiEnd()//结束匹配
                      }else{
                        var jdu=  res.data.adapt/res.data.all//进度
                        if(jdu!=1){

                          var jduBFB=parseInt(jdu*100)
                          if(!isNaN(jduBFB)){
                            $("#btn_aoto_adpat span").html("已匹配"+jduBFB+"%")
                          }

                        }else{
                          $("#btn_aoto_adpat span").html("匹配完成");
                          master.reloadGrid();
                          clearInterval(timeIng);
                          self.ppeiEnd()//结束匹配
                        }
                      }
                    }

                  },
                  error :function(res){
                  }
                })
      },3000)
    },//自动匹配进度
    ppeiEnd:function(){
      var self=this;
      var url="";
      var isDataSet = $("#isDataSet").val()
      if(isDataSet!="0"){//数据集
        url="${contextRoot}/adapterCenter/endStrategy"
      }
      $.ajax({
        type:"POST",
        dataType:"json",
        url:url,
        data:{version:$("#version").val()},
        success:function(res){
        },
        error :function(res){
        }
      })
    },//结束匹配
    /**########数据集 END#########**/
    /**########字典 BEGIN#########**/
    isAdaptationIngDic:function(){
      var version = $("#version").val();
      var self=this;//为了获取项目id
      var url="";//AdapterDatasetController
      var obj="";//为了获取进度条
      var isDataSet = $("#isDataSet").val();
      if(isDataSet=="0"){//字典
        obj=self.$zidianZdsp
        url="${contextRoot}/adapterCenter/isStrategyDic"
      }
      var isCanPlay= setInterval(function(){//判断 是否可以开始匹配了
        $.ajax({
          type:"POST",
          dataType:"",
          url:url,
          data:{version:version},
          success:function(res){
            var isPPing=JSON.parse(res.data).isAdapt//是否正在匹配
            if(isPPing=="false"){//如果不是正在匹配
              self.pipeiDoDic();//开始匹配
            }else{//如果正在匹配
              self.autoAdaptationDic(obj);//显示进度
              clearInterval(isCanPlay)
            }
          }
        })
      },3000)
    },
    pipeiDoDic:function(){
      var std_version = $("#std_version").val();
      var version = $("#version").val();
      var adapter_std_version = $("#adapter_std_version").val();
      var parmas = {std_version:std_version,version:version,adapter_std_version:adapter_std_version};
      var self=this;
      var obj;//当前属于字典还是数据集对象,赋值匹配中
      var btnObj//自动匹配的按钮
      var url//链接
      var isDataSet = $("#isDataSet").val();
      if(isDataSet=="0"){//字典
        obj=$("#zidian .boxleft");
        url="${contextRoot}/adapterCenter/strategyDic"
      }
      $("#btn_aoto_adpat_dic span").html("匹配中...");
      $.ajax({
        type:"POST",
        dataType:"json",
        url:url,
        data:parmas,
        success:function(data){
          $("#btn_aoto_adpat_dic span").html("自动适配");
        },
        error:function(){

        }
      })
    },//开始匹配
    autoAdaptationDic:function(){
      var self=this;
      var url=""//进度
      var isDataSet = $("#isDataSet").val();
      var version = $("#version").val();
      if(isDataSet=="0"){//字典
        url="${contextRoot}/adapterCenter/getStrategyDicSize"
      }
      var timeIng =setInterval(function(){
        var ver =
                $.ajax({
                  type:"POST",
                  dataType:"json",
                  url:url,
                  data:{version:version},
                  success:function(res){
                    if(res.data==undefined){
                      $("#btn_aoto_adpat_dic span").html("请求中");
                    }else{
                      if(res.data.all==0){//如果判断被除数不能为0  如果为0 直接清空
                        $("#btn_aoto_adpat_dic span").html("匹配完成");
                        clearInterval(timeIng);
                        self.ppeiEndDic()//结束匹配
                      }else{
                        var jdu=  res.data.adapt/res.data.all//进度
                        if(jdu!=1){

                          var jduBFB=parseInt(jdu*100)
                          if(!isNaN(jduBFB)){
                            $("#btn_aoto_adpat_dic span").html("已匹配"+jduBFB+"%")
                          }
                        }else{
                          $("#btn_aoto_adpat_dic span").html("匹配完成");
                          master.reloadGrid();
                          clearInterval(timeIng);
                          self.ppeiEndDic()//结束匹配
                        }
                      }
                    }

                  }
                })
      },3000)
    },//自动匹配进度
    ppeiEndDic:function(){
      var self=this;
      var url="";
      var isDataSet = $("#isDataSet").val()
      if(isDataSet=="0"){//字典
        url="${contextRoot}/adapterCenter/endStrategyDic"
      }else{//数据集
        url="${contextRoot}/adapterCenter/endStrategy"
      }
      $.ajax({
        type:"POST",
        dataType:"json",
        url:url,
        data:{version:$("#version").val()},
        success:function(res){

        }
      })
    },//结束匹配
    /**########字典 END#########**/
    uniqueArray:function(a){ /* 判断适配方案id、目标字典id、目标字典项id、源字典项id是否重复*/
      var temp = new Array();
      for(var i = 0; i < a.length; i ++){
        if(!entryMaster.contains(temp, a[i].schemeId + a[i].stdDictId+a[i].stdEntryId + a[i].adapterEntryId)){
          temp.length+=1;
          temp[temp.length-1] = a[i].schemeId + a[i].stdDictId+a[i].stdEntryId + a[i].adapterEntryId;
        }
      }
      return temp;
    },
    contains:function(a,e){
      for(j=0;j<a.length;j++)if(a[j]==e)return true;
      return false
    },
    bindEvents: function () {

      //窗体改变大小事件
      $(window).bind('resize', function() {
        resizeContent();
      });

      $('#btn_add_relation').click(function () {
        entryMaster.add();;
      });

      $('#btn_save_relation').click(function () {
        entryMaster.save();
      });

      //数据集
      $('#btn_aoto_adpat').click(function () {
        entryMaster.isAdaptationIng();
      });
      //字典
      $('#btn_aoto_adpat_dic').click(function () {
        entryMaster.isAdaptationIngDic();
      });

      $("#searchNmEntry").keyup(function (e) {
        if (e.keyCode == 13) {
          entryMaster.reloadGrid();
        }
      });
    },
    getColumn: function () {
      var columnCfg =[];
      var width;
      if(status=="1"){//已发布
        width = ["15%","15%","15%","15%","15%","12%","12%"];
      }else{//未发布
        width = ["12%","12%","12%","15%","12%","15%","12%"];
      }

      if(cfgModel==0){
        columnCfg = [
          { display: 'id', name: 'id', hide:true },
          { display: 'stdDatasetId', name: 'stdDatasetId', hide:true },
          { display: 'stdMetadataId', name: 'stdMetadataId', hide:true },
          { display: 'adapterDatasetId', name: 'adapterDatasetId', hide:true },
          { display: 'adapterMetadataId', name: 'adapterMetadataId', hide:true },
          { display: 'adapterDataType', name: 'adapterDataType', hide:true },
          { display: '目标数据元编码', name: 'stdMetadataCode',width: width[0], isAllowHide: false ,align:'left' },
          { display: '目标数据元名称', name: 'stdMetadataName',width: width[1], isAllowHide: false ,align:'left' },
          { display: '源数据集编码', name: 'adapterDatasetCode', width: width[2], render: function (row, rowindex, value, column) {
            if(status =="1"){//已发布
              return row.adapterDatasetCode;
            }else{//未发布
              var select=null;
              if(row.adapterDatasetId==undefined || row.adapterDatasetCode==undefined || row.adapterDatasetName==undefined){
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-dataset-code"  id="adapterDatasetCode'+rowindex +'" ></select></div>');
                dataRows++;
                debugger
              }else{
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-dataset-code"  id="adapterDatasetCode'+rowindex+'" >'
                        +'<option value="'+row.adapterDatasetId+','+row.adapterDatasetName+'">'+row.adapterDatasetCode+'</option></select></div>');
             debugger
              }
              $('option[value="'+value+'"]',select).attr('selected',true);
              return  select.prop("outerHTML");
            }
          }},
          { display: '源数据集名称', name: 'adapterDatasetName', width: width[3], render: function (row, rowindex, value, column) {
            if(status =="1"){//已发布
              return row.adapterDatasetName;
            }else{//未发布
              var select=null;
              if(row.adapterDatasetId==undefined || row.adapterDatasetCode==undefined || row.adapterDatasetName==undefined){
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-dataset-name"  id="adapterDatasetName'+rowindex +'" ></select></div>');
              }else{
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-dataset-name"  id="adapterDatasetName'+rowindex +'" >'
                        +'<option value="'+row.adapterDatasetId+','+row.adapterDatasetCode+'">'+row.adapterDatasetName+'</option></select></div>');
              }
              $('option[value="'+value+'"]',select).attr('selected',true);
              return  select.prop("outerHTML");
            }
          }},
          { display: '源数据元编码', name: 'adapterMetadataCode', width: width[4], render: function (row, rowindex, value, column) {
            if(status =="1"){//已发布
              return row.adapterMetadataCode;
            }else {//未发布
              var select=null;
              if(row.adapterMetadataId==undefined || row.adapterMetadataCode==undefined || row.adapterMetadataName==undefined){
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-metadata-code"  id="adapterMetadataCode'+rowindex +'" ></select></div>');
              }else{
                if(row.adapterDictId==undefined) {
                  select = $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-metadata-code"  id="adapterMetadataCode'+rowindex+'" >'
                          +'<option value="'+row.adapterMetadataId+','+row.adapterMetadataName+'">'+row.adapterMetadataCode+'</option></select></div>');
                }else {
                  select= $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-metadata-code"  id="adapterMetadataCode'+rowindex+'" >'
                          +'<option value="'+row.adapterMetadataId+','+row.adapterMetadataName+','+row.adapterDictId +'">'+row.adapterMetadataCode+'</option></select></div>');
                }
              }
              $('option[value="'+value+'"]',select).attr('selected',true);
              return  select.prop("outerHTML");
            }
          }},
          { display: '源数据元名称', name: 'adapterMetadataName', width: width[5], render: function (row, rowindex, value, column) {
            if(status =="1"){//已发布
              return row.adapterMetadataName;
            }else {//未发布
              var select=null;
              if(row.adapterMetadataId==undefined || row.adapterMetadataCode==undefined || row.adapterMetadataName==undefined){
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-metadata-name"  id="adapterMetadataName'+rowindex +'" ></select></div>');
              }else{
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-metadata-name"  id="adapterMetadataName'+rowindex +'" >'
                        +'<option value="'+row.adapterMetadataId+','+row.adapterMetadataCode+'">'+row.adapterMetadataName+'</option></select></div>');
              }
              $('option[value="'+value+'"]',select).attr('selected',true);
              return  select.prop("outerHTML");
            }
          }},
          { display: '源数据元类型', name: 'adapterDataType', width: width[6], render: function (row, rowindex, value, column) {

            if(status =="1"){//已发布
              if(row.adapterDataType == 1) {
                return "编码";
              }else{
                return "值"
              }
            }else {//未发布
              var select= $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-metadata-type"  id="adapterDataType'+rowindex +'" >'
                      +'<option value="0">'+'值'+'</option>'
                      +'<option value="1">'+'编码'+'</option></select></div>');

              if(row.adapterDataType == null){
                value = 0;
              }

              $('option[value="'+value+'"]',select).attr('selected',true);
              return  select.prop("outerHTML");
            }
          }},{
            display:'适配情况',name:'adapterInfo',width:'5%',render: function (row, rowindex, value, column) {
              var select=null;
              if(row.adapterDatasetId==undefined || row.adapterDatasetCode==undefined || row.adapterDatasetName==undefined){
                select= $('<div class="f-mt25"><select class="js-example-data-array" id="adapterInfo'+rowindex+'" ><option value="0">未适配</option></select></div>');
              }else{
                select= $('<div class="f-mt25"><select class="js-example-data-array" id="adapterInfo'+rowindex+'">'
                        +'<option value="1" >疑似适配</option><option value="2">完全适配</option></select></div>');
              }
              $('option[value="'+value+'"]',select).attr('selected',true);
              return  select.prop("outerHTML");
            }
          }
        ]

        if(status =="0"){//未发布
          columnCfg.push({ 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-clear" onclick="entryMaster.delete(\''+rowindex+'\',\'dataset\')"></a>';
            return html;
          }});
        }
      }
      else{
        columnCfg = [
          { display: 'id', name: 'id', hide:true },
          { display: 'stdDictId', name: 'stdDictId', hide:true },
          { display: 'stdEntryId', name: 'stdEntryId', hide:true },
          { display: 'adapterDictId', name: 'adapterDictId', hide:true },
          { display: 'adapterEntryId', name: 'adapterEntryId', hide:true },
          { display: '目标字典项编码', name: 'stdEntryCode', width: width[0], render: function (row, rowindex, value, column) {
            if(status =="1"){//已发布
              return row.stdEntryCode;
            }else {//未发布
              var select=null;
              if(row.stdEntryId==undefined || row.stdEntryCode==undefined || row.stdEntryValue==undefined){
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-std-dictEntry-code"  id="stdEntryCode'+rowindex +'" ></select></div>');
              }else{
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-std-dictEntry-code"  id="stdEntryCode'+rowindex+'" >'
                        +'<option value="'+row.stdEntryId+','+row.stdEntryValue+'">'+row.stdEntryCode+'</option></select></div>');
              }
              $('option[value="'+value+'"]',select).attr('selected',true);
              return  select.prop("outerHTML");
            }
          }},
          { display: '目标字典项值', name: 'stdEntryValue', width: width[1], render: function (row, rowindex, value, column) {
            if(status =="1"){//已发布
              return row.stdEntryValue;
            }else {//未发布
              var select=null;
              if(row.stdEntryId==undefined || row.stdEntryCode==undefined || row.stdEntryValue==undefined){
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-std-dictEntry-value"  id="stdEntryValue'+rowindex +'" ></select></div>');
              }else{
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-std-dictEntry-value"  id="stdEntryValue'+rowindex +'" >'
                        +'<option value="'+row.stdEntryId+','+row.stdEntryCode+'">'+row.stdEntryValue+'</option></select></div>');
              }
              $('option[value="'+value+'"]',select).attr('selected',true);
              return  select.prop("outerHTML");
            }
          }},
          { display: '源字典编码', name: 'adapterDictCode', width: width[2], render: function (row, rowindex, value, column) {
            if(status =="1"){//已发布
              return row.adapterDictCode;
            }else {//未发布
              var select=null;
              if(row.adapterDictId==undefined || row.adapterDictCode==undefined || row.adapterDictName==undefined){
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-dict-code"  id="adapterDictCode'+rowindex +'" ></select></div>');
                dataRows++;
              }else{
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-dict-code"  id="adapterDictCode'+rowindex+'" >'
                        +'<option value="'+row.adapterDictId+','+row.adapterDictName+'">'+row.adapterDictCode+'</option></select></div>');
              }
              $('option[value="'+value+'"]',select).attr('selected',true);
              return  select.prop("outerHTML");
            }
          }},
          { display: '源字典名称', name: 'adapterDictName', width: width[3], render: function (row, rowindex, value, column) {
            if(status =="1"){//已发布
              return row.adapterDictName;
            }else {//未发布
              var select=null;
              if(row.adapterDictId==undefined || row.adapterDictCode==undefined || row.adapterDictName==undefined){
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-dict-name"  id="adapterDictName'+rowindex +'" ></select></div>');
              }else{
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-dict-name"  id="adapterDictName'+rowindex +'" >'
                        +'<option value="'+row.adapterDictId+','+row.adapterDictCode+'">'+row.adapterDictName+'</option></select></div>');
              }
              $('option[value="'+value+'"]',select).attr('selected',true);
              return  select.prop("outerHTML");
            }
          }},
          { display: '源字典项编码', name: 'adapterEntryCode', width: width[4], render: function (row, rowindex, value, column) {
            if(status =="1"){//已发布
              return row.adapterEntryCode;
            }else {//未发布
              var select=null;
              if(row.adapterEntryId==undefined || row.adapterEntryCode==undefined || row.adapterEntryValue==undefined){
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-dictEntry-code"  id="adapterEntryCode'+rowindex +'" ></select></div>');
              }else{
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-dictEntry-code"  id="adapterEntryCode'+rowindex+'" >'
                        +'<option value="'+row.adapterEntryId+','+row.adapterEntryValue+'">'+row.adapterEntryCode+'</option></select></div>');
              }
              $('option[value="'+value+'"]',select).attr('selected',true);
              return  select.prop("outerHTML");
            }
          }},
          { display: '源字典项值', name: 'adapterEntryValue', width: width[5], render: function (row, rowindex, value, column) {
            if(status =="1"){//已发布
              return row.adapterEntryValue;
            }else {//未发布
              var select=null;
              if(row.adapterEntryId==undefined || row.adapterEntryCode==undefined || row.adapterEntryValue==undefined){
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-dictEntry-value"  id="adapterEntryValue'+rowindex +'" ></select></div>');
              }else{
                select= $('<div class="f-mt25"><select class="js-example-data-array sel-adapter-dictEntry-value"  id="adapterEntryValue'+rowindex +'" >'
                        +'<option value="'+row.adapterEntryId+','+row.adapterEntryCode+'">'+row.adapterEntryValue+'</option></select></div>');
              }
              $('option[value="'+value+'"]',select).attr('selected',true);
              return  select.prop("outerHTML");
            }
          }},{
            display:'适配情况',name:'adapterInfo',width:'5%',render: function (row, rowindex, value, column) {
              var select=null;
              if(row.adapterEntryId==undefined || row.adapterEntryCode==undefined || row.adapterEntryValue==undefined){
                select= $('<div class="f-mt25"><select class="js-example-data-array" id="adapterInfo'+rowindex+'" ><option value="0">未适配</option></select></div>');
              }else{
                select= $('<div class="f-mt25"><select class="js-example-data-array" id="adapterInfo'+rowindex+'">'
                        +'<option value="1" >疑似适配</option><option value="2">完全适配</option></select></div>');
              }
              $('option[value="'+value+'"]',select).attr('selected',true);
              return  select.prop("outerHTML");
            }
          }
        ]

        if(status =="0") {//未发布
          columnCfg.push({ 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-clear" onclick="entryMaster.delete(\''+rowindex+'\',\'dict\')"></a>';
            return html;
          }});
        }
      }
      return columnCfg;
    }
  };

  //源数据集编码-源数据集名称联动公共方法
  function comAdapterDataset(that,requestType,targer,changeTarget){
    var index =that.attr("id").replace(targer,"");
    var adapterStdVersion = $("#adapter_std_version").val();
    var arr = that.val()==null?[]:that.val().split(",");
    var url = '${contextRoot}' + "/standardCenter/getDatasetCodeValues?stdVersion="+adapterStdVersion+"&rows=10&order=";
    if(arr.length>0){
      if(targer=="adapterDatasetCode"){
        var selectText = "";
        $('#adapterDatasetCode'+index+' option').each(function () {
          if($(this).val()==(arr[0]+","+arr[1])){
            selectText = $(this).html();
            return false;
          }
        });
        url = '${contextRoot}' + "/standardCenter/getDatasetCodeValues?stdVersion="+adapterStdVersion+"&rows=9&order=&initVal="+selectText;//默认选中适配值
      }else{
        url = '${contextRoot}' + "/standardCenter/getDatasetCodeValues?stdVersion="+adapterStdVersion+"&rows=9&order=&initVal="+arr[1];//默认选中适配值
      }

    }
    return selectBind(that,arr,requestType,targer,changeTarget,index,url);
  }

  //源数据元编码-源数据元名称联动公共方法
  function comAdapterMetaData(that,requestType,targer,changeTarget){

    var index =that.attr("id").replace(targer,"");
    var adapterDatasetArr = $("#adapterDatasetCode"+index).val()==null?[]:$("#adapterDatasetCode"+index).val().split(",");
    var arr = that.val()==null?[]:that.val().split(",");
    var adapterStdVersion = $("#adapter_std_version").val();
    if (adapterDatasetArr.length>0) {
      var url = '${contextRoot}' + "/standardCenter/getMetadataCodeValues?stdVersion="+adapterStdVersion+"&datasetId="+adapterDatasetArr[0]+"&rows=10&order=";
      if(arr.length>0){
        url = '${contextRoot}' + "/standardCenter/getMetadataCodeValues?stdVersion="+adapterStdVersion+"&datasetId="+adapterDatasetArr[0]+"&rows=10&order=&initMetadataNm="+arr[1];//默认选中适配值
      }
    }
    return selectBind(that,arr,requestType,targer,changeTarget,index,url);
  }

  //目标字典项编码-目标字典项名称联动公共方法
  function comStdDictEntry(that,requestType,targer,changeTarget){
    var index="";
    if(!Util.isStrEmpty(that.attr("id"))){
      index =that.attr("id").replace(targer,"");
    }
    var stdVersion = $("#std_version").val();
    var arr = that.val()==null?[]:that.val().split(",");
    var url = '${contextRoot}' + "/standardCenter/getDictEntryCodeValues?stdVersion="+stdVersion+"&dictId="+$("#std_dict_id").val()+"&rows=10&order=";
    if(arr.length>0){
      url = '${contextRoot}' + "/standardCenter/getDictEntryCodeValues?stdVersion="+stdVersion+"&dictId="+$("#std_dict_id").val()+"&rows=10&order=&initDictValue="+arr[1];//默认选中适配值
    }
    return selectBind(that,arr,requestType,targer,changeTarget,index,url);
  }


  //源字典编码-源字典名称联动公共方法
  function comAdapterDict(that,requestType,targer,changeTarget){
    var index =that.attr("id").replace(targer,"");
    var adapterStdVersion = $("#adapter_std_version").val();
    var arr = that.val()==null?[]:that.val().split(",");
    var url = '${contextRoot}' + "/standardCenter/getDictCodeValues?stdVersion="+adapterStdVersion+"&rows=10&order=";
    if(arr.length>0){
      if(targer=="adapterDictCode"){
        var selectText = "";
        $('#adapterDictCode'+index+' option').each(function () {
          if($(this).val()==(arr[0]+","+arr[1])){
            selectText = $(this).html();
            return false;
          }
        });
        url = '${contextRoot}' + "/standardCenter/getDictCodeValues?stdVersion="+adapterStdVersion+"&rows=9&order=&initVal="+selectText;//默认选中适配值
      }else{
        url = '${contextRoot}' + "/standardCenter/getDictCodeValues?stdVersion="+adapterStdVersion+"&rows=9&order=&initVal="+arr[1];//默认选中适配值
      }
    }
    return selectBind(that,arr,requestType,targer,changeTarget,index,url);
  }

  //源字典项编码-源字典项名称联动公共方法
  function comAdapterDictEntry(that,requestType,targer,changeTarget){
    var index="";
    if(!Util.isStrEmpty(that.attr("id"))){
      index =that.attr("id").replace(targer,"");
    }

    var adapterDictCodeArr = $("#adapterDictCode"+index).val()==null?[]:$("#adapterDictCode"+index).val().split(",");
    var adapterStdVersion = $("#adapter_std_version").val();
    var arr = that.val()==null?[]:that.val().split(",");
    if (adapterDictCodeArr.length>0) {
      var url = '${contextRoot}' + "/standardCenter/getDictEntryCodeValues?stdVersion="+adapterStdVersion+"&dictId="+adapterDictCodeArr[0]+"&rows=10&order=";
      if(arr.length>0){
        url = '${contextRoot}' + "/standardCenter/getDictEntryCodeValues?stdVersion="+adapterStdVersion+"&dictId="+adapterDictCodeArr[0]+"&rows=10&order=&initDictValue="+arr[1];//默认选中适配值
      }
    }
    return selectBind(that,arr,requestType,targer,changeTarget,index,url);
  }

  function selectBind(that,arr,requestType,targer,changeTarget,index,url) {
    var selectId = "";
    var selectText = "";
    if(arr.length>0 && requestType=="change"){
      var option ="";
      if(arr.length >2 && arr[2]!=undefined) {
        option = '<option value="'+arr[0]+","+  $('#'+that.attr("id")).find("option:selected").text()+ "," + arr[2] +'">'+arr[1]+'</option>';
      }else {
        option = '<option value="'+arr[0]+","+  $('#'+that.attr("id")).find("option:selected").text()+'">'+arr[1]+'</option>';
      }
      $("#"+changeTarget+index).html("");
      $("#"+changeTarget+index).append(option);
      if(targer=="adapterDatasetCode" || targer=="adapterDatasetName" || targer=="adapterDictCode" || targer=="adapterDictName"){
        selectId =  arr[0]+","+ arr[1];
        selectText = $('#'+that.attr("id")).find("option:selected").text();
      }

    }else if(arr.length==0 && requestType=="change"){
      $("#"+changeTarget+index).html("");
    }
    if(Util.isStrEmpty(url)){
      var select2 =  that.select2({ placeholder: "只显示前10条结果",data:[]});
      return select2;
    }else{
      //查询下拉框数据
      var select2 =  that.select2({
        placeholder: "只显示前10条结果",
        ajax: {
          async:false,
          dataType : "json",
          url: url,
          processResults: function (data, page) {

            if(data.successFlg){
              if(targer=="adapterDatasetCode" || targer=="adapterMetadataCode"
                      || targer=="adapterDictCode" || targer=="adapterEntryCode" || targer=="stdEntryCode"){//由于机构适配值的数据格式为id：id+“，”+code，text：name，但是机构适配值为id:id+","+name,text:code,所以需要重新组装数据
                var toData;
                var toArr = [];
                var resultData = data.detailModelList||[];
                if(targer=="adapterDatasetCode" || targer=="adapterDictCode" && resultData.length>0){//查询结果有值，才填充原本选中的值
                  toArr.push({id:selectId,text:selectText});
                }

                for(var i=0;i<resultData.length;i++){
                  var name = resultData[i].text;
                  var id = "";
                  if(resultData[i].id.split(",").length >2) {
                    if(resultData[i].id.split(",")[2] != undefined) {
                      id = resultData[i].id==null?"": resultData[i].id.split(",")[0]+","+name + "," + resultData[i].id.split(",")[2];
                    }
                  }else {
                    id = resultData[i].id==null?"": resultData[i].id.split(",")[0]+","+name ;
                  }
                  var code =  resultData[i].id==null?"": resultData[i].id.split(",")[1];
                  toData = {id: id, text: code};
                  toArr.push(toData);
                }

                return {
                  results:undulpicate(toArr)
                };

              }else{//机构适配名称
                if(targer=="adapterDatasetName" || targer=="adapterDictName"){
                  var resultData = [];
                  var detailModelList = data.detailModelList;
                  if(detailModelList.length>0){
                    resultData.push({id:selectId,text:selectText});
                  }
                  for(var i=0;i<detailModelList.length;i++){
                    var  toData = {id: detailModelList[i].id, text: detailModelList[i].text};
                    resultData.push(toData);
                  }
                  return {
                    results:  undulpicate(resultData)
                  };
                }else{
                  return {
                    results:  data.detailModelList
                  };
                }

              }

            }else{
              $.ligerDialog.error(data.message);
            }


//                cache: true
          },
          escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
          minimumInputLength: 1,
        }
      })
      return select2;
    }

    function undulpicate(array){//删除数组重复元素
      array.sort();
      for(var i=0;i<array.length;i++) {
        for(var j=i+1;j<array.length;j++) {
          //注意 ===
          if(isObjectValueEqual(array[i],array[j])) {
            array.splice(j,1);
            j--;
          }
        }
      }
      return array;
    }
    function isObjectValueEqual(a, b) {//判断两个对象的值是否相等
      var aProps = Object.getOwnPropertyNames(a);
      var bProps = Object.getOwnPropertyNames(b);
      if (aProps.length != bProps.length) {
        return false;
      }
      for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i];
        if (a[propName] !== b[propName]) {
          return false;
        }
      }
      return true;
    }

  }

  /* *************************** 页面功能 **************************** */
  $(function () {
    pageInit();
  });


</script>
