//基础通用方法
var X = window.X || {
    event : new EventEmitter(),
    pageLogic : {},
    DATA : {
        'echartscolor': [ '#3ea7fd', '#cdddfd', '#5ad8a6', '#cdf3e4', '#5d7092', '#ced4de', '#f6bd16','#fcebb9','#e86452','#f8d0cb','#6dc8ec', '#d3eef9', '#9270ca', '#d3c6ea', '#ff9d4d', '#ffd8b8', '#269a99','#aad8d8','#ff99c3','#ffd6e7' ],
        'createsidebar':[
            { title: '新建看板',id: 0,url:'newkanban'},
            // {title: '新建文件夹',id: 1,url:'newwenjian'},
            {title: '创建空间',id: 2,url:'kongjianshezhi'}
        ],
        'taboperationdata':{
            kanban:[
                {'title':'重命名','img':'xiugai.png','click':'modifyname'},
                {'title':'移动至','img':'yidong.png','click':'yidong-pop'},
                // {'title':'复制看板','img':'fuzhi.png','click':'copykanban'},
                {'title':'删除看板','img':'del.png','click':'del'},
            ],
            wenjian:[
                {'title':'重新命名','img':'xiugai.png','click':'modifyname'},
                {'title':'删除文件夹','img':'del.png','click':'del'},
            ],
            baobiao:[
                {'title':'复制看板','img':'fuzhi.png','click':'copy'}
            ]
        },
        'gengduolist':[
            {'title':'报表设置','id':'shezhi'},
            {'title':'数据导出','id':'export'},
            {'title':'报表移除','id':'del'},
        ],
        'gengduolist2':[
            {'title':'数据导出','id':'export'},
        ],
        //用户搜索条件
        'search':{
            category:[
 
            ],
            condition:[
                {'title':'等于','id':'0','default':false},
                {'title':'不等于','id':'1','default':false},
                {'title':'包括','id':'2','default':true},
                {'title':'不包括','id':'3','default':false},
                {'title':'有值','id':'4','default':false},
                {'title':'无值','id':'5','default':false},
                {'title':'正则匹配','id':'6','default':false},
                {'title':'正则不匹配','id':'7','default':false},
            ],
            condition2:[
                {'title':'等于','id':'0','default':false},
                {'title':'不等于','id':'1','default':false},
                {'title':'小于','id':'2','default':true},
                {'title':'大于','id':'3','default':false},
                {'title':'有值','id':'4','default':false},
                {'title':'无值','id':'5','default':false},
                {'title':'区间','id':'6','default':false}
            ],
            condition2:[
                {'title':'等于','id':'=='},
                {'title':'不等于','id':'!='},
                {'title':'小于','id':'<'},
                {'title':'大于','id':'>'},
                {'title':'小于等于','id':'<='},
                {'title':'大于等于','id':'>='},
                {'title':'区间','id':'range'}
            ],
        },
        //日期控件参数
        'locale': {
            "format": 'YYYY-MM-DD',
            "separator": " - ",
            "applyLabel": "应用",
            "cancelLabel": "取消",
            "fromLabel": "起始时间",
            "toLabel": "结束时间'",
            "customRangeLabel": "自定义",
            "weekLabel": "W",
            "daysOfWeek": ["日", "一", "二", "三", "四", "五", "六"],
            "monthNames": ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            "firstDay": 1
        },
        'timezone':[
            {'title': "UTC+08:00 默认",id:8},
            {'title': "当前时区",id:8},
            {'title': "UTC-12:00",id:12},
            {'title': "UTC-11:00",id:11},
            {'title': "UTC-10:00",id:10},
            {'title': "UTC-09:00",id:9},
            {'title': "UTC-08:00",id:8},
            {'title': "UTC-07:00",id:7},
            {'title': "UTC±00:00",id:0}
        ],
        'analysis':{},
        'companylist':{
            'event':[
                {'title':'按天','id':'P1D'},
                {'title':'按分钟','id':'PT1M'},
                {'title':'每五分钟','id':'PT5M'},
                {'title':'每十分钟','id':'PT10M'},
                {'title':'每十五分钟','id':'PT15M'},
                {'title':'按小时','id':'PT1H'},
                // {'title':'按小时段','id':'HOUR'},
                {'title':'按周','id':'P1W'},
                {'title':'按月','id':'P1M'},
                {'title':'合计','id':'total'},
            ],
            'retention':[
                {'title':'当日','id':1},
                {'title':'次日','id':2},
                {'title':'7日','id':7},
                {'title':'14日','id':14},
                {'title':'30日','id':30}
            ],
            'distribution':[
                {'title':'按天','id':'P1D'},
                {'title':'按周','id':'P1W'},
                {'title':'按月','id':'P1M'},
                {'title':'合计','id':'total'}
            ]
        },
        'retentionlist' : [
            {'title':'留存','id':0},
            {'title':'流失','id':1},
        ],
        'screenlist':[],
        "operatorarr": [
            {title: '无',id:""},
            {title: '+',id:'+'},
            {title: '-',id:'-'}, 
            {title: '*',id:'*'},
            {title: '/',id:'/'},
        ]
    },
};
  

(function(){
    //本地李伟
    //  var ipurl = "http://10.0.0.240:7899/api/v1/";
     //本地李宗振
    //  var ipurl = "http://10.0.0.94:7899/api/v1/";
    // 线上  
    var ipurl = "http://139.159.159.3:9865/api/v1/";
    //线上测试
    // var ipurl = "http://139.159.159.3:7889/api/v1/";

    //设置或读取登录缓存，需要保存到localStorage，防止刷新时候登录数据丢失
    X.loginCache = function(data){
        if(data == null){
            var _cache = localStorage.loginData;
            if(_cache){
                return JSON.parse(_cache);
            }else{
                return null;
            }
        }else{
            localStorage.loginData = JSON.stringify(data);
        }
    };

    //统一API接口调用
    X.api = function(url,type,parms,callback){
        var loginCache = X.loginCache();
        var token = (loginCache? loginCache.token:"");
        token = "Bearer "+token;
        var contentType;
        if(url.indexOf("login") != -1){
            var data = parms;
            var url = ipurl+url;
        }else {
            var data = {};
            contentType = 'application/json';
            if(parms != 1){
                var data = JSON.stringify(parms);
            }
            if(url == 'data_mana/list'){
                var url = ipurl+url+"?game="+ X.DATA.game+"&"+parms || "";
            }else {
                var url = ipurl+url+"?game="+ X.DATA.game || "";
            }
        }
        var index;
        $.ajax({
            headers: {
                Authorization:token//此处放置请求到的用户token
            },
            url: url,
            type:type,
            data:data,
            async:true,
            contentType: contentType,
            beforeSend: function () {
                // loading 显示
                index = layer.load(1);
            },
            success:function(d){
                layer.close(index);
                if(d.code == 0){
                    if( JSON.stringify(d.data) != "{}" && JSON.stringify(d.data) != "[]" && d.data != null && d.data != ""){
                        callback && callback(d.data);
                    }else {
                        layer.msg('查无数据');
                        callback && callback(d.data);
                    }
                }else {
                    if(d.code == -5){
                        layer.msg("登录过期请重新登录!!!");
                        window.localStorage.removeItem('loginData');
                        X.gourl("login");
                        location.reload();
                    }else if(d.code == -9){
                        layer.msg(d.msg);
                    }else {
                        layer.msg(d.msg);
                    }
                }
                
            },
            error:function(error){
               layer.msg('数据正在加载中...');
               layer.close(index);
         }
        });
    };
    // 看板单独调用api方法，去除loading效果
    X.modelapi = function(url,type,parms,callback){
        var loginCache = X.loginCache();
        var token = (loginCache? loginCache.token:"");
        token = "Bearer "+token;
        var contentType;
        if(url.indexOf("login") != -1){
            var data = parms;
            var url = ipurl+url;
        }else {
            var data = {};
            contentType = 'application/json';
            if(parms != 1){
                var data = JSON.stringify(parms);
            }
            if(url == 'data_mana/list'){
                var url = ipurl+url+"?game="+ X.DATA.game+"&"+parms || "";
            }else {
                var url = ipurl+url+"?game="+ X.DATA.game || "";
            }
        }
        $.ajax({
            headers: {
                Authorization:token//此处放置请求到的用户token
            },
            url: url,
            type:type,
            data:data,
            async:true,
            contentType: contentType,
            beforeSend: function () { 

            },
            success:function(d){
                if(d.code == 0){
                    if( JSON.stringify(d.data) != "{}" && JSON.stringify(d.data) != "[]"){
                        callback && callback(d.data);
                    }else {
                        // layer.msg('查无数据');
                        callback && callback(d.data);
                    }
                }else {
                    if(d.code == -5){
                        layer.msg("登录过期请重新登录!!!");
                        window.localStorage.removeItem('loginData');
                        X.gourl("login");
                        location.reload();
                    }else if(d.code == -9){
                        callback && callback(d.msg);
                    }else {
                        layer.msg(d.msg);
                    }
                }
                
            },
            error:function(error){
               layer.msg('数据正在加载中...');
         }
        });
    };

    //获取当前页面名
    X.pagename = function(callback){
        var search = window.location.href;
        var searcharr = search.split('=');
        var pagearr = searcharr[1].split("&");
        callback && callback(pagearr[0]);
    };

    //提交修改记录
    X.submitrecord = function(content){
        var game = X.game;//项目名
        var name = X.userinfo.name;//账号名
        var date = new Date();
        var y = date.getFullYear();
        var m = date.getMonth()+1;
        var d = date.getDate();
        var h = date.getHours();
        var min = date.getMinutes();
        var s = date.getSeconds();
        var time = y+'年'+(m<10?('0'+m):m)+'月'+(d<10?('0'+d):d)+'日  '+(h<10?('0'+h):h)+':'+(min<10?('0'+min):min)+':'+(s<10?('0'+s):s);//操作时间

        console.log(name+'在'+time+'修改'+content);
        // X.api(function(){
            
        // })
    };

    X.uploadfile=function(url,id,callback){
        var loginCache = X.loginCache();
        var token = (loginCache? loginCache.token:"");
        token = "Bearer "+token;
        layui.upload.render({
            elem: id
            , url: ipurl+url+"?game="+ X.DATA.game || ""
            ,headers: {
                Authorization:token//此处放置请求到的用户token
            }
            , auto: false
            ,accept: 'file' //普通文件
            ,exts: 'xls|xlsx' //只允许上传excel文件
            ,bindAction: '#test9'
            , choose: function (obj) {
            //    console.log(obj);
            }
            , done: function (res) {
               if(res.code == 0 ){
                    layer.msg("提交成功");
                    callback && callback(res);
               }else {
                    layer.msg(res.msg);
               }
            }
        });
    }

    //下载报表
    X.download=function(url, params,name){
        // console.log(url);
        postDownload(url, params,name);
    };

    async function postDownload(url, params,name) {
        var loginCache = X.loginCache();
        var token = (loginCache? loginCache.token:"");
        token = "Bearer "+token;

        var url = ipurl+url+"?game="+ X.DATA.game;
        const request = {
          async: true,
          body: JSON.stringify(params),
          method: 'POST',
          headers: {
              Authorization:token,//此处放置请求到的用户token
              'Content-Type':'application/json',
          },
        }

        const response = await fetch(url, request);
        
        // const filename = response.headers.get('content-disposition').split('=')[1];
        const filename = name+'.xlsx';
        const blob = await response.blob();
     
        const link = document.createElement('a')
        link.download = decodeURIComponent(filename)
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        document.body.appendChild(link)
        link.click()
        URL.revokeObjectURL(link.href)
        document.body.removeChild(link)
    };

    X.template = function(url,id,data,callback){
		$.get('pages/'+ url + '.html',function(content){
			$('#'+id).html(content);
            X.pageLogic[url] && X.pageLogic[url].init && X.pageLogic[url].init(data);
            callback && callback();
            // X.pageLogic[parms.url] && X.pageLogic[parms.url].init && X.pageLogic[parms.url].init( parms );
		});
    };

    //弹窗
    X.open = function(parms){
        if(parms.url){
            var url = 'pages/'+ parms.url + '.html';
            $.get(url,function(html){
                parms.content = html;
                // openindes是弹出层的标记，方便后面多个弹框对应关闭
                parms.success = function(layero, index){
                    parms.layIndex = index;
                    X.pageLogic[parms.url] && X.pageLogic[parms.url].init && X.pageLogic[parms.url].init( parms );
                };
                layer.open(parms);
            })
        }else{
            layer.open(parms);
        }
    };

    //渲染表格无分页无操作
    X.tabledata = function(id,url,data){
        var loginCache = X.loginCache();
        var token = (loginCache? loginCache.token:"");
        token = "Bearer "+token;
            layui.table.render({
                headers: {
                    Authorization: token
                 }
                ,elem: id
                ,url: ipurl+url+"?game="+X.DATA.game
                ,cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                ,cols: data
            });
    };

    //渲染表格有分页有操作
    X.laytabledata = function(id,url,data,arr,height,callback,method){
        var loginCache = X.loginCache();
        var token = (loginCache? loginCache.token:"");
        token = "Bearer "+token;
        var url
        if(arr){
            url = ipurl+url+"?game="+X.DATA.game+arr;
        }else {
            url = ipurl+url+"?game="+X.DATA.game;
        }
        if(!height){
            var height = 'full-20'
        }
        method = method ? method : "get";
        // if(method){
        //     method = method;
        // }else{
        //     method = 'get';
        // }
        layui.table.render({
            method: method,
            headers: {
                Authorization: token
                }
            ,elem: id
            ,url: url
            ,cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            ,cols: data
            ,height: height
            ,done: function (res, curr, count) {
                callback && callback(res, curr, count);
            }
        });
    };

    //渲染模板,模板id，数据，位置id
    X.laytpldata = function (mbid ,data,wzid,callback){
        var getTpl = $(mbid).html()
        layui.laytpl(getTpl).render(data, function(html){
            wzid && $(wzid).html(html);
            layui.element.init(); //重新渲染
            callback && callback(html);
        });
    };

    //渲染下拉框
    X.laydropdown = function(id,data,callback){
        layui.dropdown.render({
            elem: id
            ,data: data
            ,click: callback
        });
    };
    
    //查询条件弹框  id:位置，data:数据，deviationleft:左偏移量，deviationtop：上偏移量
    X.querycriteriapop = function(data,url,deviationleft, deviationtop, callback){
        var innerHeight = window.innerHeight;
        if(innerHeight - deviationtop < 420){
            deviationtop = deviationtop - 450
        }
        X.open({
            type: 1,
            title: false,
            closeBtn: 0,
            // shade:,
            shadeClose: true,
            offset: [deviationtop,deviationleft],
            url: url,
            extData : data,
            callback : callback
        });
    };

    X.parametersopen = function(data,url,offset,callback){
        // var innerHeight = window.innerHeight;
        // if( innerHeight - offset[0] < height){
        //     offset[0] = offset[0] - (height + 30);
        // }
        // console.log(offset);
        X.open({
            type: 1,
            title: false,
            closeBtn: 0,
            shadeClose: true,
            skin: 'yourclass',
            offset:offset,
            url: url,
            extData : data,
            callback : callback
        });
    };

    // 渲染树形菜单
    X.treemenu = function(elem,data,id){
        layui.tree.render({
            elem: elem
            ,data: data
            ,showCheckbox: true  //是否显示复选框
            ,id: id
            ,isJump: false //是否允许点击节点时弹出新窗口跳转
            
        });
    };

    //渲染穿梭框
    X.laytransfer = function(elem,data,title,id){
        layui.transfer.render({
            elem: elem
            ,data: data
            ,title: title
            ,showSearch: true
            ,id: id
        })
    };

    //获取时间粒度中文名
    X.granularity=function(timeParticleSize,callback){
        if(timeParticleSize == 'P1D'){
            granularity = '按天'
        }else if(timeParticleSize == 'PT1M'){
            granularity = '按分钟'
        }else if(timeParticleSize == 'PT5M'){
            granularity = '每五分钟'
        }else if(timeParticleSize == 'PT10M'){
            granularity = '每十分钟'
        }else if(timeParticleSize == 'PT15M'){
            granularity = '每十五分钟'
        }else if(timeParticleSize == 'PT1H'){
            granularity = '按小时'
        }else if(timeParticleSize == 'P1W'){
            granularity = '按周'
        }else if(timeParticleSize == 'P1M'){
            granularity = '按月'
        }else if(timeParticleSize == 'total'){
            granularity = '合计'
        }else if(timeParticleSize == '1'){
            granularity = '当日'
        }else if(timeParticleSize == '2'){
            granularity = '次日'
        }else if(timeParticleSize == '7'){
            granularity = '7日'
        }else if(timeParticleSize == '14'){
            granularity = '14日'
        }else if(timeParticleSize == '30'){
            granularity = '30日'
        }
        callback && callback(granularity);
    };

    //根据中文名获取时间粒度id
    X.granularityid=function(timeParticleSize,callback){
        if(timeParticleSize == '按天'){
            granularity = 'P1D'
        }else if(timeParticleSize == '按分钟'){
            granularity = 'PT1M'
        }else if(timeParticleSize == '每五分钟'){
            granularity = 'PT5M'
        }else if(timeParticleSize == '每十分钟'){
            granularity = 'PT10M'
        }else if(timeParticleSize == '每十五分钟'){
            granularity = 'PT15M'
        }else if(timeParticleSize == '按小时'){
            granularity = 'PT1H'
        }else if(timeParticleSize == '按周'){
            granularity = 'P1W'
        }else if(timeParticleSize == '按月'){
            granularity = 'P1M'
        }else if(timeParticleSize == '合计'){
            granularity = 'total'
        }else if(timeParticleSize == '当日'){
            granularity = '1'
        }else if(timeParticleSize == '次日'){
            granularity = '2'
        }else if(timeParticleSize == '7日'){
            granularity = '7'
        }else if(timeParticleSize == '14日'){
            granularity = '14'
        }else if(timeParticleSize == '30日'){
            granularity = '30'
        }
        callback && callback(granularity);
    };


    // 分组项取交集
    X.groupintersection=function(c , a , callback){
        var dataArr=[];
        var arr=[];
        for(let i in c){
            
                for(let j in a){

                    if(c[i]['id'] == a[j]['id']){

                        for(let z in c[i]['category']){

                            for(let q in a[j]['category']){

                                if(c[i]['category'][z]['title'] == a[j]['category'][q]['title']){
                                    arr.push(c[i]['category'][z]);
                                }

                            }

                        }

                        if(arr.length > 0){
                            var data = {
                                title: c[i]['title'],
                                id:c[i]['id'],
                                category:arr
                            };
                            dataArr.push(data);
                        }

                    }
                    
                }
                
        }
        callback && callback(dataArr);
    };

    //分页
    X.layuipages = function(id,count,callback){//绑定id，数据总数
        layui.laypage.render({
            elem: id
            ,count: count //数据总数
            ,limit: 18 //每页显示数
            ,jump:callback
        });
    };

    // 日期选择器
    X.daterender = function(id,callback){
        // console.log(moment().subtract(1, 'week').startOf('week'))
        $(id).daterangepicker({
            'locale': X.DATA.locale,
            ranges: {
                '今日': [moment(), moment()],
                '昨日': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                '最近7日': [moment().subtract(7, 'days'), moment().subtract(0, 'days')],
                '最近30日': [moment().subtract(30, 'days'), moment().subtract(0, 'days')],
                '上周': [moment().subtract(1, 'week').startOf('week')+86400000, moment().subtract(1, 'week').endOf('week')+86400000],
                '本周': [moment().startOf('week')+86400000, moment()+86400000],
                '本月': [moment().startOf('month'), moment()],
                '上月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                '全部时间': [moment().subtract( parseInt((new Date).getTime()/86400000) , 'days'), moment()]
            },
            "alwaysShowCalendars": true,
            "startDate": moment().subtract(6, 'days'),
            "endDate": new Date(),
            "opens": "right",
           
        }, function (start, end, label) {
            callback && callback(start,end,label);
            // console.log(start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD')) ;
        });
    };

    X.updatatime = function(id){
        var myDate = new Date;
        var year = myDate.getFullYear(); //获取当前年
        var mon = myDate.getMonth() + 1; //获取当前月
        var date = myDate.getDate(); //获取当前日
        var h = myDate.getHours();//获取当前小时数(0-23)
        var m = myDate.getMinutes();//获取当前分钟数(0-59)
        var s = myDate.getSeconds();//获取当前秒
        var week = myDate.getDay();
        var weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
        var time = year + "-" + mon + "-" + date + " " + h+":"+m+":"+s
        // console.log(year + "-" + mon + "-" + date + " " + h+":"+m+":"+s);
        $(id).attr('title',"最新更新时间："+time);
    };

    //多选下拉框
    // X.select = function(){
        
    // };

    //多选标签-基本配置
    X.selectM = function(id,data,width,callback){
        layui.selectM({
            //元素容器【必填】
            elem: id
            //候选数据【必填】
            ,data: data
            ,width: width
            ,max: 100
            //添加验证
            ,verify:'required',
            callback:callback
        }); 
    };

    X.layuidate=function(id){
        layui.laydate.render({
            elem: id
            ,type: 'datetime'
            ,range: true
          });
    };

    //定义一个比较器--升序排列
    X.compare=function(propertyName) {
        return function(object1, object2) {
            var value1 = object1[propertyName];
            var value2 = object2[propertyName];
            if(value2 < value1) {
                return 1;
            } else if(value2 > value1) {
                return -1;
            } else {
                return 0;
            }
        }
    };

    // table
    X.fixedTable=function(id,type,classname,headdata,dataarr,cat){
        var fixedTable =  new FixedTable({
            wrap: document.getElementById(id),//生成的表格需要放到哪里
            type: type,//表格类型，有：head-fixed、col-fixed、row-col-fixed
            extraClass: classname,//需要添加到表格中的额外class
            maxHeight: true,
            fields: headdata,
            // [//表格的列
            //     {
            //         width: "150px",
            //         field: "日期",
            //         fixed: true
            //     },
            //     {
            //         width: "120px",
            //         field: "姓名",
            //         fixed: true
            //     },
            //     {
            //         width: "120px",
            //         field: "省份",
            //         //fixed: true,

            //     },
            //     {
            //         width: "120px",
            //         field: "市区"
            //     },
            //     {
            //         width: "300px",
            //         field: "地址",
            //        // fixed: true,

            //     },
            //     {
            //         width: "120px",
            //         field: "邮编",
                    
            //     },
            //     {
            //         width: "100px",
            //         field: "操作",
            //         fixed: true,
            //         fixedDirection: "right"
            //     }
            // ],
            tableDefaultContent: "<div>我是一个默认的div</div>"
        });

        fixedTable.addRow(function (){
            var html = '';
            if(cat == 'event' || cat == "ltv"){
                for(let i in dataarr){
                    html += '<tr>';
                    for(let j in dataarr[i]){
                        html += '<td class="ws-150"><div class="table-cell">'+ dataarr[i][j] +'</div></td>';
                    }
                    html += '</tr>';
                }
            }else if(cat == "retention" || cat == "scatter"){

                for(let i in dataarr){
                    html += '<tr>';
                        html += '<td class="ws-150"><div class="table-cell">'+ dataarr[i]['date'] +'</div></td>';
                        html += '<td class="ws-150"><div class="table-cell">'+ dataarr[i]['d0'] +'</div></td>';
                    for(let j in dataarr[i]['data']){
                        // for(let z in dataarr[i]['data'][j]){
                            html += '<td class="ws-150"><div class="table-cell">'+ dataarr[i]['data'][j]['n'] +'</div><div class="table-cell">'+ dataarr[i]['data'][j]['p'] +'</div></td>';
                        // }
                    }
                    html += '</tr>';
                }

            }else if(cat == "user_property"){
                for(let i in dataarr){
                    html += '<tr>';
                    html += '<td class="ws-150"><div class="table-cell">'+ i +'</div></td>';
                    html += '<td class="ws-150"><div class="table-cell">'+ dataarr[i] +'</div></td>';
                    html += '</tr>';
                }
            }
            
            return html;
        });
    };

    X.eventtable=function(data,callback){
        var titledata,date,condata = [];
        for(let i in data){
            if(data[i]['values'].length > 0 ){
                titledata= $.extend(true,[],data[0]['date_range']);
                
                // ,'阶段总和'
                if(data[i]['groups']['length'] != 0){
                    titledata.unshift('指标','分组');
                    for(let j in data[i]['values']){
                        var arr;
                        arr = $.extend(true,[],data[i].values[j])
                        arr.unshift(data[i]['event_name'],data[i]['groups'][j]);
                        // ,data[i]['sum'][j]
                        condata.push(arr);
                    }
                    // for(let j in condata){
                    //     condata[j].splice(1,0,data[i]['groups'][j]);
                    // }

                }else {
                    titledata.unshift('指标');
                    var arr;
                    arr = $.extend(true,[],data[i].values[0])
                    arr.unshift(data[i]['event_name']);
                    // ,data[i]['sum'][0]
                    condata.push(arr)
                }    
            }else {
                layer.msg('查询数据为空');
            }
        }
        date = data[0]['start_date'] + " - " + data[0]['end_date'];

        var dataArr = {
            titledata:titledata,
            condata:condata,
            date:date
        }
        callback && callback(dataArr);
    };

    X.eventchart = function(data,callback){
        var legenddata=[];
        var legendnamearr = [];
        for(let i in data){
            legendnamearr.push(data[i]['event_name'])
            if(data[i]['groups'].length > 0){
                for(let z in data[i]['groups']){
                    var pj =  data[i]['event_name']+data[i]['groups'][z];
                    legenddata.push(pj);
                }
            }else {
                var pj =  data[i]['event_name'];
                legenddata.push(pj);
            }
        }
        var seriesData=[];
        var sum = -1;
        var mean = -1;
        var sameday = 0;
        var date;
        var wowtype='',chain_ratiotype='';//判断较环比和较同比的正负
        var selected = {};//线多的话默认显示5条

        date = data[0]['start_date'] + " - " + data[0]['end_date'];
        // console.log(date);
        for(let i in data){
            for(let z in data[i]['values']){
                var arr = {
                    name: '',
                    type: 'line',
                    data: data[i]['values'][z]
                }
                seriesData.push(arr);
                sameday = data[0]['last_value'];
                
            }
        }

        //只在单个指标分析中显示总价和均值
        if(data.length == 1){
            sum = data[0]['sum'][0];
            mean = data[0]['avg'][0];
        }

        if(legenddata.length > 0){
            for(let i in seriesData){
                seriesData[i]['name'] = legenddata[i];
            }
        }

        if(legenddata.length > 5){
            for(let i in legenddata){
                if(i < 5){
                    selected[legenddata[i]] = true;
                }else {
                    selected[legenddata[i]] = false;
                }
            }
        }

        if(data[0]['wow']){
            if(data[0]['wow'] >= 0){
                wowtype = '+'
            }else{
                wowtype = '-'
            }
        }
        
        if(data[0]['chain_ratio']){
            if(data[0]['chain_ratio'] >= 0){
                chain_ratiotype = '+'
            }else{
                chain_ratiotype = '-'
            }
        }
        
        var dataArr = {
            xAxisData:data[0]['date_range'],
            legenddata:legenddata,
            seriesData:seriesData,
            legendnamearr:legendnamearr,
            selected:selected,
            date:date,
            sum:sum,
            mean:mean,
            sameday: sameday,
            wowtype:wowtype,
            wow: Math.abs(data[0]['wow']),//同比
            chain_ratio: Math.abs(data[0]['chain_ratio']),//环比
            chain_ratiotype:chain_ratiotype,
            proid_money: data[0]['proid_money'],
            proid_name: data[0]['proid_name']
        }
        console.log(dataArr);
        callback && callback(dataArr);
    };

    X.eventsmall = function(data,callback){
        var date,num,wowtype="",chain_ratiotype=""; //时间，当天数量
        //
        // for(let i in data){
        //     if(data[i]['groups']['length'] == 0){

               
        //     }
        // }
        var length = data[0]['date_range'].length - 1;
        date = data[0]['date_range'][length];
        num = data[0]['values'][0][length];
        if(data[0]['wow']){
            if(data[0]['wow'] >= 0){
                wowtype = '+'
            }else{
                wowtype = '-'
            }
        }

        if(data[0]['chain_ratio']){
            if(data[0]['chain_ratio'] >= 0){
                chain_ratiotype = '+'
            }else{
                chain_ratiotype = '-'
            }
        }
        
        var dataArr = {
            date: date,
            num: num,
            wowtype: wowtype,
            chain_ratiotype: chain_ratiotype
        }
        callback && callback(dataArr);
    };

    X.retentiontable=function(data,callback){
        var nname,pname
        if(data.retentiontype == 0) {
            nname = 'n';
            pname = 'p';
        }else {
            nname = 'n_outflow';
            pname = 'p_outflow';
        }

        // if(data['filter_item_type'] != "all"  && data['filter_item_type'] != "" && data['filter_item_type']){
        //     var filteritem = data['filter_item'];
        //     if(data['days'].length >= 0){
        //         var filterarr = [];
        //         for(let i in data['days']){
        //             for(let j in filteritem){
        //                 if(data['days'][i] == filteritem[j]){
        //                     filterarr.push(i);
        //                 }
        //             }
        //         }
        //     }
        // }

        var tabledata=[];
        for(let i in data['summary_values']){
            var arr = {
                date: i,
                d0:data['summary_values'][i]['d0'],
                data:[]
            }
            for(let j in data['summary_values'][i][nname]){
                var nrr = {
                    n:0,
                    p:0
                }
                // if(data['filter_item_type'] != "all"  && data['filter_item_type'] != "" && data['filter_item_type']){
                //     for(let a in filterarr){
                //         var index = Number(filterarr[a]);
                //         if(j == index){
                //             nrr["n"] = data['summary_values'][i][nname][j];
                //             nrr["p"] = data['summary_values'][i][pname][j]
                //             arr['data'].push(nrr);
                //         }
                //     }
                // }else {
                    nrr["n"] = data['summary_values'][i][nname][j];
                    nrr["p"] = data['summary_values'][i][pname][j]
                    arr['data'].push(nrr);
                // }
                // nrr["n"] = data['summary_values'][i][nname][j];
                // nrr["p"] = data['summary_values'][i][pname][j]
                // arr['data'].push(nrr);
            }
            tabledata.push(arr);
        }

        // var titdata = [];
        // for(let i in data['days']){
        //     var tit = "第" + i + "日";
        //     titdata.push(tit);
        // }
        // if(data['filter_item_type'] != "all" && data['filter_item_type'] != "" && data['filter_item_type']){
        //     var titarr = [];
        //     for(let j in filterarr){
        //         var index = Number(filterarr[j]);
        //         titarr.push(data['days'][index]);
        //     }
        //     for(let i in titarr){
        //         var tit = "第" + titarr[i] + "日";
        //         titdata.push(tit);
        //     }
        // }else {
        //     for(let i in data['days']){
        //         var tit = "第" + data['days'][i] + "日";
        //         titdata.push(tit);
        //     }
        // }
        // titdata.unshift("日期",data.title);
        var date = data['start_date'] + " - " + data['end_date'];
        var dataArr = {
            titledata: data.title,
            condata:tabledata,
            retentiontype:data.retentiontype,
            date:date
        }
        callback && callback(dataArr);
    };

    X.retentionchart = function(d,callback){
        var nname,pname,wowtype="",chain_ratiotype="";
        if(d.retentiontype == 0) {
            nname = 'n';
            pname = 'p';
        }else {
            nname = 'n_outflow';
            pname = 'p_outflow';
        }
        var arr = {};
        var legenddata = [];
        var seriesData = [];
        var xAxisData = [];
        var date,sum=0,mean=0,sameday=0;
        date = d['start_date'] + " - " + d['end_date'];
        if(jQuery.isEmptyObject(d.values)){
            var arr = []
            for(let i in d['summary_values']){
                var index = d['summary_values'][i][pname].length - 1;
                legenddata.push(i);
                arr.push(d['summary_values'][i][pname]);
            }
            d.title.splice(0,1);
            xAxisData = d.title;
            for(let i in arr){
                var drr = {
                    name: d.date_range[i],
                    type: 'line',
                    data: arr[i]
                }
                seriesData.push(drr);
            }
            // for(let i in arr){
            //     if(arr[i] != "-"){
            //         sum = sum + 0;
            //     }
            //     sameday = arr[i];
            // }
            // mean = (sum / arr.length).toFixed(2);
            
        }else {
            var timearr = [];
            for(let i in d.values){
                timearr.push(i);
                for(let j in d.values[i]){
                    if(arr[j]){
                        arr[j][i] = d.values[i][j][pname];
                    }else {
                        arr[j]=[];
                        arr[j][i] = d.values[i][j][pname];
                    }
                }
            }
            var ydata = {};
            for(let j in arr){
                if(!ydata[j]){
                    ydata[j] = [];
                }
                for( let i in timearr ){
                    ydata[j].push("");
                    for(let z in arr[j]){
                        if(timearr[i] == z){
                            var index = arr[j][z].length - 1;
                            ydata[j][i] =arr[j][z][index];
                        }
                    }
                }
            }
            for(let i in ydata){    
                legenddata.push(i);
                var arr = {
                    name: i,
                    type: 'line',
                    data: ydata[i]
                }
                seriesData.push(arr)
            } 

        }

        if(d['wow']){
            if(d['wow'] >= 0){
                wowtype = '+'
            }else{
                wowtype = '-'
            }
        }

        if(d['chain_ratio']){
            if(d['chain_ratio'] >= 0){
                chain_ratiotype = '+'
            }else{
                chain_ratiotype = '-'
            }
        }

        var selected = {};//线多的话默认显示5条
        if(legenddata.length > 5){
            for(let i in legenddata){
                if(i < 5){
                    selected[legenddata[i]] = true;
                }else {
                    selected[legenddata[i]] = false;
                }
            }
        }
        
        var dataArr = {
            xAxisData:xAxisData,
            legenddata:legenddata,
            seriesData:seriesData,
            selected:selected,
            date:date,
            sum:sum.toFixed(2),
            mean:mean,
            sameday: 0,
            wowtype:wowtype,
            chain_ratiotype:chain_ratiotype,
            retentiontype:d.retentiontype
        }
        callback && callback(dataArr);
    };

    X.ltvtable=function(data,callback){
        var date = data['start_date'] + " - " + data['end_date'];
        var dataArr = {
            titledata:data.title,
            condata:data.rows,
            date:date
        }
        callback && callback(dataArr);
    };

    X.userpropertytable=function(data,callback){
        var dataArr = {
            titledata:data.title,
            condata:data.value
        }
        callback && callback(dataArr);
    };

    X.userpropertychart=function(data,callback){
        var xAxisData = [];
        var seriesdata =[];
        var legenddata = [];
        var date,sum,mean,sameday;
        for(let i in data.value){
            xAxisData.push(i);
            seriesdata.push(data.value[i]);
        }
        var dataArr = {
            xAxisData:xAxisData,
            legenddata:legenddata,
            seriesData:seriesdata,
            date:0,
            sum:0,
            mean:0,
            sameday: 0
        }
        // console.log(xAxisData);
        // console.log(seriesdata);
        callback && callback(dataArr);
    };

    X.scattertable=function(data,callback){
        var tabledata = [];
        for(let i in data.list){
            var arr = {
                date: i,
                d0: data['list'][i]['总体']["total"],
                data:[]
            }
            for(let j in data['list'][i]['总体']["n"]){
                var nrr = {
                    n:0,
                    p:0
                }
                nrr["n"] = data['list'][i]['总体']["n"][j];
                nrr["p"] = data['list'][i]['总体']["p"][j]
                arr['data'].push(nrr);
            }
            tabledata.push(arr)
        }
        data['tabletitle'] = $.extend(true,[],data['label']);
        data['tabletitle'].unshift('事件发生时间','总人数');
        var date = data['start_date'] + " - " + data['end_date'];
        var dataArr = {
            titledata: data.tabletitle,
            condata:tabledata,
            date:date
        }
        callback && callback(dataArr);
    };

    X.scatterchart=function(data,callback){

        var legendData = data.label;
        var xAxisData = [];
        var seriesData = [];
        var arr =[];
        for(let i in data['list']){
            xAxisData.push(i);
            for(let j in data['list'][i]){
                if(arr[j]){
                    arr[j][i] = data['list'][i][j]['n'];
                }else {
                    arr[j]=[];
                    arr[j][i] = data['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',
                data: ydata[i]
            }
            seriesData.push(arr);
        }
        var date = data['start_date'] + " - " + data['end_date'];
        var dataArr = {
            xAxisData:xAxisData,
            legenddata:legendData,
            seriesData:seriesData,
            date:date,
        }
        callback && callback(dataArr);
    };


    // 分组项
    // X.grouped=function(data,id){
    //     console.log(data)
    //     var html
    //     for(let i in data){
    //         html = html + ` 
    //         <div class="analysis-action-row">
    //             <div class="analysis-action-left">
    //                 <div class="analysis-num bgcolor">` + i+1 + `</div>
    //                 <div class="analysis-ant-dropdown-trigger">
    //                     <img src="./static/img/shaix2.png"/>
    //                     <span>` + data[i]['column_name'] + `</span>
    //                 </div>
    //             </div>
            
    //             <div class="analysis-ta-property-range analysis-granularity"> <img src="./static/img/shezhi2.png"> </div> 
            
    //             <div class="analysis-ta-property-range analysis-section"> <img src="./static/img/shezhi2.png"> </div>
    //             <div class="analysis-action-right"> <img src="./static/img/cha1.png"/> </div>
    //         </div>
    //     `
    //     }
    //     $(id).html(html);
    // }
    
    // function ScreenClick(id){
    //     $("#zhuanghu_xila").hide();
    //     $("#zhuanghu_xila").empty();
    //     var judge_boxtxt = $('#judge_box').val();
    //     var data ={};
    //     for(let i in ScreenArr){
    //        for(let j in ScreenArr[i]['Category']){
    //             if(ScreenArr[i]['Category'][j]['id'] == id){
    //                 data = ScreenArr[i]['Category'][j];
    //                 break;
    //             }
    //        }
    //     }
        
    //     if(data['type'] == 'time'){
    //         $(".judge_box").hide();
    //         $(".search_txt").hide();
    //         $(".time-box").show();
    //     }else {
    //         $(".judge_box").show();
    //         if(judge_boxtxt == 4 || judge_boxtxt == 5){
    //             $("#judge_input").val('');
    //             $("#judge_input").hide();
    //         }else {
    //             $(".search_txt").show();
    //         }
    //         $(".time-box").hide();
    //     }
    //     $("#zhanghu_box span").html(data['title']);
    //     $("#zhanghu_box").attr('title',data['title']);
    //     $(".Screen").hide();
    //     $(".Screen").empty();
    // }



})();
