(function () {
    'use strict';

    angular.module("app")
    .factory("ToolService",["$rootScope","$timeout","UtilService",toolservice]);

    function toolservice($rootScope,$timeout,UtilService){
    	var service = {},that = $rootScope,
        rootmenu = {"dataview":"数据概览","action":"行为分析","user":"用户分析","event":"埋点管理","tool":"工具"},
        menu = {"custommenu": "行业看单","eventstats": "事件分析","funnel": "漏斗转化","retention": "留存分析",
                "intelligentpath": "智能路径","usergroup": "用户分群","event": "APP事件管理","profile": "用户属性管理",
                "logtool": "日志流-IO","report": "下载报表-IO","app": "产品中心-IO","auth": "成员管理-IO"};
    	service.setName = function(name){
    		that.name = name;
    	}
    	service.getName = function(){
    		return that.name;
    	}
        service.isDemoUser = function(){
            return (UtilService.getUser().email == 'demo@reyun.com');
        }
        service.getChannelCampaignList = function(){
            var list = [
                {id:"channel",name:"渠道"},
                {id:"campgroup",name:"活动组"},
                {id:"campaign",name:"活动"}
            ];
            return UtilService.cloneJSON(list);
        }
        service.getPackTypeList = function(){
            var list = [
                {id:"all",name:"全部"},
                {id:"APPMARKET",name:"分包"},
                {id:"ADVERTISING",name:"分链接"}
            ];
            return UtilService.cloneJSON(list);
        }
        service.getDeviceTypeList = function(){
            var list = [
                {id:"device",name:"按设备看"},
                {id:"user",name:"按账号看"}
            ];
            return UtilService.cloneJSON(list);
        }
        /**
         * [getChannelCampaignUrl description]
         * @param  type
         * @param  appid
         * @param cid 渠道ID
         * @return
         */
        service.getChannelCampaignParams = function(type,appid,cid){
            var url = "",txt = "";
            if(type == 'channel'){ //渠道
                url = appid + "/channel/findall";
                txt = "渠道";
            }
            else if(type == 'campgroup'){//活动组
                url = appid + "/campgroup/findall";
                txt = "活动组";
            }
            else if(type == 'campbychannel'){//应用渠道下的活动
                url = appid + "/campaign/findbychannel?channelid="+cid;
                txt = "活动";
            }
            else{
                url = appid + "/campaign/findall";
                txt = "活动";
            }
            return {
                url :url,
                txt:txt
            };
        }
        /**
         * [getParams description]
         * @param  {[type]} obj  一般为$scope
         * @param  {[type]} flag  1:有渠道、活动组、活动筛选
         * @return {[type]}      [description]
         */
        service.getParams = function(obj,flag){
            var params = {appid:obj.appid};
            if(obj.date){
                params.startdate = obj.date.startDate;
                params.enddate = obj.date.endDate;
            }
            if(flag && flag == 1 && obj.typeInfoIds != "" && obj.typeInfoIds != -1){{
                switch(obj.typeId){
                    case "campgroup":
                        params.cgroupid = obj.typeInfoIds;
                        break;
                    case "campaign":
                        params.campaignid = obj.typeInfoIds;
                        break;
                    case "channel":
                    default:
                        params.cid = obj.typeInfoIds;
                        break;
                }
            }}
            return params;
        }
        service.getOneColors = function(){
            return ["#1fb9e9"];
        }
        service.getTwoColors = function(){
            return ["#1fb9e9","#f8a20f"];
        }
        service.getThreeColors = function(){
            return ["#1fb9e9","#f8a20f","#8e6eb6"];
        }
        service.getSixColors = function(){
            return ["#1fb9e9","#f8a20f","#8e6eb6","#9cc272","#f36e55","#00b37f"];
        }
        service.getTenColors = function(){
            return ["#1fb9e9","#f8a20f","#00b37f","#f36e55","#5c9eff","#fccc01","#9cc272","#ec407a","#8e6eb6","#cddc39"];
        }
        service.getToday = function(){
            return {
                startDate:UtilService.getDay(0),
                endDate:UtilService.getDay(0)
            }
        }
        service.getYesDay = function(){
            return {
                startDate:UtilService.getDay(-1),
                endDate:UtilService.getDay(-1)
            }
        }
        service.getLastDays = function(d,flag){
            if(angular.isUndefined(flag)){ //默认最大显示昨天
                flag = -1;
            }
            else{
                if(d>0){
                    d -= 1;
                }
                else{
                    d += 1;
                }
            }

            return {
                startDate:UtilService.getDay(d),
                endDate:UtilService.getDay(flag)
            }
        }
        service.getLastWeeks = function(d){
            var w = UtilService.getNowWeekNum(),
                date = new Date(),
                year = date.getFullYear();

            var range = {end:year+UtilService.getStr(w)},pd = d + w +1;
            if(pd > 0 ){
                range.start = year + UtilService.getStr(pd);
            }else{
                var pr = UtilService.getYearWeekCount(year-1);
                range.start = (year-1) + UtilService.getStr(pr + pd);
            }
            return range;
        }
        service.getLastMonths = function(d){
            var date = new Date(),year = date.getFullYear(),month = date.getMonth()+1;

            var range = {end:year+UtilService.getStr(month)},pm = month+d+1;
            if(pm > 0 ){
                range.start = year + UtilService.getStr(pm);
            }else{
                range.start = (year-1) + UtilService.getStr(12 + pm);
            }
            return range;
        }

        service.getStringTypes = function(){
            return [
                {"id":"=","name":"="},
                {"id":"!=","name":"≠"},
                {"id":"in","name":"in","more":true},
                {"id":"not in","name":"not in","more":true}
            ]
        }
        service.getNumberTypes = function(){
            return [
                {"id":">","name":">"},
                {"id":">=","name":">="},
                {"id":"=","name":"="},
                {"id":"<=","name":"<="},
                {"id":"<","name":"<"},
                {"id":"between","name":"between","both":true}
            ]
        }

        //loading加载
        service.showLoading = function(){
            document.getElementById("sysLoad").style.display = "block";
            setTimeout(function(){
              service.hideLoading();
            },60*100);
        }
        service.hideLoading = function(){
            document.getElementById("sysLoad").style.display = "none";
        }
        //显示灰色背景
        service.showAlp = function(){
            document.getElementById("alpLoad").style.display = "block";
        }
        service.hideAlp = function(){
            document.getElementById("alpLoad").style.display = "none";
        }

        //删除等操作提示
        service.showTips = function(msg,time){
            service.hideLoading();
            var t = 1200;
            if(msg.length>10){
                t  = 2000;
            }
            time = time || t;
            $rootScope.operShow = true;
            $rootScope.operMsg = msg;
            $timeout(function(){
                service.hideTips();
            },time);
        }
        service.hideTips = function(){
            $rootScope.operShow = false;
            $rootScope.operMsg = "";
        }

        service.getMenuTip = function(name){
            var tip = $rootScope.currentPageTips[name];
            if(!tip){
                tip = "无";
            }
            return tip;
        }

        //计算漏斗数据格式
        service.getFunnelData = function(fdata,chartKey,chartKeyName){
            var rmd = new Date().getTime();
            if(angular.isUndefined(fdata)){
                fdata = {};
            }
            var users = [],rates = [],marks = [],preu = -1;
            chartKeyName.filter(function(key){
                var u = fdata[key],r = fdata['rate_'+key];
                u = angular.isUndefined(u) ? 0 : u;
                r = angular.isUndefined(r) ? 0 : r;
                users.push(u);
                rates.push(r);

                if(preu>-1){
                    if(preu==0){
                        marks.push(0);
                    }else{
                        marks.push(UtilService.decimal2(u/preu*100));
                    }
                }
                preu = u;
            });

            var data = {
                val : [rates,users],
                trans4last : marks,
                key : chartKey,
                rmd : ++rmd
            };
            var rateData = data.val[0],rateData1 = [],preRate = 0;
            for(var i=0;i<rateData.length;i++){
                var r = preRate - rateData[i];
                if(preRate>0){
                    // r = r / preRate  * preRate;
                }else{
                    r = 0;
                }
                rateData1.push(r); //转化率
                preRate = rateData[i];
            }
            data.val.splice(1,0,rateData1);

            return data;
        }

        service.noDataChart = function(){
            var rmd = new Date().getTime();
            return {
                val : [],
                trans4last : [],
                key : [],
                rmd : ++rmd,
                name :[]
            };
        }
        /**
         *
         * @param  {[type]} type   funnel:漏斗
         *                         customretention:自定义留存
         *                         detailcustomretention:自定义留存明细,
         *                         commonretention:固定留存
         *                         eventstats:事件
         *                         normal:普通
         */
        service.getChartConditions = function(name,reportname,params,type,id){
            if(UtilService.isNullStr(type)){type = "normal";}

            var appid = params.appid,newparams = UtilService.cloneJSON(params);
            var subType = params.viewtype || "";
            delete newparams.appid;
            var condition = {
                reportName:reportname,
                conditions:JSON.stringify(newparams),
                functionType:type,
                subType:subType,
                app:appid,
                name:name
            };
            if(!UtilService.isNullStr(id)){
                condition.functionId = id;
            }
            return condition;
        }
        //计算字节长度
        service.getByteLen = function(col){
            var templen=0;
            for(var i=0; i < col.length; i++){
                var a = col.charAt(i);
                if (a.match(/[a-zA-Z\u4e00-\u9fa5]/) != null) {
                    templen += 2;
                }
                else {
                    templen += 1;
                }
            }
            return templen;
        }
        //计算table列宽
        service.getTableColsWidth = function(cols,flag,count){
            var colsStyle = [];
            var leftw = $rootScope.unfoldFlag?90:230;
            var tablew = flag?(($(window).width()-10-leftw)/(count?count:2)-(count==3?48:45)):($(window).width()-leftw), colsw = 0;
            var specialCols = "推广活动,推广活动组,渠道,子渠道,子账号,关键字,创意,付费激活周期";
            angular.forEach(cols,function(col){
                var templen = service.getByteLen(col);
                var colw = specialCols.indexOf(col)>-1?240:col=="日期"?(flag!='day'?160:90):col=='分组'?150:(8 * templen+(flag?13:27));
                var colStyle = {'width': colw +'px','max-width': colw +'px'};
                colsw += colw;
                colsStyle.push(colStyle);
            });
            if(colsw < tablew){
                // var leftw = $rootScope.unfoldFlag?90:$rootScope.unfoldFlag==false?230:270;
                // tablew = $(window).width()-leftw;
                // if(flag){
                //     tablew = (tablew-10)/2-45;
                // }
                var diffw = tablew - 2 - colsw,
                    collen = colsStyle.length,
                    coldiffw = (diffw - 12*collen)/collen;
                angular.forEach(colsStyle,function(col){
                    var ocolw = parseInt(col.width.slice(0,-2));
                    col.width = col['max-width'] = ocolw + coldiffw +'px';
                });
            }
            return colsStyle;
        }

        service.getCMidInfo = function(){
            var cid = localStorage.getItem("rytf_cid"),
                campaignid = localStorage.getItem("rytf_campid");

            if(UtilService.isNullStr(cid)){
                cid = -1;
                campaignid = '_default_';
            }
            return {
                cid : cid,
                campaignid : campaignid
            };
        }
        service.getRoleName = function(){
            if($rootScope.isSuper){
                return "主账号";
            }
            else if($rootScope.isManage){
                return "管理员";
            }
            else if($rootScope.isAppManage){
                return "子应用管理员";
            }
        }
        service.setUser = function(user){
           window.localStorage.setItem("io_ry_user",JSON.stringify(user));
        }
        service.getUser = function(){
            var u = localStorage.getItem("io_ry_user");

            if(UtilService.isNullStr(u)){
                return {};
            }
            else{
                return JSON.parse(u);
            }
        }

        //菜单报送数据
        service.getMenuSubmitData = function(submenu){
            if($rootScope.pagePath=="userinfo")return;

            var cmids = service.getCMidInfo();
            var company = service.getUser().company;
            if(UtilService.isNullStr(company)){
                company = "";
            }

            var appkey = "",appcategory = "",appname = "",rootmenukey;
            if($rootScope.appInstance){
                appkey = $rootScope.appInstance.appkey;
                appcategory = $rootScope.appInstance.appGenreName;
                appname = $rootScope.appInstance.name;
            }
            if(!submenu || submenu==''){submenu = menu[$rootScope.pagePath];}
            for (var m in that.meauTree){
               if(that.meauTree[m].indexOf($rootScope.pagePath)>-1){
                 rootmenukey = m;
               }
            }
            var Uuser = UtilService.getUser();
            var params = {
                appid: UtilService.getTKAppkey(),
                who:Uuser.email,
                what:"pageview",
                context:{
                    rootmenu:rootmenu[rootmenukey], //菜单分类
                    menu:menu[$rootScope.pagePath], //当前菜单
                    submenu:submenu, //子菜单-看单
                    sessionid:UtilService.getCookie("JSESSIONID"),

                    user_appkey:appkey, //所选APP的id,
                    appcategory:appcategory,//应用类型  中文名
                    appname:appname, //应用名称
                    rolename:service.getRoleName(),
                    company:company,

                    "_cid":cmids.cid,
                    "_campaignid":cmids.campaignid,
                    "_apptype":"wap",

                    email:Uuser.email,
                    _deviceid:UtilService.randDeviceId(), //设备ID
                    operatesystem: UtilService.operatorSystem(),//操作系统  _ryos
                    browser: UtilService.getBrowser() //浏览器类型
                }
            };
            $.post(UtilService.getLogRoot()+"/receive/analyze/event",JSON.stringify(params));
        }
        //功能报送数据
        service.getOperSubmitData = function(opername){
            var appkey = "",appcategory = "",appname = "";
            if($rootScope.appInstance){
                appkey = $rootScope.appInstance.appkey;
                appcategory = $rootScope.appInstance.appGenreName;
                appname = $rootScope.appInstance.name;
            }

            var cmids = service.getCMidInfo();
            var company = service.getUser().company;
            if(UtilService.isNullStr(company)){
                company = "";
            }

            var Uuser = UtilService.getUser();
            var params = {
                appid:UtilService.getTKAppkey(),
                who:Uuser.email,
                what:"operation",
                context:{
                    menu:menu[$rootScope.pagePath], //菜单分类
                    opername:opername, //操作名字

                    email:Uuser.email,
                    user_appkey:appkey, //所选APP的id,
                    appcategory:appcategory,//应用类型  中文名
                    appname:appname, //应用名称
                    rolename:service.getRoleName(),
                    company:company,

                    "_cid":cmids.cid,
                    "_campaignid":cmids.campaignid,
                    "_apptype":"wap",

                    _deviceid:UtilService.randDeviceId(), //设备ID
                    operatesystem: UtilService.operatorSystem(),//操作系统  _ryos
                    browser: UtilService.getBrowser() //浏览器类型
                }
            };
            $.post(UtilService.getLogRoot()+"/receive/analyze/event",JSON.stringify(params));
        }

      //自定义报送
      service.sendWhatEvtData = function(what,jsonparams){
          var appkey = "",appcategory = "",appname = "";
          if($rootScope.appInstance){
              appkey = $rootScope.appInstance.appkey;
              appcategory = $rootScope.appInstance.appGenreName;
              appname = $rootScope.appInstance.name;
          }

          var cmids = service.getCMidInfo();
          var company = service.getUser().company;
          if(UtilService.isNullStr(company)){
              company = "";
          }

          var Uuser = UtilService.getUser();
          var params = {
              appid:UtilService.getTKAppkey(),
              who:Uuser.email,
              what:what,
              context:{
                  email:Uuser.email,
                  user_appkey:appkey, //所选APP的id,
                  appcategory:appcategory,//应用类型  中文名
                  appname:appname, //应用名称
                  rolename:service.getRoleName(),
                  company:company,

                  "_cid":cmids.cid,
                  "_campaignid":cmids.campaignid,
                  "_apptype":"wap",

                  _deviceid:UtilService.randDeviceId(), //设备ID
                  operatesystem: UtilService.operatorSystem(),//操作系统  _ryos
                  browser: UtilService.getBrowser() //浏览器类型
              }
          };
          if(jsonparams){
            for(var k in jsonparams){
              params.context[k] = jsonparams[k];
            }
          }

          $.post(UtilService.getLogRoot()+"/receive/analyze/event",JSON.stringify(params));
      }
    	return service;
    }
})();
