//基础通用方法
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'}
            ]
        },
        //用户搜索条件
        'search':{
            category:[
                {
                    'title':'全部',
                    'id':'0',
                    'Category':[]
                },
                {
                    'title':'用户属性',
                    'id':'1',
                    'Category':[ 
                        {'title':'账户ID','id':'10','type':'string'},
                        {'title':'访客ID','id':'11','type':'string'},
                        {'title':'注册时间','id':'12','type':'time'},
                        {'title':'来源渠道','id':'13','type':'time'},
                    ]
                },
                {
                    'title':'测试',
                    'id':'2',
                    'Category':[ 
                        {'title':'账户ID','id':'10','type':'string'},
                        {'title':'访客ID','id':'11','type':'string'},
                        {'title':'注册时间','id':'12','type':'time'},
                        {'title':'来源渠道','id':'13','type':'time'},
                    ]
                }
            ],
            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}
            ]
        },
        //日期控件参数
        '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':{
      
        }
    },
};

(function(){

    // var ipurl = "http://10.0.0.77:7889/api/v1/";
    var ipurl = "http://139.159.159.3:9865/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){
                // console.log(d);
                if(d.code == 0){
                    callback && callback(d.data);
                }else {
                    layer.msg(d.msg);
                }
                layer.close(index);
            },
            error:function(error){
               layer.msg('条件错误');
               layer.close(index);
         }
        });
    };

    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){
        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'
        }
        layui.table.render({
            headers: {
                Authorization: token
                }
            ,elem: id
            ,url: url
            ,cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            ,cols: data
            ,height: height
        });
    };

    //渲染模板,模板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,
            shadeClose: true,
            offset: [deviationtop,deviationleft],
            url: url,
            extData : data,
            callback : callback
        });
    };

    X.parametersopen = function(data,url,offset,callback){
        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.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.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(1, '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')
                ]
            },
            "alwaysShowCalendars": true,
            "startDate": moment().subtract(7, '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;
            }
        }
    };

    X.eventtable=function(data,callback){
        var titledata,condata = [];
        for(let i in data){
            if(data[i]['values'].length > 0 ){
                if(data[i]['groups']['length'] == 0){
                    titledata= $.extend(true,[],data[0]['date_range']) ;
                    titledata.unshift('指标','阶段总和');
                    condata.push(data[i].values[0]);
                    condata[i].unshift(data[i]['event_name'],data[i]['sum']);
                    // console.log(condata);
                }         
            }else {
                layer.msg('查询数据为空');
            }
        }
        var dataArr = {
            titledata:titledata,
            condata:condata
        }
        
        callback && callback(dataArr);
    };

    X.eventchart = function(data,callback){
        var legenddata=[];
        for(let i in data){
            for(let z in data[i]['groups']){
                var pj =  data[i]['event_name']+data[i]['groups'][z];
                legenddata.push(pj);
            }
        }
        var seriesData=[];
        var sum = 0;
        var mean = 0;
        var sameday = 0;
        var date;

        var length = data[0]['date_range'].length - 1;
        date = data[0]['date_range'][length];
        for(let i in data){
            for(let z in data[i]['values']){
                var arr = {
                    name: '',
                    type: 'line',
                    stack: '总量',
                    
                    data: data[i]['values'][z]
                }
                seriesData.push(arr);
                sameday = data[i]['values'][z][data[i]['values'][z].length - 1];
                for(let j in data[i]['values'][z]){
                    mean = parseInt(mean) + parseInt(data[i]['values'][z][j]);
                }
            }
            sum = sum + data[i]['sum'][0];
            mean = mean / data[i]['values'].length;
        }
        if(legenddata.length > 0){
            for(let i in seriesData){
                seriesData[i]['name'] = legenddata[i];
            }
        }

        var dataArr = {
            xAxisData:data[0]['date_range'],
            legenddata:legenddata,
            seriesData:seriesData,
            date:date,
            sum:sum,
            mean:mean,
            sameday: sameday
        }
        
        callback && callback(dataArr);
    };

    X.eventsmall = function(data,callback){
        var date,num,thedayprop,weekprop,thedaypropsize,weekpropsize; //时间，当天数量，与前天对比，与上个星期对比,与前天对比正负,与上个星期对比正负
        // console.log(data);
        // 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];
        thedayprop = num / data[0]['values'][0][length - 1];
        weekprop = num / data[0]['values'][0][length - 8];
        var prop1,prop2;
        if(thedayprop >= 1){
            prop1 = parseFloat((thedayprop - 1)*100);
            thedaypropsize = '+';
        }else {
            prop1 = parseFloat((1 - thedayprop)*100);
            thedaypropsize = '-';
        }

        if(weekprop >= 1){
            prop2 = parseFloat((weekprop - 1)*100);
            weekpropsize = '+';
        }else {
            prop2 = parseFloat((1 - weekprop)*100);
            weekpropsize = '-';
        }

        var dataArr = {
            date: date,
            num: num,
            thedayprop: prop1.toFixed(2),
            thedaypropsize:thedaypropsize,
            weekprop: weekprop.toFixed(2),
            weekpropsize:weekpropsize
        }
        callback && callback(dataArr);
    };

    X.retentiontable=function(data,callback){
        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]["n"]){
                var nrr = {
                    n:0,
                    p:0
                }
                nrr["n"] = data['summary_values'][i]["n"][j];
                nrr["p"] = data['summary_values'][i]["p"][j]
                arr['data'].push(nrr);
            }
            tabledata.push(arr);
        }

        var titdata = [];
        for(let i in data['days']){
            var tit = "第" + i + "日";
            titdata.push(tit);
        }
        titdata.unshift("日期",data.title);
        var dataArr = {
            titledata:titdata,
            condata:tabledata
        }
        callback && callback(dataArr);
    };

    X.retentionchart = function(d,callback){
        var arr = {};
        var legenddata = [];
        var seriesData = [];
        var xAxisData = [];
        var date=0,sum=0,mean=0,sameday=0;
        if(jQuery.isEmptyObject(d.values)){
            var arr = []
            for(let i in d['summary_values']){
                var index = d['summary_values'][i]['p'].length - 1;
                arr.push(d['summary_values'][i]['p'][index]);
                xAxisData.push(i);
            }

            seriesData = {
                type: 'line',
                data: arr
            }
            for(let i in arr){
                sum = sum + arr[i];
                sameday = arr[i];
            }
            date = '近'+xAxisData.length+'天时间';
            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]['p'];
                    }else {
                        arr[j]=[];
                        arr[j][i] = d.values[i][j]['p'];
                    }
                }
            }
            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)
            } 

        }
        
        var dataArr = {
            xAxisData:xAxisData,
            legenddata:legenddata,
            seriesData:seriesData,
            date:date,
            sum:sum.toFixed(2),
            mean:mean,
            sameday: sameday
        }
        // console.log(dataArr);
        callback && callback(dataArr);
    };

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

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

    X.userpropertychart=function(data,callback){

    };


    // 分组项
    // 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();
    // }



})();
