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

            var data ={
                "eventView":{
                    "cksql":'user_property',
                    "groupBy":[
                        
                    ],
                    "userCrowds":[
            
                    ]
                },
                "events":{
                    "analysis":"",
                    "analysisName":"",
                    "eventNameDisplay":"",
                    "filts":[
                        
                    ],
                    "quota":"",
                    "quotaDesc":"",
                    "quotatype":"",
                    "relation":"and",
                    "tableType":"user"
                },
                "cachedata":{}
            };

            // 分析属性控制重命名
            $(document).off('click','.analysis-chongmingming').on('click','.analysis-chongmingming',function(){
                $('.analysis-con-left-screen-list-left-zhibiaoname').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').hide();
                $(this).hide();
                $('.analysis-chongmingming').show();
            });

            //用户属性数据请求
            var user_attr = [];
            var quotas_map = [];
            var filter_map = [];
            var user_data = []; //分组项，用户符合，人群对比数据格式
            X.api("data_auth/user_property","get",{},function(val){
                for(let i in val){
                    var arr = {
                        id : val[i]['name'],
                        data_type : val[i]['data_type'],
                        title : val[i]['name']
                    };
                    user_attr.push(arr);
                }
                data['events']['quota']  = user_attr[0]['id'];
                data['events']['quotaDesc']  = user_attr[0]['title'];
                data['events']['quotatype'] = user_attr[0]['data_type'];
                $('.ant-dropdown-trigger').html(user_attr[0]['title']);
                

                var arr = {
                    category: user_attr,
                    id:'',
                    title:'用户属性'
                }
                user_data.push(arr);
                // console.log(user_data);

                X.api("data_auth/quotas_map","get",{},function(val){
                    quotas_map = val;
                    if(user_attr[0]['data_type'] == ""){
                        $('.analysis-choicetypename').hide();
                    }else {
                        $('.analysis-choicetypename').html(quotas_map[user_attr[0]['data_type']][0]['title']);
                        data['events']['analysis'] = quotas_map[user_attr[0]['data_type']][0]['id'];
                        data['events']['analysisName'] = quotas_map[user_attr[0]['data_type']][0]['title'];
                    }
                })

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

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

            });

             // 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).off('click','.ant-dropdown-trigger').on('click','.ant-dropdown-trigger',function(){
                var obj = $(this);
                var offset = obj.offset();
                X.querycriteriapop(user_attr,'dropdownlist',offset.left,offset.top+obj.height(),function(val){
                    obj.html(val.title);
                    data['events']['quota']  = val.id;
                    data['events']['quotaDesc']  = val.title;
                    data['events']['quotatype'] = val.data_type;
                    if(val.data_type == ""){
                        $('.analysis-choicetypename').hide();
                    }else {
                        $('.analysis-choicetypename').show();
                        data['events']['analysis']  = quotas_map[val.data_type][0].id;
                        data['events']['analysisDesc']  = quotas_map[val.data_type][0].title;
                        $('.analysis-choicetypename').html(quotas_map[val.data_type][0]['title']);
                    }
                })
            });

            $(document).off('click','.analysis-choicetypename').on('click','.analysis-choicetypename',function(){
                var obj = $(this);
                var offset = obj.offset();
                X.querycriteriapop(quotas_map[data['events']['quotatype']],'dropdownlist',offset.left,offset.top+obj.height(),function(val){
                    obj.html(val.title);
                    data['events']['analysis']  = val.id;
                    data['events']['analysisDesc']  = val.title;
                    
                })
            });

            $(document).off('click','.analysis-con-left-screen-list-left-zhibiaoname input').on('blur','.analysis-con-left-screen-list-left-zhibiaoname input',function(){
                // console.log($(this).val());
                data['events']['eventNameDisplay'] = $(this).val();
            });

            // 分组项
            X.template("grouped","shushi",data['eventView']['groupBy']);
            $(document).off('click','.analysis-footadd___2D4YB').on('click','.analysis-footadd___2D4YB',function(){
                var arr = {
                    "columnName": user_data[0]['category'][0]['title'],//事件中文显示
                    "column_id": user_data[0]['category'][0]['id'],//事件id
                    'data_type': user_data[0]['category'][0]['data_type'],//类型
                    'table_type': "",
                    "ftv":'',//条件
                    "intervalType":'def',
                    "quotaIntervalArr":[]
                };
                data['eventView']['groupBy'].push(arr);
                if(data['eventView']['groupBy'].length >= 2){
                    $(this).hide();
                }
                X.template("grouped","shushi",data['eventView']['groupBy']);
            });

            $(document).off('click','.analysis-action-right').on('click','.analysis-action-right',function(){
                var index = $(this).attr('data-index');
                data['eventView']['groupBy'].splice(index,1);
                if(data['eventView']['groupBy'].length < 2){
                    $(".analysis-footadd___2D4YB").show();
                }
                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 index = obj.attr('data-index');
                var offset = obj.offset();
                X.querycriteriapop(user_data,'category',offset.left,offset.top+obj.height(),function(val){
                    // console.log(val);
                    obj.html(val.title);
                    data['eventView']['groupBy'][index]['column_id']  = val.id;
                    data['eventView']['groupBy'][index]['columnName']  = val.title;
                    data['eventView']['groupBy'][index]['data_type']  = val.type;
                    X.template("grouped","shushi",data['eventView']['groupBy']);
                })
            });

            $(document).off('click','.analysis-ta-property-range').on('click','.analysis-ta-property-range',function(){
                var index = $(this).attr('data-index');
                var sectionid = data['eventView']['groupBy'][index];
                X.parametersopen(sectionid,'groupeditemspop',"auto",function(val){
                    data['eventView']['groupBy'][index]['intervalType'] = val.type;
                    if(val.type == "user_defined"){
                        data['eventView']['groupBy'][index]['quotaIntervalArr'] = val.quotaIntervalArr;
                    }
                })
            });

            //且用户符合
            $(document).off('click','.analysis-overall-situation-add').on('click','.analysis-overall-situation-add',function(){
                var drr={
                    "columnName":user_data[0]['category'][0]['title'],//事件中文显示
                    "column_id":user_data[0]['category'][0]['id'],//事件id
                    'data_type':user_data[0]['category'][0]['data_type'],//类型
                    'comparator_name':'等于',//默认等于
                    "comparator":'==',//符号id
                    "ftv":[],//条件
                    "strftv":'',//显示条件
                    "section":[-1,1],//区间
                    "table_type":user_data[0]['id']
                };

                data['events']['filts'].push(drr);
                
                if(data['events']['filts'].length > 1){
                    $(".analysis-overall-situation-left-guanxi").show();
                }else{
                    $(".analysis-overall-situation-left-guanxi").hide();
                }
                X.template("globalfilter","xinwei-whole",data['events']['filts']);
            });

            $(document).off('click','.analysis-overall-situation-left-guanxi').on('click',".analysis-overall-situation-left-guanxi",function(){
                var tit = $(this).html();
                if(tit == "且"){
                    $(this).html('或');
                    data['events']['relation'] = 'or';
                }else {
                    $(this).html('且');
                    data['events']['relation'] = 'and';
                }
            });

            $(document).off('click','.analysis-overall-situation-attr').on('click','.analysis-overall-situation-attr',function(){
                var obj = $(this);
                var index = obj.attr('data-index');
                var offset = obj.offset();

                X.querycriteriapop(user_data,'category',offset.left,offset.top+obj.height(),function(val){
                    obj.html(val.title);
                    data['events']['filts'][index]['column_id']  = val.id;
                    data['events']['filts'][index]['columnName']  = val.title;
                    data['events']['filts'][index]['data_type']  = val.type;
                    X.template("globalfilter","xinwei-whole",data['events']['filts']);
                })
            });

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

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

            $(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['events']['filts'][index][index]['ftv'][0] = val;
                }else {
                    data['events']['filts'][index]['ftv'][1] = val;
                }
            });

            $(document).off('click','.analysis-overall-situation-del').on('click','.analysis-overall-situation-del',function(){
                var index = $(this).attr('data-index');
                data['events']['filts'].splice(index,1);
                if(data['events']['filts'].length > 1){
                    $(".analysis-overall-situation-left-guanxi").show();
                }else{
                    $(".analysis-overall-situation-left-guanxi").hide();
                }
                X.template("globalfilter","xinwei-whole",data['events']['filts']);
            });

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

            function calculationdata(){
                data['cachedata']['user_attr'] = user_attr;
                data['cachedata']['quotas_map'] = quotas_map;
                data['cachedata']['filter_map'] = filter_map;
                data['cachedata']['user_data'] = user_data;
                var dataArr = {
                    eventView: data.eventView,
                    events: data.events
                }
                X.api("ck/user_property_model","post",dataArr,function(val){
                    attributetable(val);
                    querydata = val;
                    updata(val)
                })
            };

            function updata(d){
                var title = $(".select-chart").attr("title");
                if(title == '柱状分布图'){ attributebar(d);}
                else if(title == '饼状图'){ attributepie(d); }
            };

            var querydata;
            $(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') == '柱状分布图'){ attributebar(querydata);}
                    else if($(this).attr('title') == '饼状图'){ 
                        attributepie(querydata);
                     }
                }else{
                    layer.msg('请先计算数据,在切换图表');
                }
            });

            function attributetable(val){
                X.laytpldata("#table-attrbute-th-dot",val.title,".table-attrbute-th");
                X.laytpldata("#table-attrbute-td-dot",val.value,".table-attrbute-td");
            };

            function attributebar(val){

                var xAxisData = [];
                var seriesdata =[];
                for(let i in val.value){
                    xAxisData.push(i);
                    seriesdata.push(val.value[i]);
                }

                var myChart = echarts.init(document.getElementById('attribute-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: [{
                        data: seriesdata,
                        type: 'bar',
                    
                    }]
                };
                myChart.setOption(option,true);
            };

            function attributepie(val){
                // console.log(val);
                var seriesdata = [];
                for(let i in val.value){
                    var arr = {
                        value: val['value'][i],
                        name: i
                    };
                    seriesdata.push(arr);
                }
                // console.log(seriesdata);
                var myChart = echarts.init(document.getElementById('attribute-echarts'));
                var option = {
                    // color: X.DATA.echartscolor,
                    tooltip: {
                        trigger: 'item'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                    },
                    series: [
                        {
                            name: '访问来源',
                            type: 'pie',
                            radius: ['40%', '70%'],
                            data: seriesdata,
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ]
                };
                myChart.setOption(option,true);
            };

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

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

            // 反向填充数据
            function backfilldata(d){
                data = d.query;
                console.log(d);

                user_attr = data.cachedata.user_attr;
                quotas_map = data.cachedata.quotas_map;
                filter_map = data.cachedata.filter_map;
                user_data = data.cachedata.user_data;

                baobiaodata = d;
               
                // if(d.query.eventView.filts.length > 0){
                //     $(".analysis-overall").show();
                // }else {
                //     $(".analysis-overall").hide();
                // }
                X.template("globalfilter","xinwei-whole",data['events']['filts']);
                X.template("grouped","shushi",data['eventView']['groupBy']);
                calculationdata();
            }

        }
    };
})();