//cc
(function(){
    X.pageLogic['dashboard'] = {
        init :function(){
            var me = this;
            
            var popid='';

            layui.element.init();

            var userinfo = localStorage.getItem('loginData');
            if(userinfo){
                X.DATA["userinfo"] = JSON.parse(userinfo);
            }else {
                layer.msg('登录过期请重新登录！！！');
                X.gourl("login");
                return;
            }

            // 项目列表
            // http://10.0.0.7:6789/
            X.api("project/","get",{},function(d){
                X.laytpldata('#layui-project-dot',d,'.layui-project-box');
                X.DATA['projectarr'] = d;
                X.DATA['projectid'] = X.DATA['projectid'] || d[0]["_id"];
                X.DATA["game"] = X.DATA["game"] || d[0]["game"];
                for(let i in d){
                    if(d[i]['game'] == X.DATA["game"]){
                        $(".projecttit").html(d[i]['name']);
                    }
                }
                me.freshMenu(X.DATA['projectid']);
                // X.template("toptab","analysis-zhanwei",d);
            });

            

            // $(".username").html(X.DATA.userinfo.name);

            // 选择项目
            $(document).off('click','.selectproject').on('click','.selectproject',function(){
                var id = $(this).attr("data-id");
                var game = $(this).attr("data-game");
                $(".projecttit").html($(this).html());
                X.DATA['projectid'] = id;
                X.DATA["game"] = game;
                //侧边栏数据渲染
                me.freshMenu(id);
                // X.pageLogic.dashboard.freshMenu(id);
            });

            //a标签点击跳转事件
            $(document).off('click','.layui-nav-child a').on('click','.layui-nav-child a',function(){
                var url = $(this).attr("data-url");
                X.gourl(url);
            });

            // 修改面板名
            $(document).off('click','.layui-left-dd').on('click','.layui-left-dd',function(){
                $(".tab-tit-box .tab-tit").html($(this).find("span").html());
                X.DATA['dashboard_id'] = $(this).attr('data-id'); //看板id
                $("#model-box").html("");
                // 获取报表数据
                me.gettabledata();
            });

            // 渲染添加按钮侧边栏下拉框
            X.laydropdown("#chuangjian",X.DATA.createsidebar,function(d){
                if(d.url){
                    X.open({
                        type: 1,
                        title: false,
                        closeBtn: 0,
                        shadeClose: true,
                        url: d.url
                    })
                }
              this.elem.val(d.title);
            });

            // 时间控件渲染
            X.daterender(".tab-right-box .time",function(start, end, label) {
                var startTime = start.format('YYYY-MM-DD')+ " "+ "00:00:00";
                var endTime = end.format('YYYY-MM-DD')+ " "+ "23:59:59";
                // console.log(startTime);
                // console.log(endTime);
            });

            // X.echartsdata("#charts");

            //更新时间按钮
            $(".updatetime").click(function(){
                X.updatatime(".updatetime");
                me.gettabledata();
            });

            //管理我创建的看板
            $(document).off('click','.sousuo-box .kbglkanbanbtn').on("click",".sousuo-box .kbglkanbanbtn",function(){
                X.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    shadeClose: true,
                    offset: 'lt',
                    anim: 5,
                    skin: 'yourclass',
                    url: 'adminkanban'
                })
            });

            //渲染时区下拉框
            layui.dropdown.render({
                elem: ".tab-tit-box .tab-shiqvshezhi"
                ,data: X.DATA.timezone
                ,click: function(obj){
                    $(".tab-tit-box .tab-shiqvshezhi").html(obj.title);

                    //数据更新
                //   this.elem.val(obj.title);
                }
            });

            //筛选
            $(document).off('click','.tab-right-box .tjsx').on("click",".tab-right-box .tjsx",function(){
                // layer.msg('该功能暂未开放');
                // return;
                X.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    shade:0,
                    shadeClose: false,
                    offset: [120,270],
                    url: "screen",
                    extData : {}
                })
            })

            // 侧边栏搜索
            $('.sousuo-txt').bind('input propertychange', function() {
                var tit = $(this).val()
                var KanBanData = X.DATA['KanBanData'];
                var ProjectData = X.DATA['ProjectData'];
                if(tit != ''){
                    var ssKanBanData = [],
                        ssProjectData = []
                    for(let i in KanBanData){
                        if(KanBanData[i]['title'].indexOf(tit) != -1){
                            ssKanBanData.push(KanBanData[i]);
                        }else {
                            for(let j in KanBanData[i]['children']){
                                if(KanBanData[i]['children'][j]['title'].indexOf(tit) != -1 ){
                                    var arr = KanBanData[i];
                                    arr['children'].push(KanBanData[i]['children'][j]);
                                    ssKanBanData.push(arr);
                                }
                            }
                        }
                    }
                    for(let i in ProjectData){
                        for(let i in ProjectData){
                            if(ProjectData[i]['children'].length > 0){
                                if(ProjectData[i]['title'].indexOf(tit) != -1){
                                    ssProjectData.push(ProjectData[i]);
                                }else {
                                    var towProjectData = ProjectData[i]['children'];
                                    for(let j in towProjectData){
                                        if(towProjectData[j]['children'].length > 0){
                                            if(towProjectData[j]['children'].length > 0){
                                                var threProjectData = ProjectData[i]['children'][j]['children'];
                                                for(let z in threProjectData){
                                                    if(threProjectData[z]['title'].indexOf(tit) != -1){
                                                        var arr = ProjectData[i];
                                                        arr['children'] = towProjectData[j];
                                                        arr['children']['children'] = threProjectData[z];
                                                        // arr['children'].push( threProjectData[z] )
                                                        ssProjectData.push(arr);
                                                    }
                                                }
                                            }
                                        }else {
                                            if(towProjectData[j]['title'].indexOf(tit) != -1 ){
                                                var arr = ProjectData[i];
                                                arr['children'].push(towProjectData[j]);
                                                ssProjectData.push(arr);
                                            }
                                        }
    
                                    }
                                }
                            }else {
                                if(ProjectData[i]['title'].indexOf(tit) != -1){
                                    ssProjectData.push(ProjectData[i]);
                                }
                            }
                            
                        }
                    }
                    X.laytpldata('#mykanban-dot',ssKanBanData,'#mykanban');
                    X.laytpldata('#kongjian-dot',ssProjectData,'#kongjian');

                }else {
                    me.freshMenu(X.DATA['projectid']);
                }

            });
    
            // 用户搜索
            $("#search").click(function(){
                layer.msg('该功能暂未开放');
                return;
                X.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    shadeClose: true,
                    skin: 'yourclass',
                    url: 'search'
                  })
            });
            
            $(document).off('click','.tab-right-box .shezhi').on("click",".tab-right-box .shezhi",function(){
                layer.msg('该功能暂未开放');
                return;
                X.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    shadeClose: true,
                    offset: 'rt',
                    anim: 5,
                    skin: 'yourclass',
                    url: 'kanbanshezhi'
                })
            });
            // 保存报表列表
            $(document).off('click','.baobiao').on('click','.baobiao',function(){
                X.parametersopen({},'kanbanadmin','rt',function(){
                    me.gettabledata();
                })
            });

            //更新报表
            $(document).off('click','.model-gengx').on('click','.model-gengx',function(){
                var id = $(this).attr('data-id');
                // console.log(id);
                X.api('dashboard/','post',{id:X.DATA['dashboard_id']},function(d){
                    return;
                    X.pageLogic['dashboard'].fillmodeldata(d[id]);
    
                })

            });

            //报表跳转到详情s
            $(document).off('click','.gobaobiaoinfo').on('click','.gobaobiaoinfo',function(){
                var cat = $(this).attr('data-cat');
                var id = $(this).attr('data-id');
                var gourl='';
                if(cat == 'event'){
                    gourl = 'analysis';
                }else if(cat == 'retention'){
                    gourl = 'retained';
                    // layer.msg('暂未处理当前逻辑');
                    // return;
                }else if(cat == 'ltv'){
                    gourl = 'ltvmodel';
                    // layer.msg('暂未处理当前逻辑');
                    // return;
                }
                X.gourl(gourl,'conetnt');//跳到对应的分析页面
                X.DATA[cat+'id'] = id;
            });

            //复制单个报表
            $(document).off('click','.model-fuzhi').on('click','.model-fuzhi',function(e) {
                e.stopPropagation();
                var id = $(this).attr('data-id')
                X.parametersopen(id,'copyreport',"auto",function(d) {
                    
                })
            });

            //删除空间
            $(document).off('click','.nav-space-bar').on('click','.nav-space-bar',function(e){
                e.stopPropagation();
                var id = $(this).attr('data-id');
                X.parametersopen(id,"kongjianshezhi",'auto',function(d){

                })
            })

            //删除看板
            $(document).off('click','.nav-action-bar').on('click','.nav-action-bar',function(e){
                e.stopPropagation();
                // console.log('更多操作按钮');
                var obj = $(this);
                var offset = obj.offset();
                var offsets = [ offset.top + 10,offset.left];
                var id = $(this).attr('data-id');
                X.parametersopen(X.DATA.taboperationdata['kanban'],"dropdownlist",offsets,function(d){
                    var arr = [];
                        arr.push(id);
                    if(d.click != 'del'){
                        X.parametersopen(arr,d.click,'auto',function(){
                            // me.updata(X.DATA['projectid']);
                            me.freshMenu();
                        })
                    }else {
                        layer.confirm('确认删除选中的看板吗？该操作不可恢复', {
                            btn: ['取消','删除 '] //按钮
                          }, function(){
                            //取消
                            layer.close(layer.index);
                          }, function(){
                            //删除
                            X.api("dashboard/delete",'post',{ids:arr},function(d){
                                layer.msg('删除成功');
                                layer.close(layer.index);
                                X.pageLogic.dashboard.freshMenu(X.DATA.projectid);//刷新侧边栏
                                me.updata(X.DATA.projectid);//刷新数据
                            })
                        });
                    }
                   
                });
            });
            
        },

        // X.pageLogic.dashboard.freshMenu();
        freshMenu : function(id){
            //获取对应侧边栏
            X.api('project/kanban',"post",{"_id":id},function (d){
                X.DATA['KanBanData'] = d.kanban;
                X.DATA['ProjectData'] = d.spaces;
                X.laytpldata('#mykanban-dot',d.kanban,'#mykanban');
                X.laytpldata('#kongjian-dot',d.spaces,'#kongjian');
            });
        },

        //填充看板数据
        fillmodeldata:function(d,id){
            // console.log(d);
            X.api("ck/"+d['model']+"_model","post",{report_id:d['report_id']},function(val){
                var eventdata=[];
                var data;
                if(d['model'] == "event"){
                    // 事件分析
                    if(d['graph_size'] == 'small'){
                        X.eventsmall(val,function(data){//表格数据处理
                            data['name'] = d['name'];
                            data['modeltype'] = d['graph_type'];
                            data['id'] = d['report_id'];
                            data['modelsize'] = d['graph_size'];
                            data['cat'] = d['model'];
                            eventdata.push(data);
                        })
                    }else {
                        if(d['graph_type'] == 'table'){
                            //表格样式
                            X.eventtable(val,function(data){//表格数据处理
                                data['name'] = d['name'];
                                data['modeltype'] = d['graph_type'];
                                data['id'] = d['report_id'];
                                data['modelsize'] = d['graph_size'];
                                data['cat'] = d['model'];
                                eventdata.push(data);
                            })
                        }else if(d['graph_type'] == 'echarts'){
                            //图形
                            X.eventchart(val,function(data){
                                data['name'] = d['name'];
                                data['modeltype'] = d['graph_type'];
                                data['id'] = d['report_id'];
                                data['modelsize'] = d['graph_size'];
                                data['cat'] = d['model'];
                                eventdata.push(data);
                            })
                        }
                    }

                } else if(d['model'] == "retention"){
                    //留存分析
                    if(d['graph_size'] == 'small'){

                    }else {
                        if(d['graph_type'] == 'table'){
                            X.retentiontable(val,function(data){
                                data['name'] = d['name'];
                                data['modeltype'] = d['graph_type'];
                                data['id'] = d['report_id'];
                                data['modelsize'] = d['graph_size'];
                                data['cat'] = d['model'];
                                eventdata.push(data);
                            })

                        }else {
                            X.retentionchart(val,function(data){
                                data['name'] = d['name'];
                                data['modeltype'] = d['graph_type'];
                                data['id'] = d['report_id'];
                                data['modelsize'] = d['graph_size'];
                                data['cat'] = d['model'];
                                eventdata.push(data);
                            })
                        }
                    }
                }else if(d['model'] == 'ltv'){
                    //ltv模型
                    if(d['graph_type'] == 'table'){
                        X.ltvtable(val,function(data){
                            data['name'] = d['name'];
                            data['modeltype'] = d['graph_type'];
                            data['id'] = d['report_id'];
                            data['modelsize'] = d['graph_size'];
                            data['cat'] = d['model'];
                            eventdata.push(data);
                        })
                    }else {
                        X.ltvtable(val,function(data){
                            data['name'] = d['name'];
                            data['modeltype'] = d['graph_type'];
                            data['id'] = d['report_id'];
                            data['modelsize'] = d['graph_size'];
                            data['cat'] = d['model'];
                            eventdata.push(data);
                        })
                    }
                }else if(d['model'] == 'user_property'){
                    // 属性分析
                    if(d['graph_type'] == 'table'){
                        X.userpropertytable(val,function(data){
                            data['name'] = d['name'];
                            data['modeltype'] = d['graph_type'];
                            data['id'] = d['report_id'];
                            data['modelsize'] = d['graph_size'];
                            data['cat'] = d['model'];
                            eventdata.push(data);
                        })
                    }else {
                        X.userpropertychart(val,function(data){
                            data['name'] = d['name'];
                            data['modeltype'] = d['graph_type'];
                            data['id'] = d['report_id'];
                            data['modelsize'] = d['graph_size'];
                            data['cat'] = d['model'];
                            eventdata.push(data);
                        })
                    }
                    
                    
                }
                if(eventdata.length > 0){
                    for(var z in eventdata){
                        if(id){
                            //当有id时更新对应id看板内的内容
                            X.template("modeltable",id,eventdata[z],function(){ 
                                X.pageLogic['dashboard'].morefeatures(eventdata[z]);
                            });
                        }else {
                            //渲染模板和数据
                            X.template("modeltable",'model'+eventdata[z]['id'],eventdata[z],function(){
                                X.pageLogic['dashboard'].morefeatures(eventdata[z]);
                            });
                        }
                    }
                }

                // $('.layui-row').dad({
                //     draggable: '.layui-card'
                // });
                // $('.layui-row').dad({
                //     draggable:'table'
                // });
            })
        },

        //画统计图和添加移入移出事件
        morefeatures:function(eventdata){

            var dropdownlist = [
                {title:'表格',id:'table'},
                {title:'图形',id:'echarts'}
            ];
            X.laydropdown("#chart"+eventdata.id,dropdownlist,function(d){
                var id = $("#chart"+eventdata.id).attr('data-id');
                var modelid = 'model'+id;
                var modelsize = $("#chart"+eventdata.id).attr('data-modelsize');
                var modeltype = $("#chart"+eventdata.id).attr('data-modeltype');
                var cat = $("#chart"+eventdata.id).attr('data-cat');
                var name = $("#chart"+eventdata.id).attr('data-name');
                var data = {
                    report_id:id,
                    graph_size:modelsize,
                    graph_type:d.id,
                    model:cat,
                    name:name
                }
                X.api('dashboard/edit_show_report','post',{dashboard_id:X.DATA.dashboard_id,config:data},function(d){
                    // console.log(d);
                    X.api('dashboard/','post',{id:X.DATA['dashboard_id']},function(val){
                        for(let i in val){
                            if(val[i]['report_id'] == id){
                                X.pageLogic['dashboard'].fillmodeldata(val[i],modelid);
                            }
                        }
                    })
                })
                
            });

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

         // 获取表格数据
        gettabledata:function(){
            $("#model-box").html("");//清空表格数据
            X.api('dashboard/','post',{id:X.DATA['dashboard_id']},function(d){
                var modellist=[];
                for(let i in d){
                    var arr = {
                        sort:d[i]['sort'],
                        report_id:d[i]['report_id']
                    }
                    modellist.push(arr);
                }

                modellist.sort( X.compare("sort") );
                for(let i in modellist){
                    for(let z in d){
                        if(modellist[i]['sort'] == d[z]['sort'] && modellist[i]['report_id'] == d[z]['report_id']){
                            //渲染模板和数据
                            X.laytpldata("#kanban-model-box-dot",d[z],null,function(html){
                                $('#model-box').append(html);
                                X.pageLogic['dashboard'].fillmodeldata(d[z]);
                            });
                        }
                    }
                }
           
            })
        },

    }; 
})();
