(function(){
    X.pageLogic['distribution'] = {
        init : function(){
            
            var data ={
                "eventView":{
                    "cksql":"scatter",
                    "endTime":"",
                    "groupBy":[],
                    "startTime":"",
                    "timeParticleSize":"P1D"
                },
                "events":[
                    
                ],
                "cachedata":{
                    eventdata : [],
                    type2data : [],
                    type3data : [],
                    groupitemeventsdata: [],
                    filtersymbols:[],//筛选符号
                    screentypearr:[], //筛选项数据
                }
            }

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

            // 日期渲染
            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;
                distributiondata();
            })

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

            $(document).off('click','.analysis-navigation-bar-right-img-baobiao').on('click','.analysis-navigation-bar-right-img-baobiao',function(){
                X.parametersopen(data['eventView']['cksql'],'savedbaobiao','rt',function(d){
                    // console.log(d);
                    if(d){
                        data = d.query;
                        type2data = data.cachedata.type2data;
                        type3data = data.cachedata.type3data;
                        screentypearr = data.cachedata.screentypearr;
                        filtersymbols = data.cachedata.filtersymbols;
    
                        X.template("userpar","userpar-event",data['events']); 
                        X.template("grouped","shushi",data['eventView']['groupBy']);
                        distributiondata();

                    }

                })
            })

            X.template("grouped","shushi");
            
            var eventdata = [];
            var type2data = [];
            var type3data = [];
            var groupitemeventsdata = [];
            var filtersymbols=[];//筛选符号
            var screentypearr=[]; //筛选项数据
            var drr = [];
            screentypearr.push(drr); //每一个筛选事件按添加次数依次写入

            X.api("data_auth/my_event","get",{},function(d){
                eventdata = d;
                var arr = [
                    {
                        "analysis":"times",
                        "analysisDesc":"次数",
                        "eventName":d[0]['category'][0]['event_name'],
                        "eventDesc":d[0]['category'][0]['event_desc'],
                        "filts":[],
                        "intervalType":"def",
                        "quota":"*",
                        "quotaname":"次数",
                        "relation":"and", //筛选关系
                        "type":"normal",
                        "renameindicator":'' //重命名指标
                    }
                ]
                data['events'] = arr;

                X.api("data_auth/load_prop_quotas","post",{event_name:d[0]['category'][0]['event_name'], 'model':'scatter' },function(d){
                    X.template("userpar","userpar-event",data['events']); 
                    var retdata = d.staid_quots.concat(d.props);
                    type2data[0]=retdata;
                    screentypearr[0] = d.props;
                })
                X.api("data_auth/load_filter_props","post",{event_name:d[0]['category'][0]['event_name']},function(val){
                    groupitemeventsdata[0] = val;
                })
            })


            $(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];

                X.querycriteriapop(eventdata,'setgrouping',offset.left,offset.top+obj.height(),function(val){
                    obj.html(val.id);
                    dataevent['eventName'] = val.name;
                    dataevent['eventDesc'] = val.id;
                    X.api("data_auth/load_filter_props","post",{event_name:val.name},function(val){
                        groupitemeventsdata[index] = val;
                    })

                })
            })

            //设置一级事件中第二个参数
            $(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){
                    // console.log(type2data);
                    X.querycriteriapop(type2data[0],'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]['quotaname'] = val.title;
                            data['events'][index]['quota'] = 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]['analysisDesc'] = 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.template("userpar","userpar-event",data['events']); 
                        }
                    })
                }
            })

            //设置一级事件中第三个参数
            $(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");
                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]['analysisDesc'] = val.title;
                            data['events'][index]['analysis'] = val.id;
                        })
                    }
                }
            })

            $(document).off('click','.userevent-granularity').on('click','.userevent-granularity',function(){
                var sectionid = data['events'][0];
                X.parametersopen(sectionid,'groupeditemspop',"auto",function(val){
                    data['events'][0]['intervalType'] = val.type;
                    if(val.type == "user_defined"){
                        data['events'][0]['quotaIntervalArr'] = val.quotaIntervalArr;
                    }
                })
            })

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

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

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

            // 添加筛选项
            $(document).off('click','.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]["eventName"]},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.template("userpar","userpar-event",data['events']);  //更新事件
                    screentypearr[index] = d;
                    filtersymbols.push(d[0]['category'][0]["category"]);
                })
            }

            $(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){
                    // console.log(val);
                    var htmlstring = val.title;
                    obj.html(htmlstring);
                    filtersymbols[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[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;
                        X.template("userpar","userpar-event",data['events']); 
                    }
                })
            })

            $(document).off('click','.analysis-con-left-screen-list-right-screen-qh-tit').on('click','.analysis-con-left-screen-list-right-screen-qh-tit',function(){
                var tit = $(this).html();
                if(tit == '且'){
                    $(this).html('或');
                    data['events'][0]['relation'] = 'or';
                }else{
                    $(this).html('且');
                    data['events'][0]['relation'] = 'and';
                }
            })

            $(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).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 = {
                    "columnName": "#account_id",//事件中文显示
                    "column_id": "#account_id",//事件id
                    'data_type': "string",//类型
                    'table_type': "event",
                    "ftv":'',//条件
                    "section":''//区间
                };
                data['eventView']['groupBy'].push(arr);
                X.template("grouped","shushi",data['eventView']['groupBy']);
            })

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

            // 时间粒度
            var timeParticleSizearr = [
                {'title':'按天','id':'P1D'},
                {'title':'按周','id':'P1W'},
                {'title':'按月','id':'P1M'},
                {'title':'合计','id':'total'}
            ]
            X.laydropdown('.analtsis-timeParticleSize',timeParticleSizearr,function(d){
                // console.log(d);
                $(".analtsis-timeParticleSize").html(d.title);
                data['eventView']['timeParticleSize'] = parseInt(d.id);
                retaineddata();
            })

            // 计算
            $(document).off('click','.analysis-calculation').on('click','.analysis-calculation',function(){

              distributiondata()
              
            })

            var querydata;
            function distributiondata(){
                data['cachedata']['eventdata'] = eventdata;
                data['cachedata']['type2data'] = type2data;
                data['cachedata']['type3data'] = type3data;
                data['cachedata']['groupitemeventsdata'] = groupitemeventsdata;
                data['cachedata']['filtersymbols'] = filtersymbols;
                data['cachedata']['screentypearr'] = screentypearr;
                var dataArr = {
                    eventView: data.eventView,
                    events: data.events
                }
                X.api("ck/scatter_model","post",dataArr,function(d){
                    querydata = d;
                    d['tabletitle'] = $.extend(true,[],d['label']);
                    d['tabletitle'].unshift('事件发生时间','总人数');
                    updata(d)
                })
            }

            function updata(d){
                var title = $(".select-chart").attr("title");
                if(title == '数据表'){ $(".table-div-box").show(); $(".analysis-echarts").hide(); retainedtable(d)}
                else if(title == '数值分布'){ $(".table-div-box").hide(); $(".analysis-echarts").show(); retainednRetained(d) }
                else if(title == '百分比分布'){ $(".table-div-box").hide(); $(".analysis-echarts").show(); retaineddayRetained(d) }
            }
            
            $(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') == '数值分布'){ $(".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('请先计算数据,在切换图表');
                }
            })

            function retainedtable(d){
                var tabledata = [];
                for(let i in d.list){
                    var arr = {
                        date: i,
                        total: d['list'][i]['总体']["total"],
                        data:[]
                    }
                    for(let j in d['list'][i]['总体']["n"]){
                        var nrr = {
                            n:0,
                            p:0
                        }
                        nrr["n"] = d['list'][i]['总体']["n"][j];
                        nrr["p"] = d['list'][i]['总体']["p"][j]
                        arr['data'].push(nrr);
                    }
                    tabledata.push(arr)
                }
                // console.log(tabledata);
                X.laytpldata("#table-fenxi-th-dot",d.tabletitle,".table-fenxi-th");
                X.laytpldata("#table-fenxi-td-dot",tabledata,".table-fenxi-td");
            }

            function retainednRetained(d){
                var legendData = d.label;
                var xAxisData = [];
                var seriesData = [];
                var arr =[];
                for(let i in d['list']){
                    xAxisData.push(i);
                    for(let j in d['list'][i]){
                        if(arr[j]){
                            arr[j][i] = d['list'][i][j]['n'];
                        }else {
                            arr[j]=[];
                            arr[j][i] = d['list'][i][j]['n'];
                        }
                    }
                }
                var ydata = {};
                for(let j in arr){
                    if(!ydata[j]){
                        ydata[j] = [];
                    }
                    for( let i in xAxisData){
                        ydata[j].push("");
                        for(let z in arr[j]){
                            if(xAxisData[i] == z){
                                var index = arr[j][z].length - 1;
                                ydata[j][i] =arr[j][z][index];
                            }
                        }
                    }
                } 
                for(let i in ydata){
                    var arr = {
                        name: i,
                        type: 'line',
                        areaStyle: {},
                        emphasis: {
                            focus: 'series'
                        },
                        data: ydata[i]
                    }
                    seriesData.push(arr);
                }
                
                var myChart = echarts.init(document.getElementById('distribution-echarts'));
                var option = {
                    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);
            }
            
            function retaineddayRetained(d){
                var legendData = d.label;
                var xAxisData = [];
                var seriesData = [];
                var arr =[];
                for(let i in d['list']){
                    xAxisData.push(i);
                    for(let j in d['list'][i]){
                        if(arr[j]){
                            arr[j][i] = d['list'][i][j]['p'];
                        }else {
                            arr[j]=[];
                            arr[j][i] = d['list'][i][j]['p'];
                        }
                    }
                }
                var ydata = {};
                for(let j in arr){
                    if(!ydata[j]){
                        ydata[j] = [];
                    }
                    for( let i in xAxisData){
                        ydata[j].push("");
                        for(let z in arr[j]){
                            if(xAxisData[i] == z){
                                var index = arr[j][z].length - 1;
                                ydata[j][i] =arr[j][z][index];
                            }
                        }
                    }
                } 
                for(let i in ydata){
                    var arr = {
                        name: i,
                        type: 'line',
                        areaStyle: {},
                        emphasis: {
                            focus: 'series'
                        },
                        data: ydata[i]
                    }
                    seriesData.push(arr);
                }
                
                var myChart = echarts.init(document.getElementById('distribution-echarts'));
                var option = {
                    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',
                            axisLabel: {
                                formatter:'{value}%'
                            }
                        }
                    ],
                    series: seriesData
                };
                myChart.setOption(option,true);
            }

            $(document).off('click','.analysis-savereport').on('click','.analysis-savereport',function(){
                X.parametersopen(data,'savereport','auto')  
            })

        }
    };
})();