(function(){
    X.pageLogic['funnelanalysis'] = {
        init : function(parms){
            // 分组项
            X.template("grouped","shushi");

            var data ={
                        "eventView":{
                            "cksql":"funnel",
                            "endTime":"",
                            "filts":[],
                            "groupBy":[],
                            "e_days":0,
                            "s_days":7,
                            "relation":"and",
                            "startTime":"",
                            "statType":"retention",
                            "timeParticleSize":"P1D",
                            "windows_gap":7
                        },
                        "events":[
                            
                        ],
                        "cachedata":{
                            eventdata : [],
                            groupitemeventsdata: [],
                            filtsftvdata:[],
                            filtersymbols:[],//筛选符号
                        }
            };

            // 日期渲染
            X.daterender("#retained-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;
                data['eventView']['e_days'] = parseInt((sameday - endmonth)/86400);
                data['eventView']['s_days'] = parseInt((sameday - startmonth)/86400);
                retaineddata();
            })

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

            var eventdata;
            var filtersymbols = [[],[]];//默认两个事件
            var groupitemeventsdata=[[],[]]//分组项里的事件
            // var screentypearr = [];

            X.api("data_auth/my_event","get",{},function(d){
                eventdata = d;
                var arr = [{
                    "eventDesc":eventdata[0]['category'][0]['event_desc'],
                    "eventName":eventdata[0]['category'][0]['event_name'],
                    "filts":[],
                    "relation":"and",
                    "relationUser":"and",
                    "renameindicator":""
                },{
                    "eventDesc":eventdata[0]['category'][0]['event_desc'],
                    "eventName":eventdata[0]['category'][0]['event_name'],
                    "filts":[],
                    "relation":"and",
                    "relationUser":"and",
                    "renameindicator":""
                }
                ]
                data['events'] = arr;
                X.api("data_auth/load_filter_props","post",{event_name:d[0]['category'][0]['event_name']},function(val){
                    
                    groupitemeventsdata[0] = val;
                    groupitemeventsdata[1] = val;
                    //初始事件
                    X.template("funnel","funnel-event",data['events']);
                })
            })
            
            //开启重命名
            $(document).off('click','.analysis-chongmingming-initial-event').on('click','.analysis-chongmingming-initial-event',function(){
                $("#analysis-con-left-screen-list-left-zhibiaoname-initial-event").show();
                $(this).hide();
                $(".analysis-chongmingming-del-initial-event").show();
            })

            //取消重命名
            $(document).off('click','.analysis-chongmingming-del-initial-event').on('click','.analysis-chongmingming-del-initial-event',function(){
                $("#analysis-con-left-screen-list-left-zhibiaoname-initial-event").hide();
                $("#analysis-con-left-screen-list-left-zhibiaoname-initial-event input").val('');
                $(this).hide();
                $(".analysis-chongmingming-initial-event").show();
            })

            // 添加指标
            function addindex(){
                var defaultindicator = {
                    "eventDesc":eventdata[0]['category'][0]['event_desc'],
                    "eventName":eventdata[0]['category'][0]['event_name'],
                    "filts":[],
                    "relation":"and",
                    "relationUser":"and",
                    "renameindicator":""
                }
                data['events'].push(defaultindicator);
                X.template("funnel","funnel-event",data['events'],function(){
                    var drr = [];
                    filtersymbols.push(drr);
                    if(data['events'].length > 2){
                        $(".analysis-del").show();
                    }else {
                        $(".analysis-del").hide();
                    }
                });
                
            }

            //添加按钮
            $(document).off('click','.analysis-jia1').on('click','.analysis-jia1',function(){
                addindex();
            })
            $(document).off('click','.funnel-updataevent').on('click','.funnel-updataevent',function(){
                addindex();
            })
            
            // 添加筛选项
            $(document).off('click','.analysis-shaix').on('click','.analysis-shaix',function(){
                var obj = $(this);
                var index = obj.attr("data-index");
                addscreen(index);
            })

            // 添加筛选项
            function addscreen(index){
                console.log(data);
                X.api('data_auth/load_filter_props',"post",{event_name:data['events'][index]["eventName"]},function(d){
                    console.log(d);
                    var arr = {
                        "columnDesc":groupitemeventsdata[0][0]['category'][0]['title'],
                        "columnName":groupitemeventsdata[0][0]['category'][0]['id'],
                        "comparator":"==",
                        "comparatorName":"等于",
                        "ftv":[],
                        "strftv":"",
                        "table_type":groupitemeventsdata[0][0]['category'][0]['data_type'],
                        "timeUnit":""
                    }
                    data['events'][index]['filts'].push(arr);
                    var drr=[];
                    filtersymbols.push(drr);
                    groupitemeventsdata[index] = d;
                    filtersymbols[index][filtersymbols[index].length ] = d[0]['category'][0]["category"];

                    X.template("funnel","funnel-event",data['events']);
                })
            }

            $(document).off('click','.analysis-zhibiao-updata').on('click','.analysis-zhibiao-updata',function(){
                var obj = $(this);
                var index = obj.attr("data-index");
                addscreen(index);
            })

            // 删除指定初始事件筛选
            $(document).off('click','.analysis-del').on('click','.analysis-del',function(){
                var index = $(this).attr("data-index");
                data['events'].splice(index,1);
                filtersymbols[index].splice(index,1);
                // groupitemeventsdata[index].splice(index,1);
                X.template("funnel","funnel-event",data['events']);
            })
            
            //删除指定筛选
            $(document).off('click','.analysis-zhibiao-list-del').on('click','.analysis-zhibiao-list-del',function(){
                var index = $(this).attr("data-index");
                var indexs = $(this).attr("data-twonum");
                data['events'][index]['filts'].splice(indexs,1);
                filtersymbols[index].splice(indexs,1);
                X.template("funnel","funnel-event",data['events']);
            })

            $(document).off('click','.analysis-con-left-screen-list-left-zhibiaoname-initial-event input').on('blur','.analysis-con-left-screen-list-left-zhibiaoname-initial-event input',function(){
                var txt = $(this).val();
                data['events'][0]['renameindicator'] = txt;
            })

            $(document).off('click','.ant-dropdown-trigger').on('click','.ant-dropdown-trigger',function(){
                var obj = $(this);
                var offset = obj.offset();
                var index = obj.attr("data-index");
                var dataevent= data['events'][index];
                // console.log(dataevent);
                X.querycriteriapop(eventdata,'setgrouping',offset.left,offset.top+obj.height(),function(val){
                    console.log(val);
                    obj.html(val.id);
                    dataevent['eventName'] = val.name;
                    dataevent['eventDesc'] = val.id;

                    X.api("data_auth/load_filter_props","post",{event_name:val.name},function(val){
                        groupitemeventsdata[index] = val;
                    })
                    // console.log(data['events']);

                })
            })

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

            // 过滤数据
            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','.analysis-choicetypename').on('click','.analysis-choicetypename',function(){
                var obj = $(this);
                var offset = obj.offset();
                var index = $(this).attr("data-index");
                var indexs = $(this).attr("data-indexs");
                console.log(filtersymbols);
                X.querycriteriapop(filtersymbols[index][indexs],'dropdownlist',offset.left,offset.top+obj.height(),function(val){
                    if(val != undefined){
                        obj.html(val.title);
                        data['events'][index]['filts'][indexs]['comparatorName'] = val.title;
                        data['events'][index]['filts'][indexs]['comparator'] = val.id;
                    }
                })
            })

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

            //全局筛选
            var filtsftvdata=[];
            $(document).off('click','.analysis-overall-situation-add').on('click','.analysis-overall-situation-add',function(){
                var screentypedata = filteringdata();
                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['eventView']['filts'].push(drr);
                filtsftvdata.push(screentypedata[0]['category'][0]['category']);
                if(data['eventView']['filts'].length > 1){
                    $(".analysis-overall-situation-left-guanxi").show();
                }else{
                    $(".analysis-overall-situation-left-guanxi").hide();
                }
                X.template("globalfilter","xinwei-whole",data['eventView']['filts'],function(){
                    analysisdown();
                });
            })

            //删除指定全局数据
            $(document).off('click','.analysis-overall-situation-del').on('click','.analysis-overall-situation-del',function(){
                var index = $(this).attr('data-index');
                data['eventView']['filts'].splice(index,1);
                filtsftvdata.splice(index,1);
                if(data['eventView']['filts'].length > 1){
                    $(".analysis-overall-situation-left-guanxi").show();
                }else{
                    $(".analysis-overall-situation-left-guanxi").hide();
                }
                X.template("globalfilter","xinwei-whole",data['eventView']['filts'],function(){
                    analysisdown();
                });
            })

            $(document).off('click','.analysis-overall-situation-attr').on('click','.analysis-overall-situation-attr',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['eventView']['filts'][index]['columnName'] = val.title;
                    data['eventView']['filts'][index]['column_id'] = val.id;
                    data['eventView']['filts'][index]['data_type'] = val.type;
                    data['eventView']['filts'][index]['comparator_name'] = '等于';
                    data['eventView']['filts'][index]['comparator_id'] = '==';
                    data['eventView']['filts'][index]['table_type'] = val.table_type;
                    filtsftvdata[index]=val.category;
                    analysisdown();//渲染下拉框
                })
            })

            //循环给条件框渲染下拉框
            function analysisdown(){
                for(let i in data['eventView']['filts']){
                    X.laydropdown("#analysis-overall-situation-fuhao-"+i,filtsftvdata[i],function(val){
                        $(this).html(val.title);
                        data['eventView']['filts'][i]['comparator_name'] = val.title;
                        data['eventView']['filts'][i]['comparator_id'] = val.id;
                        if(val.id == "range"){
                            data['eventView']['filts'][i]['ftv'] = [-1,1];
                        }
                        X.template("globalfilter","xinwei-whole",data['eventView']['filts'],function(){
                            analysisdown();
                        });
                    })
                }
            }
            // 分组项
            $(document).off('click','.analysis-action-right').on('click','.analysis-action-right',function() {
                var index = $(this).attr("data-index");
                data.eventView.groupBy.splice(index,1);
                X.template("grouped","shushi",data['eventView']['groupBy']);
                $(".group-updata").show();
            })  

            $(document).off('click','.analysis-footadd___2D4YB').on('click','.analysis-footadd___2D4YB',function() {
                var arr = {
                    "columnName": "#account_id",//事件中文显示
                    "column_id": "#account_id",//事件id
                    'data_type': "string",//类型
                    'table_type': "event",
                    "ftv":'',//条件
                    "section":''//区间
                };
                data['eventView']['groupBy'].push(arr);
                X.template("grouped","shushi",data['eventView']['groupBy']);
                $(this).hide();
            })

            $(document).off('click','.analysis-ant-dropdown-trigger').on('click','.analysis-ant-dropdown-trigger',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);
                    var htmlstring = val.title;
                    obj.html(htmlstring);
                    data.eventView.groupBy[index]['columnName'] = val.title;
                    data.eventView.groupBy[index]['column_id'] = val.id;
                    data.eventView.groupBy[index]['data_type'] = val.type;
                    data.eventView.groupBy[index]['table_type'] = val.table_type;
                })
            })

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

            // 时间粒度
            var timeParticleSizearr = [
                {'title':'1天','id':'1'},
                {'title':'7日','id':'7'},
                {'title':'14日','id':'14'},
                {'title':'30日','id':'30'},
            ]
            X.laydropdown('.analtsis-timeParticleSize',timeParticleSizearr,function(d){
                $(".analtsis-timeParticleSize").html(d.title);
                data['eventView']['windows_gap'] = parseInt(d.id);
                retaineddata();
            })

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

                retaineddata()
            })
            var querydata;
            function retaineddata(){
                data['cachedata']['eventdata'] = eventdata;
                data['cachedata']['groupitemeventsdata'] = groupitemeventsdata;
                data['cachedata']['filtersymbols'] = filtersymbols;
                data['cachedata']['filtsftvdata'] = filtsftvdata;
                var dataArr = {
                    eventView: data.eventView,
                    events: data.events
                }
                X.api("ck/funnel_model","post",dataArr,function(d){
                    d['etitle'] = $.extend(true,[],d['title']);
                    if(d['title'].length == 2){
                        d['etitle'].unshift('总体');
                    }
                    querydata = d;
                    updata(d)
                })
            }

            function updata(d){
                var title = $(".select-chart").attr("title");
                if(title == '转化图'){ retainedtable(d); retaineddayRetained(d);}
                else if(title == '趋势图'){ retainednRetained(d);retainednRetainedtable(d); }
            }

            function retainedtable(d){
                var tabledata=[];
                for(let i in d['list']){
                    var arr = {
                        title: d['list'][i]["title"],
                        data:[]
                    }
                    for(let j in d['list'][i]["n"]){
                        var nrr = {
                            n:0,
                            p:0
                        }
                        nrr["n"] = d['list'][i]["n"][j];
                        nrr["p"] = d['list'][i]["p1"][j]
                        arr['data'].push(nrr);
                    }
                    tabledata.push(arr)
                }
    
                X.laytpldata("#table-fenxi-th-dot",d.etitle,".table-fenxi-th");
                X.laytpldata("#table-fenxi-td-dot",tabledata,".table-fenxi-td");
            }

            //转化图
            function retaineddayRetained(d){
                var arr = {};
                var xAxisData= d['level'];
                var seriesData=[];

                for(let i in d['list']){
                    var arr = {
                        name: d['list'][i]['title'],
                        type: 'bar',
                        barMaxWidth : 30,
                        data: d['list'][i]['p1']
                    }
                    seriesData.push(arr);
                }
            
                var myChart = echarts.init(document.getElementById('funnel-echarts'));
                var option = {
                    color: X.DATA.echartscolor,
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                            label: {
                                backgroundColor: '#6a7985'
                            }
                        }
                    },
                    grid: {
                        left: '2%',
                        right: '2%',
                        bottom: '5%',
                        top: '10%',
                    },
                    xAxis: [
                        {
                            type: 'category',
                            data: xAxisData
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value'
                        }
                    ],
                    series: seriesData
                };
                myChart.setOption(option,true);
            }
            // 趋势图
            function retainednRetained(d){
               var arr = {};
               var legenddata = [];
               var seriesData = [];
               var xAxisdata = [];
               if(jQuery.isEmptyObject(d.date_data)){
                var arr = []
                for(let i in d['summary_values']){
                    var index = d['summary_values'][i]['p'].length - 1;
                    arr.push(d['summary_values'][i]['p'][index]);
                }

                seriesData = {
                    type: 'line',
                    data: arr
                }
               }else {
                var arr =[];
                for(let i in d['date_data']){
                    xAxisdata.push(i);
                    for(let j in d['date_data'][i]){
                        if(arr[j]){
                            arr[j][i] = d['date_data'][i][j]['p1'];
                        }else {
                            arr[j]=[];
                            arr[j][i] = d['date_data'][i][j]['p1'];
                        }
                    }
                }

                var ydata = {};
                for(let j in arr){
                    if(!ydata[j]){
                        ydata[j] = [];
                    }
                    for( let i in xAxisdata ){
                        ydata[j].push("");
                        for(let z in arr[j]){
                            if(xAxisdata[i] == z){
                                var index = arr[j][z].length - 1;
                                ydata[j][i] =arr[j][z][index];
                            }
                        }
                    }
                }

                for(let i in ydata){    
                    legenddata.push(i);
                    var arr = {
                        name: i,
                        type: 'line',
                        data: ydata[i]
                    }
                    seriesData.push(arr)
                } 

               }
                var myChart = echarts.init(document.getElementById('funnel-echarts'));
                var option = {
                    title: {
                        text: ''
                    },
                    color: [ '#3ea7fd', '#cdddfd', '#5ad8a6', '#cdf3e4', '#5d7092', '#ced4de', '#f6bd16','#fcebb9','#e86452','#f8d0cb','#6dc8ec', '#d3eef9', '#9270ca', '#d3c6ea', '#ff9d4d', '#ffd8b8', '#269a99','#aad8d8','#ff99c3','#ffd6e7' ],
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                            label: {
                                backgroundColor: '#6a7985'
                            }
                        }
                    },
                    legend: {
                        type:'scroll',
                        data: legenddata
                    },
                    grid: {
                        left: '2%',
                        right: '2%',
                        bottom: '2%',
                        top: '10%',
                        containLabel: true
                    },
                    xAxis: [
                        {
                            type: 'category',
                            boundaryGap: false,
                            data: xAxisdata
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value'
                        }
                    ],
                    series: seriesData
                };
                myChart.setOption(option,true);

            }
            //趋势图表格
            function retainednRetainedtable(d){
                var arr = {};
                var seriesData = [];
                var xAxisdata = [];
                if(jQuery.isEmptyObject(d.date_data)){
                 var arr = []
                 for(let i in d['summary_values']){
                     var index = d['summary_values'][i]['p'].length - 1;
                     arr.push(d['summary_values'][i]['p'][index]);
                 }
 
                 seriesData = {
                     type: 'line',
                     data: arr
                 }
                }else {
                 var arr =[];
                 for(let i in d['date_data']){
                     xAxisdata.push(i);
                     for(let j in d['date_data'][i]){
                         if(arr[j]){
                             arr[j][i] = d['date_data'][i][j]['p1'];
                         }else {
                             arr[j]=[];
                             arr[j][i] = d['date_data'][i][j]['p1'];
                         }
                     }
                 }
 
                 var ydata = {};
                 for(let j in arr){
                     if(!ydata[j]){
                         ydata[j] = [];
                     }
                     for( let i in xAxisdata ){
                         ydata[j].push(0);
                         for(let z in arr[j]){
                             if(xAxisdata[i] == z){
                                 var index = arr[j][z].length - 1;
                                 ydata[j][i] =arr[j][z][index];
                             }
                         }
                     }
                 }
 
                }
                xAxisdata.unshift('总体');

                var tabdata = [];
                for(let i in ydata){
                    var arr = {
                        'title': i,
                        'data':[]
                    }
                    for(let j in ydata[i]){
                        var nrr = {
                            n:'',
                            p:ydata[i][j]
                        }
                        arr['data'].push(nrr);
                    }
                    tabdata.push(arr);
                }
                console.log(tabdata);
                X.laytpldata("#table-fenxi-th-dot",xAxisdata,".table-fenxi-th");
                X.laytpldata("#table-fenxi-td-dot",tabdata,".table-fenxi-td");
            }

            $(document).off('click','.analtsis-chart-switch').on('click','.analtsis-chart-switch',function(){
                if(querydata){
                    $('.analtsis-chart-switch-box .analtsis-chart-switch').removeClass('select-chart');
                    $(this).addClass('select-chart');
                    if($(this).attr('title') == '转化图'){ retainedtable(querydata); retaineddayRetained(querydata)}
                    else if($(this).attr('title') == '趋势图'){ 
                        retainednRetained(querydata);
                        retainednRetainedtable(querydata);
                     }
                }else{
                    layer.msg('请先计算数据,在切换图表');
                }
            })

            $(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;
                        screentypearr = data.cachedata.screentypearr;
                        filtersymbols = data.cachedata.filtersymbols;
                        filtsftvdata = data.cachedata.filtsftvdata;
    
                        X.template("funnel","funnel-event",data['events']);
                        X.template("grouped","shushi",data['eventView']['groupBy']);
                        X.template("globalfilter","xinwei-whole",data['eventView']['filts'],function(){
                            analysisdown();
                        });
              
                        retaineddata();
                    }

                })
            })

        }
    };
})();