(function(){
    X.pageLogic['retained'] = {
        init : function(parms){

            X.template("grouped","shushi");
            // X.template("toptab","analysis-zhanwei",X.DATA['projectarr']);
            
            var data ={
                "eventView":{
                    "cksql":"retention",
                    "endTime":"2021-06-07 23:59:59",
                    "filts":[],
                    "groupBy":[],
                    "e_days":0,
                    "s_days":7,
                    "relation":"and",
                    "startTime":"2021-05-09 00:00:00",
                    "statType":"retention",
                    "timeParticleSize":"P1D",
                    "unitNum":7,
                    "filter_item_type":'all',
                    "filter_item":[]
                },
                "events":[
                    
                ]
            };

            // 重新渲染控件
            layui.form.render();

            // 日期渲染
            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;

                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);
                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 groupitemeventsdata;//分组项里的事件
            var querydata; //计算后返回的数据
            var filter_map,quotas_map;

            X.api("data_auth/my_event","get",{},function(d){
                eventdata = d;

                X.api("data_auth/load_prop_quotas","post",{event_name:eventdata[0]['category'][0]['event_name']},function(val){
                    
                    type2data = val.props;

                    var arr = [{
                        "eventDesc":eventdata[0]['category'][0]['event_desc'],
                        "eventName":eventdata[0]['category'][0]['event_name'],
                        "filts":[],
                        "relation":"and",
                        "relationUser":"and",
                        "renameindicator":"",
                        "event_attr": type2data[0]['title'],
                        "event_attr_id": type2data[0]['id'],
                    },{
                        "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 = val;
                        //初始事件
                        // console.log(data['events'][0]);
                        X.template("event","initial-event",data['events'][0]);
                        X.template("returnvisitevent","returnvisit-event",data['events'][1]);

                        X.api("data_auth/filter_map","get",{},function(d){
                            filter_map = d;

                            X.api('data_auth/quotas_map',"get",{},function(d){
                                quotas_map = d;
                                //从数据看板点击进来触发事件
                                if(X.DATA.retentionid && X.DATA.retentionid != ''){
                                    var report_idarr = [];
                                    report_idarr.push(X.DATA.retentionid);
                                    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]);
                                    })
                                }
                            })

                        })

                        
                    })
                })
            });

            $(document).off('click','.analysis-zhibiao-list-type2').on('click','.analysis-zhibiao-list-type2',function(){
                var obj = $(this);
                var offset = obj.offset();
                var index = obj.attr("data-index");
                if(type2data.length >0){
                    X.parametersopen(type2data,'dropdownlist',[offset.top+obj.height(),offset.left],function(val){
                        // if(val != undefined){
                            console.log(val);
                            $("#analysis-zhibiao-list-type2-"+index).html(val.title);
                            data['events'][index]['event_attr'] = val.title;
                            data['events'][index]['event_attr_id'] = val.id;
                        // }
                    })
                }
            });
           
            //开启重命名
            $(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-return-event').on('click','.analysis-chongmingming-return-event',function(){
                $("#analysis-con-left-screen-list-left-zhibiaoname-return-event").show();
                $(this).hide();
                $(".analysis-chongmingming-del-return-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();
            });

            $(document).off('click','.analysis-chongmingming-del-return-event').on('click','.analysis-chongmingming-del-return-event',function(){
                $("#analysis-con-left-screen-list-left-zhibiaoname-return-event").hide();
                $("#analysis-con-left-screen-list-left-zhibiaoname-return-event input").val('');
                $(this).hide();
                $(".analysis-chongmingming-return-event").show();
            });

            // 添加初始事件筛选
            // var initialevent = []
            $(document).off('click','.analysis-shaix-initial-event').on('click','.analysis-shaix-initial-event',function(){
                var arr = {
                    "columnDesc":groupitemeventsdata[0]['category'][0]['title'],
                    "columnName":groupitemeventsdata[0]['category'][0]['id'],
                    "comparator":"==",
                    "comparatorName":"等于",
                    "ftv":[],
                    "strftv":"",
                    "tableType":groupitemeventsdata[0]['category'][0]['data_type'],
                    "data_type":groupitemeventsdata[0]['category'][0]['data_type'],
                    "timeUnit":""
                }
                // initialevent.push(arr);
                data['events'][0]['filts'].push(arr);

                X.template("event","initial-event",data['events'][0]);
            });
            var returnevent = [];
            $(document).off('click','.analysis-shaix-return-event').on('click','.analysis-shaix-return-event',function(){
                var arr = {
                    "columnDesc":groupitemeventsdata[0]['category'][0]['title'],
                    "columnName":groupitemeventsdata[0]['category'][0]['id'],
                    "comparator":"==",
                    "comparatorName":"等于",
                    "ftv":[],
                    "strftv":"",
                    "tableType":groupitemeventsdata[0]['category'][0]['data_type'],
                    "data_type":groupitemeventsdata[0]['category'][0]['data_type'],
                    "timeUnit":""
                }
                // data['events'][1]['filts'].push(arr);
                returnevent.push(arr);
                data['events'][1]['filts'] = returnevent;
                X.template("returnvisitevent","returnvisit-event",data['events'][1]);
            });

            // 删除指定初始事件筛选
            $(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'][0]['filts'].splice(index,1);
                X.template("event","initial-event",data['events'][0]);
            });

            $(document).off('click','.analysis-zhibiao-list-del-return-event').on('click','.analysis-zhibiao-list-del-return-event',function(){
                var index = $(this).attr("data-twonum");
                data['events'][1]['filts'].splice(index,1);
                X.template("returnvisitevent","returnvisit-event",data['events'][1]);
            });
            
            $(document).off('blur','.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('blur','.analysis-con-left-screen-list-left-zhibiaoname-return-event input').on('blur','.analysis-con-left-screen-list-left-zhibiaoname-return-event input',function(){
                var txt = $(this).val();
                data['events'][1]['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){
                    obj.html(val.id);
                    dataevent['eventName'] = val.name;
                    dataevent['eventDesc'] = val.id;
                    // 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");
                X.querycriteriapop(groupitemeventsdata,'category',offset.left,offset.top+obj.height(),function(val){
                    var htmlstring = val.title;
                    obj.html(htmlstring);
                    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]['tableType'] = val.table_type;
                    if(val.type == 'user_label'){                        
                        data['events'][index]['filts'][indexs]['comparatorName'] = "是";   
                        data['events'][index]['filts'][indexs]['comparator'] = 'in';        
                    }
                    if(index == 0){
                        X.template("event","initial-event",data['events'][0]);
                    }else {
                        X.template("returnvisitevent","returnvisit-event",data['events'][1]);
                    }
                })
            });
            
            $(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");
                var type = data['events'][index]['filts'][indexs]['data_type'];
                console.log(type);
                X.parametersopen(filter_map[type],'dropdownlist',[offset.top+obj.height(),offset.left],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").on("click",".analysis-zhibiao-list-type4",function(){
                var obj = $(this);
                var offset = obj.offset();
                var index = $(this).attr("data-index");
                var indexs = $(this).attr("data-indexs");
                var columnName = data['events'][index]['filts'][indexs]['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){
                            data['events'][index]['filts'][indexs]['strftv'] = val.title;
                            var arr = [];
                            arr.push(val.id);
                            data['events'][index]['filts'][indexs]['ftv'] = arr; 
                            X.template("event","initial-event",data['events'][0]);
                            X.template("returnvisitevent","returnvisit-event",data['events'][1]);
                        })
                    }
                })
            });

            
            $(document).off("click",".analysis-overall-situation-input").on("click",".analysis-overall-situation-input",function(){
                var obj = $(this);
                var offset = obj.offset();
                var index = $(this).attr("data-index");
                var columnName = data['eventView']['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){
                            data['eventView']['filts'][index]['strftv'] = val.title;
                            var arr = [];
                            arr.push(val.id);
                            data['eventView']['filts'][index]['ftv'] = arr; 
                            X.template("globalfilter","xinwei-whole",data['eventView']['filts'],function(){
                                renderdate();
                            });
                        })
                    }
                })
            });

            $(document).off('change','.analysis-zhibiao-list-type4 input').on('change','.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 = groupitemeventsdata;
                console.log(screentypedata);
                var drr={
                    "columnName":screentypedata[0]['category'][0]['id'],//事件id
                    //"column_id":screentypedata[0]['category'][0]['id'],
                    "columnDesc":screentypedata[0]['category'][0]['title'],//事件中文显示
                    'data_type':screentypedata[0]['category'][0]['data_type'],//类型
                    'comparator_name':'等于',//默认等于
                    "comparator":'==',//符号id
                    "ftv":[],//条件
                    "strftv":'',//显示条件
                    "section":[-1,1],//区间
                    "tableType":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(){
                    renderdate();
                });
            });

            //删除指定全局数据
            $(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(){
                    renderdate();
                });
            });

            $(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(groupitemeventsdata,'category',offset.left,offset.top+obj.height(),function(val){
                    console.log(val);
                    obj.html(val.title);
                    data['eventView']['filts'][index]['columnDesc'] = val.title;
                    data['eventView']['filts'][index]['columnName'] = val.id;
                    data['eventView']['filts'][index]['data_type'] = val.type;
                    data['eventView']['filts'][index]['comparator_name'] = '等于';
                    data['eventView']['filts'][index]['comparator'] = '==';
                    data['eventView']['filts'][index]['tableType'] = val.table_type;
                    filtsftvdata[index]=val.category;

                    if(val.type == 'user_label'){                        
                        data['eventView']['filts'][index]['comparator_name'] = "是";                        
                        data['eventView']['filts'][index]['comparator'] = 'in';                     
                    }

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

            //循环给条件框渲染下拉框
            // 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'] = val.id;
            //             if(val.id == "range"){
            //                 data['eventView']['filts'][i]['ftv'] = [-1,1];
            //             }
            //             X.template("globalfilter","xinwei-whole",data['eventView']['filts'],function(){
            //                 analysisdown();
            //             });
            //         })
            //     }
            // };

            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['eventView']['filts'][render_date_index]['strftv'] = value;
                        var datearr = [];
                        datearr.push(value)
                        data['eventView']['filts'][render_date_index]['ftv'] = datearr;
                      }
                    });
                });
            };

            $(document).off('click','.analysis-overall-situation-fuhao').on('click','.analysis-overall-situation-fuhao',function(){
                var obj = $(this);
                var offset = obj.offset();
                var index = obj.attr("data-index");
                var type = data['eventView']['filts'][index]['data_type'];
                console.log(type);
                X.parametersopen(filter_map[type],'dropdownlist',[offset.top+obj.height(),offset.left],function(val){
                    $(this).html(val.title);
                    data['eventView']['filts'][index]['comparator_name'] = val.title;
                    data['eventView']['filts'][index]['comparator'] = val.id;
                    if(val.id == "range"){
                        data['eventView']['filts'][index]['ftv'] = [-1,1];
                    }
                    X.template("globalfilter","xinwei-whole",data['eventView']['filts'],function(){
                        renderdate();
                    });
                })
            }); 

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

            // 分组项
            $(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']);
            });

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

            });

            $(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(groupitemeventsdata,'category',offset.left,offset.top+obj.height(),function(val){
                    var htmlstring = val.title;
                    obj.html(htmlstring);
                    data.eventView.groupBy[index]['columnDesc'] = val.title;
                    data.eventView.groupBy[index]['columnName'] = val.id;
                    data.eventView.groupBy[index]['data_type'] = val.type;
                    data.eventView.groupBy[index]['tableType'] = val.tableType;
                })
            });

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

            // 时间粒度
            X.laydropdown('.analtsis-timeParticleSize',X['DATA']['companylist']['retention'],function(d){
                // console.log(d);
                $(".analtsis-timeParticleSize").html(d.title);
                data['eventView']['unitNum'] = parseInt(d.id);
                retaineddata();
            });

            //留存流失
            var retentionloss = [
                {'title':'留存','id':0},
                {'title':'流失','id':1}
            ]
            var retentiontype = 0;//判断是显示流失数据还是留存
            X.laydropdown('.retention-loss',retentionloss,function(d){
                $('.retention-loss').html(d.title);
                if(querydata['summary_values']){
                    retentiontype = d.id;
                    updata(querydata);
                }
            })

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

            function retaineddata(){
                var dataArr = {
                    eventView: data.eventView,
                    events: data.events
                }
                X.api("ck/retention_model","post",dataArr,function(d){
                    if(d != "查无数据"){
                        querydata = d;
                        updata(d);
                        $(".chawushuj").hide();
                    }else {
                        $("#analysis-echarts").empty();
                        $(".table-fenxi-th").html("");
                        $(".table-fenxi-td").html("");
                        $(".chawushuj").show();
                    }
                })
            };

            $(document).off('click','.analysis-savereport').on('click','.analysis-savereport',function(){
                if(baobiaodata != '' && baobiaodata != undefined && baobiaodata != null){
                    baobiaodata['saveas']= 0;
                    X.parametersopen(baobiaodata,'savereport','auto');
                }else{
                    X.parametersopen(data,'savereport','auto');          
                }
            });

            //另存为
            $(document).off('click','.analysis-saveas').on('click','.analysis-saveas',function(){
                baobiaodata['saveas']= 1;
                X.parametersopen(baobiaodata,'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){
                        backfilldata(d);
                    }

                })
            });

            var baobiaodata;//以存报表数据
            function backfilldata(d){
                data = d.query;
                baobiaodata = d;
                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";

                X.template("event","initial-event",data['events'][0]);
                X.template("returnvisitevent","returnvisit-event",data['events'][1]);
                X.template("globalfilter","xinwei-whole",data['eventView']['filts'],function(){
                    renderdate();
                });
                X.template("grouped","shushi",data['eventView']['groupBy']);
      
                retaineddata();
            };

            function updata(d){
                var title = $(".select-chart").attr("title");
                if(title == '数据报表'){ $(".table-div-box").show(); $(".analysis-echarts").hide(); retainedtable(d)}
                else if(title == '第N日留存'){ $(".table-div-box").hide(); $(".analysis-echarts").show(); retainednRetained(d) }
                else if(title == '每日留存'){ $(".table-div-box").hide(); $(".analysis-echarts").show(); retaineddayRetained(d) }
            };

            //数据报表渲染
            function retainedtable(d){
                var nname,pname

                if(data['eventView']['filter_item_type'] != "all" && data['eventView']['filter_item_type']){
                    // var filteritem = data['eventView']['filter_item'];
                    // if(d['days'].length >= 0){
                        // var filterarr = [];
                        // for(let i in d['days']){
                        //     for(let j in filteritem){
                        //         if(d['days'][i] == filteritem[j]){
                        //             filterarr.push(i);
                        //         }
                        //     }
                        // }
                    // }
                    // var titarr = [];
                    // var tablearr = [];
                    // for(let i in filterarr){
                    //     var index = Number(filterarr[i])  + 2;
                    //     titarr.push(titdata[index]);
                    // }
                    // titarr.unshift(titdata[0],titdata[1]);
                    // console.log(titarr);
                }

                if(retentiontype == 0) {
                    nname = 'n';
                    pname = 'p';
                }else {
                    nname = 'n_outflow';
                    pname = 'p_outflow';
                }
                var tabledata=[];
                for(let i in d['summary_values']){
                    var arr = {
                        date: i,
                        d0:d['summary_values'][i]['d0'],
                        data:[]
                    }
                    for(let j in d['summary_values'][i]["n"]){
                        var nrr = {
                            n:0,
                            p:0
                        }
                        // if(data['eventView']['filter_item_type'] != "all" && data['eventView']['filter_item_type']){
                        //     for(let a in filterarr){
                        //         var index = Number(filterarr[a]);
                        //         if(j == index){
                        //             nrr["n"] = d['summary_values'][i][nname][j];
                        //             nrr["p"] = d['summary_values'][i][pname][j]
                        //             arr['data'].push(nrr);
                        //         }
                        //     }
                        // }else {
                            nrr["n"] = d['summary_values'][i][nname][j];
                            nrr["p"] = d['summary_values'][i][pname][j]
                            arr['data'].push(nrr);
                        // }
                    }
                    tabledata.push(arr)
                }
    
                // var titdata = [];
                // if(data['eventView']['filter_item_type'] != "all" && data['eventView']['filter_item_type']){
                //     var titarr = [];
                //     for(let j in filterarr){
                //         var index = Number(filterarr[j]);
                //         titarr.push(d['days'][index]);
                //     }
                //     for(let i in titarr){
                //         var tit = "第" + titarr[i] + "日";
                //         titdata.push(tit);
                //     }
                // }else {
                //     for(let i in d['days']){
                //         var tit = "第" + d['days'][i] + "日";
                //         titdata.push(tit);
                //     }
                // }
                // titdata.unshift("日期",d.title);
                // console.log(titdata);
                 console.log(tabledata);

                // X.fixedTable('table-div-box','row-col-fixed','',headdata);


                X.laytpldata("#table-fenxi-th-dot",d.title,".table-fenxi-th");
                X.laytpldata("#table-fenxi-td-dot",tabledata,".table-fenxi-td");
            };

            // 每日留存
            function retaineddayRetained(d){
                var arr = {};
                var xAxisData=[];
                var seriesData=[];
                var legenddata = [];
                if(jQuery.isEmptyObject(d.values)){
                    legenddata = d.date_range;
                    for(let i in d['days']){
                        var tit = "第" + i + "日";
                        xAxisData.push(tit);
                    }
                    for(let i in d['summary_values']){
                        var arr = {
                            name: i,
                            type: 'line',
                            data: d['summary_values'][i]['p']
                        }
                        seriesData.push(arr);
                    }
                }else {
                    var timearr = [];
                    for(let i in d.values){
                        timearr.push(i);
                        for(let j in d.values[i]){
                            if(arr[j]){
                                arr[j][i] = d.values[i][j]['p'];
                            }else {
                                arr[j]=[];
                                arr[j][i] = d.values[i][j]['p'];
                            }
                        }
                    }
    
                    var ydata = {};
                    for(let j in arr){
                        if(!ydata[j]){
                            ydata[j] = [];
                        }
                        for( let i in timearr ){
                            ydata[j].push("");
                            for(let z in arr[j]){
                                if(timearr[i] == z){
                                    var index = arr[j][z].length - 1;
                                    ydata[j][i] =arr[j][z][index];
                                }
                            }
                        }
                    }
                    console.log(ydata);
                    // for(let i in ydata){    
                    //     legenddata.push(i);
                    //     var arr = {
                    //         name: i,
                    //         type: 'line',
                    //         data: ydata[i]
                    //     }
                    //     seriesData.push(arr)
                    // } 
                }
                return;
                var myChart = echarts.init(document.getElementById('analysis-echarts'));
                var option = {
                    title: {
                        text: ''
                    },
                    color:  X.DATA.echartscolor,
                    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);
            };
            // 第N日留存
            function retainednRetained(d){
                var nname,pname
                if(retentiontype == 0) {
                    nname = 'n';
                    pname = 'p';
                }else {
                    nname = 'n_outflow';
                    pname = 'p_outflow';
                }
               var arr = {};
               var legenddata = [];
               var seriesData = [];
               if(jQuery.isEmptyObject(d.values)){
                var arr = []
                for(let i in d['summary_values']){
                    var index = d['summary_values'][i][pname].length - 1;
                    legenddata.push(i);
                    arr.push(d['summary_values'][i][pname]);
                }
                d.title.splice(0,1);
                xAxisData = d.title;
                
                for(let i in arr){
                    var drr = {
                        name: d.date_range[i],
                        type: 'line',
                        data: arr[i]
                    }
                    seriesData.push(drr);
                }

               }else {
                var timearr = [];
                for(let i in d.values){
                    timearr.push(i);
                    for(let j in d.values[i]){
                        if(arr[j]){
                            arr[j][i] = d.values[i][j][pname];
                        }else {
                            arr[j]=[];
                            arr[j][i] = d.values[i][j][pname];
                        }
                    }
                }
                var ydata = {};
                for(let j in arr){
                    if(!ydata[j]){
                        ydata[j] = [];
                    }
                    for( let i in timearr ){
                        ydata[j].push("");
                        for(let z in arr[j]){
                            if(timearr[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 selected = {};//线多的话默认显示5条
                if(legenddata.length > 5){
                    for(let i in legenddata){
                        if(i < 5){
                            selected[legenddata[i]] = true;
                        }else {
                            selected[legenddata[i]] = false;
                        }
                    }
                }

                var myChart = echarts.init(document.getElementById('analysis-echarts'));
                var option = {
                    title: {
                        text: ''
                    },
                    color: X.DATA.echartscolor,
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                            label: {
                                backgroundColor: '#6a7985'
                            }
                        }
                    },
                    legend: {
                        type:'scroll',
                        data: legenddata,
                        selected:selected
                    },
                    grid: {
                        left: '2%',
                        right: '2%',
                        bottom: '2%',
                        top: '10%',
                        containLabel: true
                    },
                    xAxis: [
                        {
                            type: 'category',
                            boundaryGap: false,
                            data: d.date_range
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value'
                        }
                    ],
                    series: seriesData
                };
                myChart.setOption(option,true);

            };

            $(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') == '数据报表'){ $(".table-div-box").show(); $(".analysis-echarts").hide(); retainedtable(querydata)}
                    else if($(this).attr('title') == '第N日留存'){ $(".table-div-box").hide(); $(".analysis-echarts").show(); retainednRetained(querydata) }
                    else if($(this).attr('title') == '每日留存'){ $(".table-div-box").hide(); $(".analysis-echarts").show(); retaineddayRetained(querydata) }
                }else{
                    layer.msg('请先计算数据,在切换图表');
                }
            });

            //显示设置
            $(document).off('click','.analtsis-condition-xssz').on('click','.analtsis-condition-xssz',function(){
                var obj = $(this);
                var offset = obj.offset();
                // offset.left,offset.top+obj.height()
                $(".showsetup-box").show();
                $(".showsetup-down-box").css('top',offset.top+obj.height());
                $(".showsetup-down-box").css('left',offset.left-211);
                layui.form.val('showsetupexample',{
                    'showsetup': data['eventView']['filter_item_type']
                })
            });

            $(document).off('click','.showsetup-box-zz').on('click','.showsetup-box-zz',function(){
                $(".showsetup-box").hide();
            });

            layui.form.on('radio(showsetup)', function(val){
                if(val.value == 'date'){
                    $(".showsetup-edit").show();
                    $(".showsetup-bianji-show-box-type").show();
                    var value = $(".showsetup-bianji-input-box textarea").val();
                    var valarr = value.split(',');
                    valarr.sort(function(a, b){return a - b});
                    var listarr = unique(valarr);
                    data['eventView']['filter_item'] = listarr;             
                    X.laytpldata("#showsetup-bianji-show-box-dot",listarr,".showsetup-bianji-show-box");
                }else {
                    $(".showsetup-edit").hide();
                    $(".showsetup-wancheng").hide();
                    $(".showsetup-bianji-show-box-type").hide();
                    $(".showsetup-bianji-input-box-type").hide();
                }
                data['eventView']['filter_item_type'] = val.value;
                if(querydata){
                    retainedtable(querydata)
                }
            });

            $(document).off('click','.showsetup-edit').on('click','.showsetup-edit',function(){
                $(".showsetup-edit").hide();
                $(".showsetup-wancheng").show();
                $(".showsetup-bianji-show-box-type").hide();
                $(".showsetup-bianji-input-box-type").show();
            });

            $(document).off('click','.showsetup-wancheng').on('click','.showsetup-wancheng',function(){
                $(".showsetup-edit").show();
                $(".showsetup-wancheng").hide();
                $(".showsetup-bianji-show-box-type").show();
                $(".showsetup-bianji-input-box-type").hide();
                var value = $(".showsetup-bianji-input-box textarea").val();
                var valarr = value.split(',');
                valarr.sort(function(a, b){return a - b});
                var listarr = unique(valarr);
                data['eventView']['filter_item'] = listarr;
                X.laytpldata("#showsetup-bianji-show-box-dot",listarr,".showsetup-bianji-show-box");
                if(querydata){
                    retainedtable(querydata)
                }
            });

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

            // 下载
            $(document).off('click','.download-table').on('click','.download-table',function(){
                console.log(11111);
                X.download('ck/retention_model_export',data,'事件分析');
            });


        }
    };
})();