(function(){
    X.pageLogic['routeanalysis'] = {
        init : function(){
            
            var data = {
                "eventView":{
                    "cksql":'trace',
                    "col_limit":10,
                    "startTime":"",
                    "session_interval":30,
                    "session_type":"minute",
                    "endTime":"",
                    "e_days":0,
                    "s_days":7,
                },
                "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":[],
                }
            }


            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){
            //      
            //     })
            // })

            // 日期渲染
            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;
                var sameday = Date.parse(new Date()) / 1000; //当天时间戳
                
                var enddate = new Date(end.format('YYYY-MM-DD'));
                var endmonth = Date.parse(enddate)/1000;

                var startdate = new Date(start.format('YYYY-MM-DD'));
                var startmonth = Date.parse(startdate)/1000;
                data['eventView']['e_days'] = parseInt((sameday - endmonth)/86400);
                data['eventView']['s_days'] = parseInt((sameday - startmonth)/86400);
                // calculationdata();
            })

            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";

            var filter_map;
            var eventdata = {};
            var filtsftvdata =[];
            var groupitemeventsdata = [];
            var routeevent = [];
            X.api("data_auth/my_event","get",{},function(d){
                eventdata['list'] = d;
                X.api("data_auth/load_filter_props","post",{event_name:d[0]['category'][0]['event_name']},function(val){
                    groupitemeventsdata= val;
                })
            });
            X.api("data_auth/filter_map","get",{},function(d){
                filter_map = d;
            });

            //从数据看板点击进来触发事件
            if(X.DATA.traceid && X.DATA.traceid != ''){
                var report_idarr = [];
                report_idarr.push(X.DATA.traceid);
                if(X.DATA.authority != 'rw'){
                    $('.analysis-savereport').hide();
                }else {
                    $('.analysis-saveas').show();
                }
                X.api('report/read_report','post',{project_id:X.DATA.projectid,report_id:report_idarr},function(d){
                    backfilldata(d[0].query);
                    // console.log(d);
                })
            }

            if(X.DATA['trace_query_cond'] && X.DATA['trace_query_cond'] != ''){
                // data = X.DATA['trace_query_cond'];
                backfilldata(X.DATA['trace_query_cond']);
            }


            function backfilldata(d){
                if(d){
                    data = d;
                    $('.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("小时");
                    }
                    routeevent = data.cachedata.event_names;
                    // $('.participate-num').html(data.cachedata.event_names.length);
    
                    X.template("route","event-roue-event",data['events']['source_event']);
                    $('.participate-num').html(data.events.event_names.length);
                    eventdata['select'] = data.events.event_names;
                    X.template("globalfilter","xinwei-whole",data['events']['user_filter']['filts'],function(){
                        renderdate()
                    });
                    X.laytpldata("#eventsplit-box-dot",data['events']['by_fields'],".eventsplit-box");
                    // X.template("userpar","userpar-event",data['events']);
          
                    calculationdata();
                }
            }

            $(document).off('click','.eventsplit').on('click','.eventsplit',function(){
                
                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");
                }
            });

            $(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){
                    console.log(val);
                    var selectdata = []; //选中事件的id数组
                    for(let i in val){
                        selectdata.push(val[i]['event_name']);
                    }
                    eventdata['select'] = selectdata;
                    data['events']['event_names'] = selectdata;
                    data['events']['event_namesdes'] = val;
                    $('.participate-num').html(val.length);
                    routeevent = [];
                    for(let i in val){
                        var arr = {
                            title: val[i]['event_desc']
                            ,id: val[i]['event_name']
                        }
                        routeevent.push(arr);
                    }
                    data['events']['source_event']['eventName'] = routeevent[0]['id'];
                    data['events']['source_event']['eventDesc'] = routeevent[0]['title'];
                    X.template("route","event-roue-event",data['events']['source_event']);

                })
            });

            $(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(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;
                  
                })
            });

            $(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(groupitemeventsdata,'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);
                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'],function(){
                    renderdate()
                });
            });

           $(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)
            });

           // 添加筛选项
           function addscreen(index){

                var arr = {
                    "columnDesc":groupitemeventsdata[0]['category'][0]['title'],//事件中文显示
                    "columnName":groupitemeventsdata[0]['category'][0]['id'],//事件id
                    "comparator_name": filter_map[groupitemeventsdata[0]['category'][0]['data_type']][0]['title'],//选择符号中文显示
                    "comparator":filter_map[groupitemeventsdata[0]['category'][0]['data_type']][0]['id'],//符号id
                    "data_type":groupitemeventsdata[0]['category'][0]['data_type'],
                    "ftv":[],//条件
                    "strftv":'',//字符串显示条件
                    "tableType": groupitemeventsdata[0]['id']
                } //筛选数据
                data['events']['source_event']['filts'].push(arr);
                X.template("route","event-roue-event",data['events']['source_event']);  //更新事件
            };

            $(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();
                console.log(routeevent)
                X.querycriteriapop(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;
                })
            });

            $(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(groupitemeventsdata,'category',offset.left,offset.top+obj.height(),function(val){
                    obj.html(val.title);
                    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");
                var type = data['events']['source_event']['filts'][indexs]['data_type'];
                X.querycriteriapop(filter_map[type],'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('blur','.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 = groupitemeventsdata;
                if(!screentypedata) {alert('请先选择参与分析事件'); return;}
                var drr={
                    "columnDesc":screentypedata[0]['category'][0]['title'],//事件中文显示
                    "columnName":screentypedata[0]['category'][0]['id'],//事件id
                    'data_type':screentypedata[0]['category'][0]['data_type'],//类型
                    'comparator_name':'等于',//默认等于
                    "comparator":'==',//符号id
                    "ftv":[],//条件
                    "strftv":'',//显示条件
                    "section":[-1,1],//区间
                    "table_type":screentypedata[0]['id']
                };
                data['events']['user_filter']['filts'].push(drr);
                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'],function(){
                    renderdate()
                });

            });

            $(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(groupitemeventsdata,'category',offset.left,offset.top+obj.height(),function(val){
                    obj.html(val.title);
                    data['events']['user_filter']['filts'][index]['columnDesc'] = val.title;
                    data['events']['user_filter']['filts'][index]['columnName'] = val.id;
                    data['events']['user_filter']['filts'][index]['data_type'] = val.type;
                    data['events']['user_filter']['filts'][index]['tableType'] = val.table_type;
                    X.template("globalfilter","xinwei-whole",data['events']['user_filter']['filts'],function(){
                        renderdate()
                    });
                })
            });

            $(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");
                var type = data['events']['user_filter']['filts'][index]['data_type'];
                X.querycriteriapop(filter_map[type],'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'] = 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'],function(){
                            renderdate()
                        });
                    }
                })
            });

            var render_date_index;//且用户符合时间选择框的index
            $(document).off('click','.analysis-overall-situation-date').on('click','.analysis-overall-situation-date',function(){
                var index = $(this).attr('data-index');
                render_date_index = index;
                // console.log(index);
            });

            // 渲染过滤项时间框
            function renderdate(){
                lay('.analysis-overall-situation-date').each(function(){
                    layui.laydate.render({
                      elem: this
                      ,type:"datetime"
                      ,trigger: 'click'
                      ,done: function(value, date, endDate){
                        data['events']['user_filter']['filts'][render_date_index]['strftv'] = value;
                        var datearr = [];
                        datearr.push(value)
                        data['events']['user_filter']['filts'][render_date_index]['ftv'] = datearr;
                      }
                    });
                });
            };

            $(document).off("click",".analysis-overall-situation-input").on("click",".analysis-overall-situation-input",function(event){
                var obj = $(this);
                var offset = obj.offset();
                var index = $(this).attr("data-index");
                var comparator = obj.attr("data-comparator");
                var columnName = data['events']['user_filter']['filts'][index]['columnName'];

                X.api("data_mana/select_attr","post",{attr_name:columnName},function(val){
                    if(val != "查无数据"){
                        X.parametersopen(val['map_'],'dropdownlist',[offset.top+obj.height(),offset.left],function(val){
                            
                            if(comparator == "in"){
                                if(data['events']['user_filter']['filts'][index]['strftv'] == "" ){
                                    var strftv = val.title;
                                    data['events']['user_filter']['filts'][index]['ftv'].push(val.id);
                                }else {
                                    var strftv = data['events']['user_filter']['filts'][index]['strftv'] + "," + val.title;
                                    data['events']['user_filter']['filts'][index]['ftv'].push(val.id);
                                }
                                data['events']['user_filter']['filts'][index]['strftv'] = strftv;
                            }else {
                                data['events']['user_filter']['filts'][index]['strftv'] = val.title;
                                var arr = [];
                                arr.push(val.id);
                                data['events']['user_filter']['filts'][index]['ftv'] = arr; 
                            }

                            X.template("globalfilter","xinwei-whole",data['events']['user_filter']['filts'],function(){
                                renderdate()
                            });
                            
                        })
                    }
                })
            });

            $(document).off('blur','.analysis-overall-situation-input input').on('blur','.analysis-overall-situation-input input',function(){
                var index = $(this).attr('data-index');
                var val = $(this).val();
                var valarr = val.split(",");
                data['events']['user_filter']['filts'][index]['ftv']=valarr;
                data['events']['user_filter']['filts'][index]['strftv']=val;
            });

            $(document).off('blur','.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;
                }
            });

            $(document).off('click','.analysis-zhibiao-list-del-initial-event').on('click','.analysis-zhibiao-list-del-initial-event',function(){
                var index = $(this).attr('data-twonum');
                data['events']['source_event']['filts'].splice(index,1);
                X.template("route","event-roue-event",data['events']['source_event']);
            });
            

            // 时间粒度
            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('blur','.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'];
                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;
                        $('.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'],function(){
                            renderdate()
                        });
                        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: '#3ea7fd'
                        },
                        lineStyle: {
                            color: '#eeeeee',
                            opacity: 0.9
                        }
                    };
                    levelsdata.push(arr);
                }

                myChart.setOption(option = {
                    title: {
                        text: '用户行为路径'
                    },
                    tooltip: {
                        trigger: 'item',
                        triggerOn: 'mousemove'
                    },
                    series: [
                        {
                            type: 'sankey',
                            left: '1%',
                            right: '0%',
                            data: d.nodes,
                            links: d.links,
                            nodeWidth: 100,
                            nodeGap: 10,
                            draggable:false,
                            nodeAlign: 'left',
                            label:{
                                position:'',
                                formatter: function(event){
                                    // console.log(event)
                                    
                                },
                              },
                            emphasis: {
                                focus: 'adjacency'
                            },
                            levels: levelsdata,
                            lineStyle: {
                                curveness: 0.5
                            }
                        }
                    ]
                });

                // 图表单击事件
                myChart.setOption(option);
                
                // 绑定前解绑click事件
                myChart.off("click");
                // 跳转节点详情弹窗
                myChart.on('click', function (params) {
                    var name = params.name;
                    if(name.indexOf("流失") == -1){
                        var event_next = d.event_next[name];
                  
                        var titarr = {};
                        var namearr = [];
                        var nextsum = 0;
                        for(let i in event_next){
                            var tit = event_next[i]['event_name'].split("-")[0];
                            if(namearr.indexOf(tit) < 0){
                                namearr.push(tit);
                                titarr[tit] = {};
                                titarr[tit]['data'] = [];
                                titarr[tit]['sum'] = 0;
                            }
                            var value = event_next[i].value;
                            titarr[tit]['sum'] = titarr[tit]['sum'] + value;
                            titarr[tit]['data'].push(event_next[i]);
                            if(tit != "流失"){
                                nextsum += event_next[i].value;
                            }
                        }

                        var echartsdata = {
                            name: name,
                            sumnum: d.event_num[name],
                            nextsum: nextsum,
                            titarr: titarr,
                            namearr:namearr,
                            data:data,
                            event_next: event_next
                        }
                    
                        X.open({
                            type: 1,
                            title: false,
                            closeBtn: 0,
                            shadeClose: true,
                            skin: 'yourclass',
                            url: 'nodedetails',
                            extData: echartsdata
                        })
                    }

                    

                });

            };

            // 返回
            $(document).off('click','.analysis-fanhui').on('click','.analysis-fanhui',function(){
                X.gourl("dashboard");
                // return;
            });

        }
    };
})();