(function(){
    X.pageLogic['ltvmodel'] = {
        init : function(){
           
            X.template("grouped","xinwei-whole");
            var data ={
                "eventView":{
                    "cksql":"ltv",
                    "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,
                    "quota":'#account_id'
                },
                "events":[
                    
                ],
                "cachedata":{
                    eventdata:[],
                    groupitemeventsdata:[],
                }
            };

            // 日期渲染
            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=[[],[]];//分组项里的事件

            X.api("data_auth/my_event","get",{},function(d){
                eventdata = d;
                X.api("data_auth/load_filter_props","post",{event_name:'pay'},function(val){
                    groupitemeventsdata = val;

                    //从数据看板点击进来触发事件
                    if(X.DATA.ltvid && X.DATA.ltvid != ''){
                        var report_idarr = [];
                        report_idarr.push(X.DATA.ltvid);
                        X.api('report/read_report','post',{project_id:X.DATA.projectid,report_id:report_idarr},function(d){
                            backfilldata(d[0]);
                        })
                    }
     
                })
            });

            //全局筛选
            var filtsftvdata=[];
            $(document).off('click','.analysis-overall-situation-add').on('click','.analysis-overall-situation-add',function(){
                var screentypedata = groupitemeventsdata;
                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
                    "ftv":[],//条件
                    "strftv":'',//显示条件
                    "section":[-1,1],//区间
                    "table_type":screentypedata[0]['id'],
                };
                if(data['eventView']['filts'].length == 1){
                    layer.msg('此项只能添加一个');
                    return;
                }
                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();
                }
                console.log(data);
                X.template("globalfilter","xinwei-whole",data['eventView']['filts']);
            });

            var listarr =[
                {title:'角色',id:'#account_id'},
                {title:'设备',id:'#distinct_id'},
                // {title:'账号',id:'binduid'},
            ]
            X.laydropdown('.eventsplit',listarr,function(d){
                $('.eventsplit').html(d.title);
                data['eventView']['quota'] = d.id;
                console.log(d);
            });

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

            $(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]['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'] = '==';
                    data['eventView']['filts'][index]['table_type'] = val.table_type;
                    filtsftvdata[index]=val.category;
                    X.template("globalfilter","xinwei-whole",data['eventView']['filts']);
                })
            });

            $(document).off('click','.analysis-overall-situation-fuhao').on('click','.analysis-overall-situation-fuhao',function(){
                var obj = $(this);
                var offset = obj.offset();
                var index = $(this).attr("data-index");
                X.querycriteriapop(filtsftvdata[index],'dropdownlist',offset.left,offset.top+obj.height(),function(val){
                    if(val != undefined){
                        obj.html(val.title);
                        data['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']);
                    }
                })
            });
            $(document).off('click','.analysis-overall-situation-input input').on('blur','.analysis-overall-situation-input input',function(){
                var val = $(this).val();
                var index = $(this).attr("data-index");
                data['eventView']['filts'][index]['ftv'] = [];
                data['eventView']['filts'][index]['strftv'] = val;
                data['eventView']['filts'][index]['ftv'].push(val);
            });

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



            // 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':'当日','id':'1'},
                {'title':'次日','id':'2'},
                {'title':'7日','id':'7'},
                {'title':'14日','id':'14'},
                {'title':'30日','id':'30'},
            ];
            X.laydropdown('.analtsis-timeParticleSize',timeParticleSizearr,function(d){
                console.log(d);
                $(".analtsis-timeParticleSize").html(d.title);
                data['eventView']['unitNum'] = parseInt(d.id);
                retaineddata();
            });

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

            function retaineddata(){
                data['cachedata']['eventdata'] = eventdata;
                data['cachedata']['groupitemeventsdata'] = groupitemeventsdata;
                var dataArr = {
                    eventView: data.eventView,
                    events: data.events
                }
                X.api("ck/ltv_model","post",dataArr,function(d){
                    if(d.title.length == 0){
                        layer.msg('无数据');
                        return;
                    }else{
                        X.laytpldata("#table-fenxi-th-dot",d.title,".table-fenxi-th");
                        X.laytpldata("#table-fenxi-td-dot",d.rows,".table-fenxi-td");
                    }
                })
            };

            var baobiaodata;//已存报表
            $(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);
                    }

                })
            });

            function backfilldata(d){
                data = d.query;
                eventdata = data.cachedata.eventdata;
                groupitemeventsdata = data.cachedata.groupitemeventsdata;
                baobiaodata = d

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

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


        }
    };
})();