(function(){
    X.pageLogic['analysis'] = {
        init : function(){
            var me = this;
            // 渲染form样式
            layui.form.render();

            var dataArr; //分析指标
            var groupeddata;//分组项
            var type2data =[],type3data = [];
            var screentypearr=[]; //筛选项数据
            var drr = [];
            screentypearr.push(drr); //每一个筛选事件按添加次数依次写入
            var filtersymbols=[];//筛选符号
            filtersymbols.push(drr);
            var groupitemeventsdata=[]//分组项里的事件
            var defaultgroupdata //默认添加分组项里的事件
            var data = {
                "events":[],
                "eventView":{
                    "cksql":"event",
                    "startTime":"",
                    "timeParticleSize":"P1D",
                    "endTime":"",
                    "graphShape":"L0",
                    "e_days":0,
                    "s_days":7,
                    "groupBy":[],
                    "uiCommonConfig":{
                        "tableSorts":[],
                        "chartSort":"num-desc"
                    },
                    "filts":[],//全局筛选
                    "relation":1,
                    "zone_time":'8'//时区
                },
                "cachedata":{
                    type2data:[],
                    type3data:[],
                    screentypearr:[],
                    filtersymbols:[],
                    groupitemeventsdata:[],
                    defaultgroupdata:[],
                }
            }

            var retdata,props;

             // 日期渲染
            X.daterender("#analtsis-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);
                console.log(parseInt((sameday - endmonth)/86400));
                console.log(parseInt((sameday - startmonth)/86400));
                // calculationdata();
            })

            var time = $("#analtsis-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("toptab","analysis-zhanwei",X.DATA['projectarr'],function(){
            X.api("data_auth/my_event","get",{},function(d){
            
                dataArr = d;
                X.api("data_auth/load_prop_quotas","post",{event_name:dataArr[0]['category'][0]['event_name']},function(d){
                    retdata = d.staid_quots.concat(d.props);
                    props = d.props;
                    var defaultindicator = {
                        "event_desc":dataArr[0]['category'][0]['event_desc'],
                        "event_name":dataArr[0]['category'][0]['event_name'],
                        "event_attr":"总次数",
                        "event_attr_id":"*",
                        "analysisname":'',
                        "analysis":'total_count',
                        "filts":[],//过滤项
                        "condrelation":'and',
                        "customEvent":'',
                        "eventNameDisplay":'',//重命名指标
                        "format":'float',
                        "formatname":'两位小数'
                    }
                    data.events.push(defaultindicator);
                    X.laytpldata("#analysis-con-left-screen-list-dot",data.events,".analysis-con-left-screen-list-box");
                    type2data[0]= retdata;
                    type3data[0]= [];
                    screentypearr[0]=d.props;
                    X.api("data_auth/load_filter_props","post",{event_name:dataArr[0]['category'][0]['event_name']},function(val){
                        defaultgroupdata = val;
                        groupitemeventsdata.push(val);

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

                    })
                })
                // groupeddata = d.group_by;
            })
            // });
            

            // 渲染选择时间下拉框
            layui.dropdown.render({
                elem: ".analysis-navigation-bar-datetime"
                ,data: X.DATA.timezone
                ,click: function(obj){
                    $(".analysis-navigation-bar-datetime").html(obj.title);
                    data['eventView']['zone_time'] = obj.id;
                }
              });

            //   伸缩左侧选项
            $(".analysis-con-left-shrink").click(function(){
                if($(".analysis-con-left").css('left') == "auto" || $(".analysis-con-left").css('left') == "0px"){
                    $(".analysis-con-left").css("position","absolute");
                    $(".analysis-con-left").css("left","-535px");
                    $(".analysis-con-left-shrink").css("transform","rotate(180deg)");
                    $(".analysis-con-right").css("width","calc(100% - 15px)");
                    $(".analysis-con-right").css("margin-left","16px");
                }else {
                    $(".analysis-con-left").css("position","relative");
                    $(".analysis-con-left").css("left","auto");
                    $(".analysis-con-left-shrink").css("transform","rotate(3600deg)");
                    $(".analysis-con-right").css("width","calc(100% - 550px)");
                    $(".analysis-con-right").css("margin-left","0px");
                }
            });

            //已存报表
            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){
                    if(d){
                        backfilldata(d)
                    }
                })
            });

            // 反向填充数据
            function backfilldata(d){
                data = d.query;
                type2data = data.cachedata.type2data;
                type3data = data.cachedata.type3data;
                screentypearr = data.cachedata.screentypearr;
                filtersymbols = data.cachedata.filtersymbols;

                baobiaodata = d;
               
                if(d.query.eventView.filts.length > 0){
                    $(".analysis-overall").show();
                }else {
                    $(".analysis-overall").hide();
                }

                X.laytpldata("#analysis-con-left-screen-list-dot",d.query.events,".analysis-con-left-screen-list-box");
                X.laytpldata("#analysis-gpmain___3YGfw-dot",d.query.eventView.groupBy,".analysis-gpmain___3YGfw");
                X.laytpldata("#analysis-overall-situation-list-box-dot",d.query['eventView']['filts'],".analysis-overall-situation-list-box");
                analysisdown();
                calculationdata();
            }

            // 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).on('click','.analysis-gongshi',function(){
                var index = $(this).attr("data-index");
                $("#analysis-con-left-screen-list-left-box-"+index).hide();
                $("#analysis-custom-box-"+index).show();
                $(this).hide();
                $("#analysis-con-left-screen-list-right-"+index+" "+".analysis-zhibiao").show();

            });
            
            // 切换为指标选择
            $(document).on('click','.analysis-zhibiao',function(){
                var index = $(this).attr("data-index");
                $("#analysis-con-left-screen-list-left-box-"+index).show();
                $("#analysis-custom-box-"+index).hide();
                $(this).hide();
                $("#analysis-con-left-screen-list-right-"+index+" "+".analysis-gongshi").show();
            });

            //复制指标
            $(document).on('click','.analysis-fuzhi',function(){
                var index = $(this).attr("data-index");
                var arr = data.events[index];
                data.events.push(arr);
                X.laytpldata("#analysis-con-left-screen-list-dot",data.events,".analysis-con-left-screen-list-box");
                var num = data.events.length;
                type2data[num] = type2data[index];
                type3data[num] = type3data[index];
                screentypearr[num] = screentypearr[index];
                filtersymbols[num] = filtersymbols[index];
            });

            //重命名指标
            $(document).off('click','.analysis-chongmingming').on('click','.analysis-chongmingming',function() {
                var index = $(this).attr('data-index');
                $("#analysis-con-left-screen-list-left-zhibiaoname-"+index).show();
                $(this).hide();
                $("#analysis-con-left-screen-list-right-"+index+" "+".analysis-chongmingming-del").show();
            });

            //删除重命名
            $(document).off('click','.analysis-chongmingming-del').on('click','.analysis-chongmingming-del',function() {
                var index = $(this).attr("data-index");
                $("#analysis-con-left-screen-list-left-zhibiaoname-"+index).hide();
                $("#analysis-con-left-screen-list-left-zhibiaoname-"+index+" "+"input").val('');
                $(this).hide();
                $("#analysis-con-left-screen-list-right-"+index+" "+".analysis-chongmingming").show();
            });
            
            // 设置一级事件
            $(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')
                X.querycriteriapop(dataArr,'setgrouping',offset.left,offset.top+obj.height(),function(val){
                    var htmlstring = val.id;
                    obj.html(htmlstring);
                    data['events'][index]['event_desc'] = val.id;
                    data['events'][index]['event_name'] = val.name;
                    X.api("data_auth/load_prop_quotas","post",{event_name:val.name},function(d){
                        var retdata = d.staid_quots.concat(d.props);
                        type2data[index]=retdata;
                        screentypearr[index] = d.props;
                    })

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

                    
                })
            });
            //设置一级事件中第二个参数
            $(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.querycriteriapop(type2data[index],'dropdownlist',offset.left,offset.top+obj.height(),function(val){
                        if(val != undefined){
                            $("#analysis-zhibiao-list-type2-"+index).html(val.title);
                            
                            type3data[index]=val.category;
                            data['events'][index]['event_attr'] = val.title;
                            data['events'][index]['event_attr_id'] = val.id;
                            if(val.category &&  val.category.length > 0){
                                $("#analysis-zhibiao-list-type3-"+index).show();
                                $("#analysis-zhibiao-list-type3-"+index).html(val.category[0].title);
                                data['events'][index]['analysisname'] = val.category[0].title;
                                data['events'][index]['analysis'] = val.category[0].id;
                            }else {
                                $("#analysis-zhibiao-list-type3-"+index).hide();
                                data['events'][index]['analysis'] = val.analysis;
                            }
                            X.laytpldata("#analysis-con-left-screen-list-dot",data.events,".analysis-con-left-screen-list-box");
                        }
                    })
                }
            });
            //设置一级事件中第三个参数
            $(document).off('click','.analysis-zhibiao-condition').on('click','.analysis-zhibiao-condition',function(){
                var obj = $(this);
                var offset = obj.offset();
                var index = obj.attr("data-index");
                var indexs = obj.attr("data-indexs");
                if(type3data.length>0){
                    if(type3data[index].length > 0){
                        X.querycriteriapop(type3data[index],'dropdownlist',offset.left,offset.top+obj.height(),function(val){
                            $("#analysis-zhibiao-list-type3-"+index).html(val.title);
                            data['events'][index]['analysisname'] = val.title;
                            data['events'][index]['analysis'] = val.id;
                        })
                    }
                }
            });

            $(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(screentypearr[index],'category',offset.left,offset.top+obj.height(),function(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]['tableType'] = val.table_type;
                })

            });

            $(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");
                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]['comparator_name'] = val.title;
                        data['events'][index]['filts'][indexs]['comparator'] = val.id;
                    }
                })
            });

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

            // 添加筛选项
            function addscreen(index){
                X.api('data_auth/load_filter_props',"post",{event_name:data['events'][index]["event_name"]},function(d){

                    var arr = {
                        "columnDesc":d[0]['category'][0]['title'],//事件中文显示
                        "columnName":d[0]['category'][0]['id'],//事件id
                        "comparator_name":d[0]['category'][0]['category'][0]['title'],//选择符号中文显示
                        "comparator":d[0]['category'][0]['category'][0]['id'],//符号id
                        "data_type":d[0]['category'][0]['data_type'],
                        "ftv":'',//条件
                        "strftv":'',//字符串显示条件
                        "tableType": d[0]['id']
                    } //筛选数据
                    data['events'][index]['filts'].push(arr);
                    X.laytpldata("#analysis-con-left-screen-list-dot",data.events,".analysis-con-left-screen-list-box");
                    var drr=[];
                    filtersymbols.push(drr);
                    screentypearr[index] = d;
                    filtersymbols[index][filtersymbols[index].length ] = d[0]['category'][0]["category"];
                })
            };

            //监听重命名指标
            $(document).off('click','.analysis-con-left-screen-list-left-zhibiaoname input').on('blur','.analysis-con-left-screen-list-left-zhibiaoname input',function(){
                var index = $(this).attr("data-index");
                var txt = $(this).val();
                data['events'][index]['eventNameDisplay'] = txt;
            });

            // 监听文本框
            $(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 val = $(this).val();
                var valarr = val.split(",");
                data['events'][index]['filts'][indexs]['ftv']=valarr;
                data['events'][index]['filts'][indexs]['strftv']=val;
            });

            // 且和或切换
            $(document).on("click",".analysis-con-left-screen-list-right-screen-qh-tit",function(){
                var html = $(this).html(); //condrelation筛选条件的关系
                var index = $(this).attr("data-index");
                if(html == "且"){
                    $(this).html('或');
                    data['events'][index]['condrelation'] = 'or'
                }else {
                    $(this).html('且');
                    data['events'][index]['condrelation'] = 'and'
                }
            });

            // 添加条件按钮
            $(document).on('click',".analysis-zhibiao-updata",function(){
                // addindex();
            });

            // 删除二级筛选项
            $(document).on('click','.analysis-zhibiao-list-del',function(){
                // var id = "analysis-zhibiao-list-mar-"+$(this).attr("data-twonum");
                // $("#"+id).remove();
                var index = $(this).attr("data-index");
                var indexs = $(this).attr("data-indexs");
                filtersymbols[index].splice(indexs,1);
                data.events[index]['filts'].splice(indexs,1);
                X.laytpldata("#analysis-con-left-screen-list-dot",data.events,".analysis-con-left-screen-list-box");
            });

            // 添加指标
            function addindex(){
                var defaultindicator = {
                    "event_desc":dataArr[0]['category'][0]['event_desc'],
                    "event_name":dataArr[0]['category'][0]['event_name'],
                    "event_attr":"总次数",
                    "event_attr_id":"*",
                    "analysisname":'',
                    "analysis":'total_count',
                    "filts":[],//过滤项
                    "condrelation":'and',
                    "customEvent":'',
                    "eventNameDisplay":'',//重命名指标
                    "format":'float',
                    "formatname":'两位小数'
                }
                data['events'].push(defaultindicator);

                X.laytpldata("#analysis-con-left-screen-list-dot",data.events,".analysis-con-left-screen-list-box");
                var index = data.events.length - 1;
                type2data[index]= retdata;
                type3data[index]= [];
                $(".analysis-del").show() //显示删除按钮
                var drr = [];
                screentypearr.push(drr);
                if(data.events.length > 1){
                    $(".analysis-overall").show();
                }else {
                    $(".analysis-overall").hide();
                }
                screentypearr[index]=props;
                groupitemeventsdata.push(defaultgroupdata);
            };

            //添加按钮
            $(document).on('click','.analysis-jia1',function(){

                addindex();

            });
            //添加指标按钮
            $(document).on('click','.analysis-bottom-jia1',function(){

                addindex();

            });

            //删除指标
            $(document).on('click',".analysis-del",function(){
                if(data['events'].length != 1){
                    var index = $(this).attr("data-index");
                    data['events'].splice(index,1);
                    if(data['events'].length == 1){
                        $(".analysis-del").hide(); //隐藏删除按钮
                        $(".analysis-overall").hide();
                    }
                    X.laytpldata("#analysis-con-left-screen-list-dot",data.events,".analysis-con-left-screen-list-box");
                }
            });
            

            $(".analysis-custom-event-box .analysis-custom-event-txt").blur(function(){
                $(this).css("border-bottom","0px");
            
            });

            $(document).off('click','.analysis-custom-event-box .analysis-custom-event-txt').on('blur','.analysis-custom-event-box .analysis-custom-event-txt',function(){
                // $(this).css("border-bottom","1px solid #3d90ff");
                var obj = $(this);
                var offset = obj.offset();
                var index = obj.attr("data-index");
                data['events'][index]['customEvent'] = $(this).val();
            });

            $(document).off('click','.analysis-con-left-screen-list-left-zhibiaoname2 input').on('blur','.analysis-con-left-screen-list-left-zhibiaoname2 input',function(){
                var index = $(this).attr('data-index');
                data['events'][index]['eventNameDisplay'] = $(this).val();
            });

            $(document).off('click','.ant-select-selector').on('click','.ant-select-selector',function(){
                var obj = $(this);
                var offset = obj.offset();
                var index = $(this).attr("data-index");
                var downlist = [
                    {title:'两位小数',id:'float'},
                    {title:'百分比',id:'percent'},
                    {title:'取整',id:'integer'},
                ];
                X.querycriteriapop(downlist,'dropdownlist',offset.left,offset.top+obj.height(),function(val){
                    if(val != undefined){
                        obj.html(val.title);
                        data['events'][index]['format'] = val.id;
                        data['events'][index]['formatname'] = val.title;
                    }
                })

            });

            //分组项
            var cat = "event";
            $(document).off('click','.analysis-footadd___2D4YB').on('click','.analysis-footadd___2D4YB',function(){
                var index = data['eventView']['groupBy'].length;
                var screentypedata = filteringdata();
                for(let i in screentypedata){
                    if(screentypedata[i]['category'].length > 0){
                        var drr = {
                            "columnDesc":screentypedata[i]['category'][index]['title'],//事件中文显示
                            "columnName":screentypedata[i]['category'][index]['id'],//事件id
                            'data_type':screentypedata[i]['category'][index]['data_type'],//类型
                            'tableType': screentypedata[i]['id'],
                            "ftv":'',//条件
                            "section":''//区间
                        }
                        break;
                    }
                }
                
                data.eventView.groupBy.push(drr);
                X.laytpldata("#analysis-gpmain___3YGfw-dot",data.eventView.groupBy,".analysis-gpmain___3YGfw");

            });

            $(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){
                    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.table_type;
                    X.laytpldata("#analysis-gpmain___3YGfw-dot",data.eventView.groupBy,".analysis-gpmain___3YGfw");
                })
            });

            $(document).off('click','.analysis-granularity').on("click",".analysis-granularity",function(){
                var obj = $(this);
                var offset = obj.offset();
                var type = obj.attr("data_type");
                var index = obj.attr("data-index");
                var arr;
                if(type == 'date'){
                    arr = {
                        data:[
                            {'name':"按天",'id':'day','checked':true},
                            {'name':"按分钟",'id':'min','checked':false},
                            {'name':"按小时",'id':'hour','checked':false},
                            {'name':"按周",'id':'week','checked':false},
                            {'name':"按月",'id':'month','checked':false}
                        ],
                        default: data.eventView.groupBy[index]['ftv']
                        
                    }
                }else {
                    arr ={
                        data:[
                            {'name':"按元素",'id':'0','checked':true},
                            {'name':"按列表整体",'id':'1','checked':false},
                            {'name':"按元素集合",'id':'2','checked':false}
                        ],
                        default: data.eventView.groupBy[index]['ftv']
                    } 
                }

                X.querycriteriapop(arr,'groupitem',offset.left,offset.top+obj.height(),function(val){
                    data.eventView.groupBy[index]['ftv'] = val.id;
                })
            });

            $(document).on("click",".analysis-section",function(){
                var obj = $(this);
                var offset = obj.offset();
                var sectionid = obj.attr("data-sectionid");
   
                X.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    shadeClose: true,
                    skin: 'yourclass',
                    url: 'groupeditemspop',
                    extData : sectionid,
                    callback : function(val){

                    }
                  })

            });

            $(document).on('click','.analysis-action-right',function(){
                var index = $(this).attr('data-index');
                data.eventView.groupBy.splice(index,1);
                X.laytpldata("#analysis-gpmain___3YGfw-dot",data.eventView.groupBy,".analysis-gpmain___3YGfw");
            });

            $(document).on('click','.analysis-event-splitting',function(){

            });

            // 过滤数据
            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;
            };

            // 全局筛选
            var filtsftvdata=[];
            $(document).on('click','.analysis-overall-situation-add',function(){

                var screentypedata = filteringdata();
                var drr={
                    "columnDesc":screentypedata[0]['category'][0]['title'],//事件中文显示 columnDesc
                    "columnName":screentypedata[0]['category'][0]['id'],//事件id
                    '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'])

                $(".analysis-overall-situation-left-box").show();

                if(data['eventView']['filts'].length > 1){
                    $(".analysis-overall-situation-left-guanxi").show();
                }else{
                    $(".analysis-overall-situation-left-guanxi").hide();
                }
                X.laytpldata("#analysis-overall-situation-list-box-dot",data['eventView']['filts'],".analysis-overall-situation-list-box");
                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'] = val.id;
                        if(val.id == "range"){
                            data['eventView']['filts'][i]['ftv'] = [-1,1];
                        }
                        X.laytpldata("#analysis-overall-situation-list-box-dot",data['eventView']['filts'],".analysis-overall-situation-list-box");
                        analysisdown();
                    })
                }
            };

            $(document).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();
                    // $(".analysis-overall-situation-left-box").hide();
                }
                X.laytpldata("#analysis-overall-situation-list-box-dot",data['eventView']['filts'],".analysis-overall-situation-list-box");
                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){
                    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;
                    X.laytpldata("#analysis-overall-situation-list-box-dot",data['eventView']['filts'],".analysis-overall-situation-list-box");
                    analysisdown();
                })
            });

            $(document).off('click','.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['eventView']['filts'][index]['ftv']=valarr;
                data['eventView']['filts'][index]['strftv']=val;
            });

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

            // 时间粒度
            var timeParticleSizearr = [
                {'title':'按天','id':'P1D'},
                {'title':'按分钟','id':'PT1M'},
                {'title':'每五分钟','id':'PT5M'},
                {'title':'每十分钟','id':'PT10M'},
                {'title':'每十五分钟','id':'PT15M'},
                {'title':'按小时','id':'PT1H'},
                {'title':'按周','id':'P1W'},
                {'title':'按月','id':'P1M'},
                {'title':'合计','id':'total'},
            ];

            X.laydropdown('.analtsis-timeParticleSize',timeParticleSizearr,function(d){
                $(".analtsis-timeParticleSize").html(d.title);
                data['eventView']['timeParticleSize'] = d.id;
                calculationdata();
            });

            X.layuidate('#analysis-overall-situation-time1');
           
            // 计算
            $(document).off('click','.analysis-calculation').on('click','.analysis-calculation',function(){
                calculationdata();
                
            });

            var querydata;//查询数据
            $(document).on('click','.analtsis-chart-switch-box .analtsis-chart-switch',function(){
                if(querydata){
                    $('.analtsis-chart-switch-box .analtsis-chart-switch').removeClass('select-chart');
                    $(this).addClass('select-chart');
                    if($(this).attr('title') == '趋势图'){trendchart(querydata)}
                    else if($(this).attr('title') == '堆积图'){stackingdiagram(querydata);}
                    else if($(this).attr('title') == '累计图'){}
                    else if($(this).attr('title') == '分布图'){distributionmap(querydata)}
                    else if($(this).attr('title') == '饼状分布'){}
                }else{
                    // layer.msg('请先计算数据,在切换图表');
                }

            });

            //堆积图
            function stackingdiagram(d){
                var xAxisData=[];
                for(let i in d){
                    for(let z in d[i]['groups']){
                        var pj =  d[i]['event_name']+d[i]['groups'][z];
                        xAxisData.push(pj);
                    }
                }
                var seriesData=[];
                for(let i in d){
                    for(let z in d[i]['values']){
                        var arr = {
                            name: '',
                            type: 'line',
                            stack: '总量',
                            areaStyle: {},
                            emphasis: {
                                focus: 'series'
                            },
                            data: d[i]['values'][z]
                        }
                        seriesData.push(arr);
                    }
                }
                if(xAxisData.length > 0){
                    for(let i in seriesData){
                        seriesData[i]['name'] = xAxisData[i];
                    }
                }

                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: xAxisData
                    },
                    grid: {
                        left: '2%',
                        right: '2%',
                        bottom: '2%',
                        top: '10%',
                        containLabel: true
                    },
                    xAxis: [
                        {
                            type: 'category',
                            boundaryGap: false,
                            data: d[0]['date_range']
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value'
                        }
                    ],
                    series: seriesData
                };
                myChart.setOption(option,true);
            };

            //趋势图
            function trendchart(d){
                var xAxisData=[];
                for(let i in d){
                    for(let z in d[i]['groups']){
                        var pj =  d[i]['event_name']+d[i]['groups'][z];
                        xAxisData.push(pj);
                    }
                }
                var seriesData=[];
                for(let i in d){
                    for(let z in d[i]['values']){
                        var arr = {
                            name: '',
                            type: 'line',
                            data: d[i]['values'][z]
                        }
                        seriesData.push(arr);
                    }
                }
                if(xAxisData.length > 0){
                    for(let i in seriesData){
                        seriesData[i]['name'] = xAxisData[i];
                    }
                }
                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: xAxisData
                    },
                    // toolbox: {
                    //     feature: {
                    //         saveAsImage: {}
                    //     }
                    // },
                    grid: {
                        left: '2%',
                        right: '2%',
                        bottom: '2%',
                        top: '10%',
                        containLabel: true
                    },
                    xAxis: [
                        {
                            type: 'category',
                            boundaryGap: false,
                            data: d[0]['date_range']
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value'
                        }
                    ],
                    series: seriesData
                };
                myChart.setOption(option,true);
            };

            //分布图
            function distributionmap(d){
                var legendData =[];
                var xAxisData=[];
                var seriesData=[];
                if(jQuery.isEmptyObject(d[0]["groups"])){
                    for(let i in d){
                        xAxisData.push(d[i]['event_name']);
                        legendData.push(d[i]['event_name']);
                        var num =0;
                        for(let j in d[i]['values'][i]){
                            num = num + d[i]['values'][i][j]
                        }
                        var arr = {
                            name: d[i]['event_name'],
                            type: 'bar',
                            barWidth : 30,
                            data: [],
                        }
                        arr['data'].push(num);
                        seriesData.push(arr);
                    }
                    
                }else {
                    for(let i in d){
                        xAxisData.push(d[i]['event_name']);
                        for(let j in d[i]['groups']){
                            var num =0;
                            for(let z in d[i]['values'][j]){
                                num = num + d[i]['values'][j][z]
                            }
                            if(i > 0){
                                for(let q in seriesData){
                                    if(d[i]['groups'][j] == seriesData[q]['name']){
                                        seriesData[q]['data'].push(num);
                                    }else {
                                        var arr = {
                                            name: d[i]['groups'][j],
                                            type: 'bar',
                                            barWidth : 30,
                                            data: [],
                                        }
                                        arr['data'].push(num);
                                        seriesData.push(arr);
                                    }
                                }
                            }else {
                                var arr = {
                                    name: d[i]['groups'][j],
                                    type: 'bar',
                                    barWidth : 30,
                                    data: [],
                                }
                                arr['data'].push(num);
                                seriesData.push(arr);
                            }
                            

                        }
                    }
                }
                // for(let i in d){
                //     for(let z in d[i]['groups']){
                //         var pj =  d[i]['event_name']+d[i]['groups'][z];
                //         xAxisData.push(pj);
                //     }
                // }
                // var seriesData=[];
                // for(let i in d){
                //     for(let z in d[i]['values']){
                //         var arr = {
                //             name: '',
                //             type: 'bar',
                //             data: d[i]['values'][z]
                //         }
                //         seriesData.push(arr);
                //     }
                // }
                // if(xAxisData.length > 0){
                //     for(let i in seriesData){
                //         seriesData[i]['name'] = xAxisData[i];
                //     }
                // }
                // return;
                var myChart = echarts.init(document.getElementById('analysis-echarts'));
                var option = {
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    color: X.DATA.echartscolor,
                    legend: {
                        data: legendData
                    },
                    grid: {
                        left: '2%',
                        right: '2%',
                        bottom: '2%',
                        top: '10%',
                        containLabel: true
                    },
                    xAxis: [
                        {
                            type: 'category',
                            axisTick: {show: false},
                            data: xAxisData
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value'
                        }
                    ],
                    series: seriesData
                };
                myChart.setOption(option,true);
            };

            //表格
            function tabledata(d){
                var titledata,condata = [];
                for(let i in d){
                    if(d[i]['groups']['length'] == 0){
                        titledata= $.extend(true,[],d[0]['date_range']) ;
                        titledata.unshift('指标','阶段总和');
                        condata.push(d[i].values[0]);
                        condata[i].unshift(d[i]['event_name'],d[i]['sum']);
                    }else {

                    }
                }
                
                X.laytpldata("#table-fenxi-th-dot",titledata,".table-fenxi-th");
                X.laytpldata("#table-fenxi-td-dot",condata ,".table-fenxi-td");
            };

            function calculationdata(){
                data['cachedata']['type2data'] = type2data;
                data['cachedata']['type3data'] = type3data;
                data['cachedata']['screentypearr'] = screentypearr;
                data['cachedata']['filtersymbols'] = filtersymbols;
                data['cachedata']['groupitemeventsdata'] = groupitemeventsdata;
                data['cachedata']['defaultgroupdata'] = defaultgroupdata;
                var dataArr = {
                    eventView: data.eventView,
                    events: data.events
                }
                X.api("ck/event_model","post",dataArr,function(d){
                    querydata = d;
                    if(d.length > 0){
                        if(d[0].values.length > 0 ){
                            updata();
                            tabledata(d);
                            // stackingdiagram(d);
                            // tabledata(d);
                        }else {
                            $("#analysis-echarts").empty();
                            layer.msg("无数据");
                        }
                    }else {
                        $("#analysis-echarts").empty();
                        layer.msg("无数据");
                    }
                    
                })
            };

            function updata(){
               var tit = $(".select-chart").attr("title");
               if(tit == '趋势图'){trendchart(querydata)}
                else if(tit == '堆积图'){stackingdiagram(querydata);}
                else if(tit == '累计图'){}
                else if(tit == '分布图'){distributionmap(querydata)}
                else if(tit == '饼状分布'){}
            };

            // 保存报表
            $(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');          
                }
            });

        },

        // 保存报表
        // savereport:function(d){

        // }

    };
})();


