<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="utf-8"%>
<%@include file="/WEB-INF/ehr/commons/jsp/commonInclude.jsp" %>
<script src="${contextRoot}/develop/lib/plugin/validate/jValidate.js"></script>

<script>

    /* ************************** 全局变量定义 **************************** */

    var Util = $.Util;
    var schemeVersionList = [];
    var validAdd = null;

    /* *************************** 自定义模块 ***************************** */
    var jobLayout = {
        dialog:null,
        grid:null,
        cacheDatasetIdList:[],
        cacheDatasetCodeList:[],
        cacheMappingInitData:[],
        cacheMappingData:[],
        init:function(){
            var me = this;
            $('.m-retrieve-area').show();

            $.ajax({
                url: '${contextRoot}/crawler/getSchemeList',
                dataType: "json",
                success: function (data) {
                    if(data.successFlg){
                        schemeVersionList = data.detailModelList || [];
                        me.loadGrid();
                    }else{
                        $.ligerDialog.error(data.message);
                    }

                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $.ligerDialog.error("获取适配方案版本列表失败！")
                }
            });




            me.bindEvents();
        },
        loadGrid:function(){
            var me= this;
            this.grid = $("#div_job_grid").ligerGrid({
                url: '${contextRoot}/crawler/list',
                method: 'post',
                selectRowButtonOnly: true,
                allowHideColumn:false,
                validate : true,
                unSetValidateAttr:false,
                columns: [
                    { display: 'status', name: 'status', hide:true },
                    { display: 'scheme_id', name: 'scheme_id', hide:true },
                    { display: 'datasetId', name: 'datasetId', hide:true },
                    {display:'适配方案',name:'', width: '20%',render: function (row, rowindex, value, column) {
                        var select= '<select class="sel-scheme-name form-control required"  id="schemeNm'+rowindex+'" style="margin-top:3px;font-size:12px;">';
                        for(var i=0;i<schemeVersionList.length;i++){
                            select+='<option value="'+schemeVersionList[i].schemeId+'">'+schemeVersionList[i].name+'</option>';
                        }
                        select = $(select+"</select>");
                        $('option[value="'+row.scheme_id+'"]',select).attr('selected',true);

                        return  select.prop("outerHTML");
                    }},
                    {display:'版本',name:'',width: '20%',render: function (row, rowindex, value, column) {
                        var select= '<select class="sel-version-name form-control required"  data-rowindex="'+rowindex+'" id="versionNm'+rowindex+'" style="margin-top:3px;font-size:12px;">';
                        var versionList = [];
                        for(var i=0;i<schemeVersionList.length;i++){
                            if(schemeVersionList[i].schemeId == row.scheme_id){
                                versionList = schemeVersionList[i].versionList;
                                for(var j=0;j<versionList.length;j++){
                                    select+='<option value="'+versionList[j].id+'">'+versionList[j].name+'</option>';
                                }
                            }
                        }
                        select = $(select+"</select>");
                        $('option[value="'+row.scheme_version_id+'"]',select).attr('selected',true);

                        return  select.prop("outerHTML");
                    }},
                    {display:'数据集名称',name:'datasetName', width: '40%',render: function (row, rowindex, value, column) {
                        var dataSets = value;
                        if(value==undefined){
                            dataSets="";
                        }else if(value.toString().substring(value.length-1,value.length)==","){
                            dataSets=value.toString().substring(0,value.length-1);
                        }
                        var html = '<input style="margin-top:3px;font-size:12px;" data-rowindex="'+rowindex+'" id="dataSets'+rowindex+'" class="required sel-dataset-name form-control" value="'+(dataSets || "")+'" >' ;
                        return html;
                    }},
                    {display:'操作', name: 'operator', width: '20%', render: function (row, rowindex, value, column) {
                        var html = '<div class="m-inline-buttons" style="width:120px;">';
                        html += '<a href="javascript:void(0)" style="width: 80px;" class="mapping"  data-rowindex="'+rowindex+'" onclick="javascript:jobLayout.mapping(\''+rowindex+'\')">数据映射</a>';
                        html += '<a class="m-btn-delete" onclick="javascript:jobLayout.delete(\''+rowindex+'\')"></a>';

                        return html;
                    }}
                ],
                onSuccess:function(data, grid){//成功获取服务器数据的事件
                    //缓存初始化勾选的数据集id
                    var detailModelList = data.detailModelList;
                    for(var i=0;i<detailModelList.length;i++){
                        me.cacheDatasetIdList[i] = detailModelList[i].datasetId;
                        me.cacheDatasetCodeList[i]="";
                        me.cacheMappingInitData[i]="";
                        me.cacheMappingData[i]="";
                    }
                },
                onAfterShowData: function (gridData) {//显示完数据事件
                    validAdd = new jQuery.jValidation.Validation($("#div_job_grid"),{immediate:true,onSubmit:false});

                    //【适配方案】change事件
                    $(".sel-scheme-name").on("change", function() {
                        var rowIndex = $(this).attr("id").replace("schemeNm","");
                        var option = "";
                        var versionList = [];
                        for(var i=0;i<schemeVersionList.length;i++){
                            if(schemeVersionList[i].schemeId == $(this).val()){
                                versionList = schemeVersionList[i].versionList;
                                for(var j=0;j<versionList.length;j++){
                                    option+='<option value="'+versionList[j].id+'">'+versionList[j].name+'</option>';
                                }
                            }
                        }
                        $("#versionNm"+rowIndex).html("");
                        $("#versionNm"+rowIndex).append(option);
                        //清空值
                        me.cacheDatasetIdList[rowIndex]="";
                        me.cacheDatasetCodeList[rowIndex]="";
                        me.cacheMappingInitData[rowIndex]="";
                        me.cacheMappingData[rowIndex]="";
                        $("#dataSets"+rowIndex).val("");

                    });

                    //【版本】change事件
                    $(".sel-version-name").on("change", function() {
                        var rowIndex = $(this).data("rowindex");
                        //清空值
                        me.cacheDatasetIdList[rowIndex]="";
                        me.cacheDatasetCodeList[rowIndex]="";
                        me.cacheMappingInitData[rowIndex]="";
                        me.cacheMappingData[rowIndex]="";
                        $("#dataSets"+rowIndex).val("");
                    });

                    //【数据集名称】focus事件
                    $(".sel-dataset-name").on("focus", function() {
                        
                        var rowindex = $(this).attr("data-rowindex");
                        jobLayout.grid.select(rowindex);//选中行
                        var selectedVersionId = $("#versionNm"+rowindex).val();
                        if(selectedVersionId==null){
                            $.ligerDialog.error("当前版本为空，不能选择数据集！");
                            return false;
                        }

                        /* 判断适配方案与版本是否重复*/
                        var resultArr =  me.getGridData();
                        var uniqueArr = me.uniqueArray(resultArr);
                        if(resultArr.length!==uniqueArr.length){
                            $.ligerDialog.error("相同适配方案下，不能有相同的版本!");
                            return false;
                        }

                        var row = jobLayout.grid.getSelectedRow();
                        var cacheDatasetId =JSON.stringify(me.cacheDatasetIdList[rowindex]);//获取缓存勾选的数据集
                        var  params = {
                            schemeId:$("#schemeNm"+rowindex).val(),
                            versionId: $("#versionNm"+rowindex).val(),
                            schemeNm:$("#schemeNm"+rowindex).find("option:selected").text(),
                            cacheDatasetId:cacheDatasetId};
                        me.dialog = $.ligerDialog.open({
                            height: 600,
                            width: 600,
                            title: "数据集选择器",
                            url: '${contextRoot}/crawler/datasetDetail',
                            //load: true,
                            urlParms: params
                        });
                    });


                }
            });
        },
        //绑定按钮事件
        bindEvents: function () {
            var me = this;
            $('#btnAdd').click(function () {
                var dataRow = {
                    status:'',
                    scheme_id:'',
                    scheme_version_id:'',
                    datasetName:'',
                    datasetId:''
                };
                var rowData = me.grid.getData();
                for (var i = 0; i < rowData.length; i++) {
                    me.grid.rows[i].scheme_id = $("#schemeNm"+i).val();
                    me.grid.rows[i].scheme_version_id= $("#versionNm"+i).val();
                    me.grid.rows[i].datasetName= $("#dataSets"+i).val();
                }
                //将新添加的行插入到最后一列
                me.grid.addRow(dataRow);
                $(".sel-scheme-name#schemeNm"+rowData.length).trigger("change");
                me.cacheDatasetIdList.push("");
                me.cacheDatasetCodeList.push("");
                me.gridScrollTop();//1、将滚动条滚动到底部
            });
            $('#btnSave').click(function(){
                
                if(!validAdd.validate()){
                    return false;
                }
                var resultArr =  me.getGridData();//获取表格数据
                var option = me.grid.options;

                $.ajax({
                    url: "${contextRoot}/crawler/saveDateSet",
                    type: "post",
                    dataType: "json",
                    data:{job: JSON.stringify(resultArr),rows:option.pageSize,page:option.page},
                    success: function (data) {
                        
                        if(data.successFlg){
                            $.ligerDialog.success(data.message);
                            jobLayout.grid.loadData(true);
                        }else{
                            $.ligerDialog.error(data.message);
                        }

                    },error:function(){

                    }
                });

            });
        },
        getGridData:function(){
            
            var me = this;
            var rowData = this.grid.getData();
            var resultArr = [];
            for (var i = 0; i < rowData.length; i++) {
                var row = {
                    schemeId:$("#schemeNm"+i).val(),
                    versionId: $("#versionNm"+i).val(),
                    dataSets:me.cacheDatasetIdList[i],
                    relation:me.cacheMappingData[i]}
                resultArr.push(row);
            }
            return resultArr;
        },
        contains:function(a, e){
            for(j=0;j<a.length;j++)if(a[j]==e)return true;
            return false;
        },
        uniqueArray:function(a){ /* 判断适配方案与版本是否重复*/
            var temp = new Array();
            for(var i = 0; i < a.length; i ++){
                if(!this.contains(temp, a[i].schemeId + a[i].versionId)){
                    temp.length+=1;
                    temp[temp.length-1] = a[i].schemeId + a[i].versionId;
                }
            }
            return temp;
        },
        gridScrollTop:function(){
            var div = $('#div_job_grid .l-grid-body2')[0],
                    scrollHeight = div.scrollHeight;
    
            if( div.scrollTop + div.clientHeight >= div.scrollHeight ){//滚动条已滑动到底部
                return false;
            }
            var scrollTop = div.scrollTop;
            var timer= setInterval(function () {
                scrollTop += 150;
                div.scrollTop = scrollTop;
                if (scrollTop >= scrollHeight) clearInterval(timer);}, 100);//滚动到底部，释放计时器
        },
        //数据映射
        mapping:function(rowindex){
            
            var versionId = $("#versionNm"+rowindex).val();
            var datasetIdStr =  this.cacheDatasetIdList[rowindex]==undefined?"":this.cacheDatasetIdList[rowindex];
            if(versionId==null){
                $.ligerDialog.error("当前版本为空，不能进行数据映射！");
                return false;
            }
            if( $("#dataSets"+rowindex).val()==""){
                $.ligerDialog.error("当前勾选的数据集数据为空，不能进行数据映射！");
                return false;
            }
            var me = this;
            var  params = {versionId:versionId,datasetIdStr:datasetIdStr};
            me.dialog = $.ligerDialog.open({
                height: 800,
                width: 1200,
                title: "数据映射",
                url: '${contextRoot}/crawler/jobDataMapping',
                //load: true,
                urlParms: params
            });
        },
        //删除数据映射
        delete:function(rowindex) {
            this.grid.select(rowindex);//选中行
            var me = this;
            var row = me.grid.getSelectedRow();
            var rowData = me.grid.getData();
            //判断是否是新增的数据。若是新增的数据，则直接删除数据，不发送后台请求
            if(row.__status=="add"){
                $.ligerDialog.confirm("确定要删除该适配方案数据映射吗？", function (confirm) {
                    if (confirm)
                    {
                        
                        //保存当前编辑的数据
                        for (var i = 0; i < rowData.length; i++) {
                            me.grid.rows[i].scheme_id = $("#schemeNm"+i).val();
                            me.grid.rows[i].scheme_version_id= $("#versionNm"+i).val();
                            me.grid.rows[i].datasetName= $("#dataSets"+i).val();
                        }
                        //删除行缓存的数据
                        var cacheDatasetIdList = me.cacheDatasetIdList;
                        var cacheDatasetCodeList = me.cacheDatasetCodeList;
                        var cacheMappingInitData = me.cacheMappingInitData;
                        var cacheMappingData = me.cacheMappingData;
                        cacheDatasetIdList.splice(rowindex,1);
                        cacheDatasetCodeList.splice(rowindex,1);
                        cacheMappingInitData.splice(rowindex,1);
                        cacheMappingData.splice(rowindex,1);
                        //删除行
                        me.grid.deleteRow(rowindex);
                    }
                });
            }else{
                var delVersionId = $("#versionNm"+rowindex).val();
                if(delVersionId==null){
                    $.ligerDialog.error("当前没有选择适配版本，不能删除！");
                    return false;
                }
                var addFlag = false;
                for (var i = 0; i < rowData.length; i++) {
                    if(rowData[i].status==""){//新增
                        addFlag = true;
                        break;
                    }
                }
                if(addFlag){//有新增数据并且未保存
                    $.ligerDialog.error("当前有未保存的数据，请先保存，再删除");
                    return false;
                }
                $.ligerDialog.confirm("确定要删除该适配方案数据映射吗？", function (confirm) {
                    if (confirm)
                    {
                        $.ajax({ //ajax处理
                            type: "POST",
                            url : "${contextRoot}/crawler/deleteDateSet",
                            dataType : "json",
                            data:{version:delVersionId},
                            cache:false,
                            success :function(data){
                                if(data.successFlg) {
                                    $.ligerDialog.success(data.message);
                                    jobLayout.grid.loadData(true);//重新加载表格数据
                                }
                                else{
                                    $.ligerDialog.error(data.message);
                                }
                            },
                            error :function(data){
                                $.ligerDialog.error("删除失败！");
                            }
                        });
                    }
                });
            }

        },
        //弹窗返回消息
        callbackDialog:function(message){
            $.ligerDialog.success(message);
            this.grid.reload();
            this.dialog.close();
        }
    }

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


