(function(){
    X.pageLogic['routeanalysis'] = {
        init : function(){
            var eventdata = {};
            var filtsftvdata =[];
            X.api("data_auth/my_event","get",{},function(d){
                eventdata['list'] = d;
            })

            var data = {
                "eventView":{
                    "cksql":'trace',
                    "col_limit":10,
                    "startTime":"",
                    "session_interval":30,
                    "session_type":"minute",
                    "endTime":""
                },
                "events":{
                    "by_fields":[
                        
                    ],
                    "event_names":[],
                    "source_event":{
                        "eventName":"",
                        "eventDesc":"",
                        "source_type":"initial_event",
                        "source_type_name":"初始事件",
                        "filts": [],
                        "relation":'and'
                    },
                    "user_filter":{
                        "filterType":"COMPOUND",
                        "filts":[]
                    }
                },
                "cachedata":{
                    "event_names":[],
                    "groupitemeventsdata":[],
                    "filtsftvdata":[]
                }
            }


            X.template("route","event-roue-event",data['events']['source_event']);

            // 日期渲染
            X.daterender("#route-condition-date",function(start, end, label){
                var startTime = start.format('YYYY-MM-DD')+ " "+ "00:00:00";
                var endTime = end.format('YYYY-MM-DD')+ " "+ "23:59:59";
                data['eventView']['startTime'] = startTime;
                data['eventView']['endTime'] = endTime;
                X.api("ck/trace_model","post",data,function(d){
                    routeanalysisdata(d);
                })
            })

            var time = $("#route-condition-date").val();
            var timearr = time.split(" ");
            data['eventView']['startTime'] = timearr[0] + " "+"00:00:00";
            data['eventView']['endTime'] = timearr[2]+" "+"23:59:59";

            $(document).off('click','.eventsplit').on('click','.eventsplit',function(){
                var routeevent = X['DATA']['routeevent'];
                console.log(routeevent);
                if( routeevent && routeevent.length > data['events']['by_fields'].length){
                    var arr = {
                        "eventName": routeevent[data['events']['by_fields'].length]['id'],
                        "eventDesc": routeevent[data['events']['by_fields'].length]['title'],
                        "field":"rmbmoney",
                        "fieDesc":"rmbmoney",
                        "range":"",
                        "range_type":"def",
                        "tableType":"event",
                        "intervalType":"",
                        "quotaIntervalArr":""
                    };
                    data['events']['by_fields'].push(arr);
                    X.laytpldata("#eventsplit-box-dot",data['events']['by_fields'],".eventsplit-box");

                    X.api("data_auth/load_filter_props","post",{event_name:routeevent[data['events']['by_fields'].length]['id']},function(val){
                        console.log(val);
                        // defaultgroupdata = val;
                        groupitemeventsdata.push(val);
                    })
                
                }
            })

            $(document).off('click','.route-action-right').on('click','.route-action-right',function(){
                var index = $(this).attr('data-index');
                data['events']['by_fields'].splice(index,1);
                X.laytpldata("#eventsplit-box-dot",data['events']['by_fields'],".eventsplit-box");
            })
            
            $(document).off('click','.participate-box').on('click','.participate-box',function(){
                var obj = $(this);
                var offset = obj.offset();
                X.querycriteriapop(eventdata,'participate',offset.left,offset.top+obj.height(),function(val){
                    var selectdata = []; //选中事件的id数组
                    X.DATA['routeevent'] = [];
                    // var selectdescdata = []; //选中事件的别名数组
                    for(let i in val){
                        selectdata.push(val[i]['event_name']);
                        // selectdescdata.push(val[i]['event_desc']);
                    }
                    eventdata['select'] = selectdata;
                    data['events']['event_names'] = selectdata;
                    $('.participate-num').html(selectdata.length);
                    
                    for(let i in val){
                        var arr = {
                            title: val[i]['event_desc']
                            ,id: val[i]['event_name']
                        }
                        if(X.DATA['routeevent']){
                            X.DATA['routeevent'].push(arr);
                        }else {
                            X.DATA['routeevent'] = [];
                            X.DATA['routeevent'].push(arr);
                        }
                    }
                    data['events']['source_event']['eventName'] = X.DATA['routeevent'][0]['id'];
                    data['events']['source_event']['eventDesc'] = X.DATA['routeevent'][0]['title'];
                    X.template("route","event-roue-event",data['events']['source_event']);

                    X.api("data_auth/load_filter_props","post",{event_name:val[0]['event_name']},function(val){
                        // defaultgroupdata = val;
                        groupitemeventsdata.push(val);
                    })
                })
            })

            var groupitemeventsdata = [];
            $(document).off('click','.route-ant-select-selector1').on('click','.route-ant-select-selector1',function(){
                var obj = $(this);
                var offset = obj.offset();
                var index = obj.attr('data-index');
                X.querycriteriapop(X.DATA['routeevent'],'dropdownlist',offset.left,offset.top+obj.height(),function(val){
                    obj.html(val.title);
                    data['events']['by_fields'][index]['eventDesc'] = val.title;
                    data['events']['by_fields'][index]['eventName'] = val.id;
                    X.api("data_auth/load_filter_props","post",{event_name:val.id},function(val){
                        console.log(val);
                        // defaultgroupdata = val;
                        groupitemeventsdata.push(val);
                    })
                })
            })

            // 过滤数据
            function filteringdata(){
                var screentypedata;
                if(groupitemeventsdata.length>1){
                    for(var i =0; i < groupitemeventsdata.length - 1; i++){
                        if(i == 0){
                            X.groupintersection(groupitemeventsdata[i] , groupitemeventsdata[Number(i) + Number(1)],function(d){
                                screentypedata = d;
                            });
                        }else {
                            X.groupintersection(screentypedata , groupitemeventsdata[Number(i) + Number(1)],function(d){
                                screentypedata = d;
                            })
                        }
                    }
                }else { 
                    screentypedata = groupitemeventsdata[0];
                }
                return screentypedata;
            }

            $(document).off('click','.route-ant-select-selector2').on('click','.route-ant-select-selector2',function(){
                var obj = $(this);
                var offset = obj.offset();
                var index = obj.attr('data-index');
                X.querycriteriapop(filteringdata(),'category',offset.left,offset.top+obj.height(),function(val){
                    console.log(val);
                    obj.html(val.title);
                    data['events']['by_fields'][index]['eventDesc'] = val.title;
                    data['events']['by_fields'][index]['eventName'] = val.id;
                })
            })

            $(document).off('click','.userevent-granularity').on('click','.userevent-granularity',function(){
                var index = $(this).attr('data-index');
                var sectionid = data['events']['by_fields'][index];
                console.log(sectionid);
                X.parametersopen(sectionid,'groupeditemspop',"auto",function(val){
                    data['events']['by_fields'][index]['intervalType'] = val.type;
                    if(val.type == "user_defined"){
                        data['events']['by_fields'][index]['quotaIntervalArr'] = val.quotaIntervalArr;
                    }
                })
            })

            $(document).off('click','.analysis-overall-situation-del').on('click','.analysis-overall-situation-del',function(){
                var index = $(this).attr('data-index');
                data['events']['user_filter']['filts'].splice(index,1);
                filtsftvdata.splice(index,1);
                if(data['events']['user_filter']['filts'].length > 1){
                    $(".analysis-overall-situation-left-guanxi").show();
                }else{
                    $(".analysis-overall-situation-left-guanxi").hide();
                }
            })

           $(document).off('click','.analysis-shaix-initial-event').on('click','.analysis-shaix-initial-event',function(){
                addscreen(0)
           })

           $(document).off('click','.analysis-zhibiao-updata-initial-event').on('click','.analysis-zhibiao-updata-initial-event',function(){
                addscreen(0)
            })

           // 添加筛选项
           var filtersymbols = [];
           function addscreen(index){
                X.api('data_auth/load_filter_props',"post",{event_name:data['events']['source_event']["eventName"]},function(d){
                    var arr = {
                        "columnDesc":d[0]['category'][0]['title'],//事件中文显示
                        "columnName":d[0]['category'][0]['id'],//事件id
                        "comparator_name":d[0]['category'][0]['category'][0]['title'],//选择符号中文显示
                        "comparator":d[0]['category'][0]['category'][0]['id'],//符号id
                        "data_type":d[0]['category'][0]['data_type'],
                        "ftv":'',//条件
                        "strftv":'',//字符串显示条件
                        "tableType": d[0]['id']
                    } //筛选数据
                    data['events']['source_event']['filts'].push(arr);
                    X.template("route","event-roue-event",data['events']['source_event']);  //更新事件
                    // screentypearr[index] = d;
                    filtersymbols.push(d[0]['category'][0]["category"]);
                })
            }

            $(document).off('click','.analysis-con-left-screen-list-right-screen-qh-tit').on('click','.analysis-con-left-screen-list-right-screen-qh-tit',function(){
                if($(this).html() == '或'){
                    $(this).html('且');
                    data['events']["source_event"]['relation'] = 'or';
                }else{
                    $(this).html('或');
                    data['events']["source_event"]['relation'] = 'and';
                }
            })

            $(document).off('click','.ant-dropdown-trigger').on('click','.ant-dropdown-trigger',function(){
                var obj = $(this);
                var offset = obj.offset();
                X.querycriteriapop(X.DATA['routeevent'],'dropdownlist',offset.left,offset.top+obj.height(),function(val){
                    obj.html(val.title);
                    data['events']['source_event']['eventDesc']= val.title;
                    data['events']['source_event']['eventName'] = val.id;
                    X.api("data_auth/load_filter_props","post",{event_name:val.id},function(val){
                        console.log(val);
                        // defaultgroupdata = val;
                        groupitemeventsdata.push(val);
                    })
                })
            })

            $(document).off('click','.analysis-zhibiao-list-type2').on('click','.analysis-zhibiao-list-type2',function(){
                var eventdata = [
                    {'title':'初始事件','id':'initial_event'},
                    {'title':'结束事件','id':'termination_event'}
                ]
                var obj = $(this);
                var offset = obj.offset();
                X.querycriteriapop(eventdata,'dropdownlist',offset.left,offset.top+obj.height(),function(val){
                    obj.html(val.title);
                    // data['events']['source_event']['source_type_name']= val.title;
                    data['events']['source_event']['source_type'] = val.id;
                    
                })
            })

            $(document).off("click",".ta-property-select").on('click','.ta-property-select',function(){
                var obj = $(this);
                var offset = obj.offset();
                var indexs = obj.attr("data-indexs");
                X.querycriteriapop(filteringdata(),'category',offset.left,offset.top+obj.height(),function(val){
                    obj.html(val.title);
                    filtersymbols[indexs] = val.category;
                    data['events']['source_event']['filts'][indexs]['columnDesc'] = val.title;
                    data['events']['source_event']['filts'][indexs]['columnName'] = val.id;
                    data['events']['source_event']['filts'][indexs]['data_type'] = val.type;
                    data['events']['source_event']['filts'][indexs]['tableType'] = val.table_type;
                })
            })

            $(document).off('click','.analysis-choicetypename').on('click','.analysis-choicetypename',function(){
                var obj = $(this);
                var offset = obj.offset();
                var indexs = $(this).attr("data-indexs");
                X.querycriteriapop(filtersymbols[indexs],'dropdownlist',offset.left,offset.top+obj.height(),function(val){
                    if(val != undefined){
                        obj.html(val.title);
                        data['events']['source_event']['filts'][indexs]['comparator_name'] = val.title;
                        data['events']['source_event']['filts'][indexs]['comparator'] = val.id;
                        X.template("userpar","userpar-event",data['events']); 
                    }
                })
            })

            $(document).off('click','.analysis-zhibiao-list-type4 input').on('blur','.analysis-zhibiao-list-type4 input',function(){
                var indexs = $(this).attr("data-indexs");
                var val = $(this).val();
                var valarr = val.split(",");
                data['events']['source_event']['filts'][indexs]['ftv']=valarr;
                data['events']['source_event']['filts'][indexs]['strftv']=val;
            })

            $(document).off('click','.analysis-overall-situation-add').on('click','.analysis-overall-situation-add',function(){
                var screentypedata = filteringdata();
                if(!screentypedata) {alert('请先选择参与分析事件'); return;}
                var drr={
                    "columnName":screentypedata[0]['category'][0]['title'],//事件中文显示
                    "column_id":screentypedata[0]['category'][0]['id'],//事件id
                    'data_type':screentypedata[0]['category'][0]['data_type'],//类型
                    'comparator_name':'等于',//默认等于
                    "comparator_id":'==',//符号id
                    "ftv":[],//条件
                    "strftv":'',//显示条件
                    "section":[-1,1],//区间
                    "table_type":screentypedata[0]['id']
                };
                data['events']['user_filter']['filts'].push(drr);
                filtsftvdata.push(screentypedata[0]['category'][0]['category']);
                if(data['events']['user_filter']['filts'].length > 1){
                    $(".analysis-overall-situation-left-guanxi").show();
                }else{
                    $(".analysis-overall-situation-left-guanxi").hide();
                }
                X.template("globalfilter","xinwei-whole",data['events']['user_filter']['filts']);

            })

            $(document).off('click','.analysis-overall-situation-attr').on('click','.analysis-overall-situation-attr',function(){
                var obj = $(this);
                var offset = obj.offset();
                var index = $(this).attr("data-index");
                X.querycriteriapop(filteringdata(),'category',offset.left,offset.top+obj.height(),function(val){
                    obj.html(val.title);
                    data['events']['user_filter']['filts'][index]['columnName'] = val.title;
                    data['events']['user_filter']['filts'][index]['column_id'] = val.id;
                    data['events']['user_filter']['filts'][index]['data_type'] = val.type;
                    data['events']['user_filter']['filts'][index]['tableType'] = val.table_type;
                    filtsftvdata[index] = val.category;
                })
            })

            $(document).off('click','.analysis-overall-situation-fuhao').on('click','.analysis-overall-situation-fuhao',function(){
                var obj = $(this);
                var offset = obj.offset();
                var index = $(this).attr("data-index");
                X.querycriteriapop(filtsftvdata[index],'dropdownlist',offset.left,offset.top+obj.height(),function(val){
                    if(val != undefined){
                        obj.html(val.title);
                        data['events']['user_filter']['filts'][index]['comparator_name'] = val.title;
                        data['events']['user_filter']['filts'][index]['comparator_id'] = val.id;
                        if(val.id == "range"){
                            data['events']['user_filter']['filts'][index]['ftv'] = [-1,1];
                        }
                        X.template("globalfilter","xinwei-whole",data['events']['user_filter']['filts']);
                    }
                })
            })
            $(document).off('click','.analysis-overall-situation-input input').on('blur','.analysis-overall-situation-input input',function(){
                var val = $(this).val();
                var index = $(this).attr("data-index");
                data['events']['user_filter']['filts'][index]['strftv'] = val;
            })

            $(document).off('click','.analysis-overall-situation-input2 input').on('blur','.analysis-overall-situation-input2 input',function(){
                var name = $(this).attr('name');
                var val = $(this).val();
                var index = $(this).attr("data-index");
                
                if(name == 'start'){
                    data['events']['user_filter']['filts'][index]['ftv'][0] = val;
                    data['events']['user_filter']['filts'][index]['section'][0] = val;
                }else {
                    data['events']['user_filter']['filts'][index]['ftv'][1] = val;
                    data['events']['user_filter']['filts'][index]['section'][1] = val;
                }
            })

            // 时间粒度
            var timeParticleSizearr = [
                {'title':'秒','id':'second'},
                {'title':'分钟','id':'minute'},
                {'title':'小时','id':'hour'},
            ]
            X.laydropdown('.route-condition',timeParticleSizearr,function(d){
                console.log(d);
                $(".route-condition").html(d.title);
                data['eventView']['session_type'] = parseInt(d.id);
            })

            $(document).off('click','.analysis-con-left-screen-box2 input').on('blur','.analysis-con-left-screen-box2',function(){
                data['eventView']['session_interval'] =parseInt($('.analysis-con-left-screen-box2 input').val());
            })

            //计算按钮
            $(document).off('click','.analysis-calculation').on('click','.analysis-calculation',function(){
                calculationdata();
            });


            function calculationdata(){
                data['cachedata']['event_names'] = X['DATA']['routeevent'];
                data['cachedata']['groupitemeventsdata'] = groupitemeventsdata;
                data['cachedata']['filtsftvdata'] = filtsftvdata;
                var dataArr = {
                    eventView: data.eventView,
                    events: data.events
                }
                X.api("ck/trace_model","post",dataArr,function(d){
                    routeanalysisdata(d);
                })
            }

            // sql语句显示
            $(document).off('click','.sqlquery').on('click','.sqlquery',function(){
                var obj = $(this);
                var offset = obj.offset();
                X.querycriteriapop(data,'conditionquery',offset.left - 410,offset.top+obj.height(),function(){
                    
                })
            })

            $(document).off('click','.analysis-savereport').on('click','.analysis-savereport',function(){
                X.parametersopen(data,'savereport','auto')  
            })

            $(document).off('click','.analysis-navigation-bar-right-img-baobiao').on('click','.analysis-navigation-bar-right-img-baobiao',function(){
                X.parametersopen(data['eventView']['cksql'],'savedbaobiao','rt',function(d){
                    console.log(d);
                    if(d){
                        data = d.query;
                        filtsftvdata = data.cachedata.filtsftvdata;
                        groupitemeventsdata = data.cachedata.groupitemeventsdata;
                        $('.route-time-input').val(data['eventView']['session_interval']);
                        if(data['eventView']['session_type'] == "second"){
                            $(".route-condition").html("秒");
                        }else if(data['eventView']['session_type']  == "minute"){
                            $(".route-condition").html("分钟");
                        }else {
                            $(".route-condition").html("小时");
                        }
                        X.DATA['routeevent'] = data.cachedata.event_names;
                        $('.participate-num').html(data.cachedata.event_names.length);
    
                        X.template("route","event-roue-event",data['events']['source_event']);
                        X.template("globalfilter","xinwei-whole",data['events']['user_filter']['filts']);
                        X.laytpldata("#eventsplit-box-dot",data['events']['by_fields'],".eventsplit-box");
                        // X.template("userpar","userpar-event",data['events']);
              
                        calculationdata();
                    }

                })
            })

            function routeanalysisdata(d){
                var myChart = echarts.init(document.getElementById('routeanalysis-echarts'));

                var colordata = X.DATA['echartscolor'];
                var levelsdata = [];
                for(let i in colordata){
                    var arr = {
                        depth: i,
                        itemStyle: {
                            color: colordata[i]
                        },
                        label: {
                            show:true,
                            position: 'center'
                        },
                        lineStyle: {
                            color: 'source',
                            opacity: 0.6
                        }
                    };
                    levelsdata.push(arr);
                }

                myChart.setOption(option = {
                    title: {
                        text: '用户行为路径'
                    },
                    grid: {
                        left: '2%',
                        right: '2%',
                        bottom: '2%',
                        top: '10%',
                        containLabel: true
                    },
                    tooltip: {
                        trigger: 'item',
                        triggerOn: 'mousemove'
                    },
                    series: [
                        {
                            type: 'sankey',
                            data: d.nodes,
                            links: d.links,
                            emphasis: {
                                focus: 'adjacency'
                            },
                            levels: levelsdata,
                            lineStyle: {
                                curveness: 0.5
                            }
                        }
                    ]
                });
            }

        }
    };
})();