/**
 * Created by lgy on 2015/10/20.
 */

App.controller('timelineCtrl', ['$scope', '$http', '$location', function ($scope, $http, $q) {
    'use strict';
    
    $scope.isshowjia=true;
    $scope.gettimeline = function (page,i) {
        if(i==0){
            $scope.plans=[];
            $scope.pagenum=1;
        }
        $http.post('./plan_findMarketingPlan.action', {
            currpage: $scope.pagenum,
            pagesize: $scope.pagesize
        }, $scope.postCfg)
            .success(function (data) {
                var systime=data.nowday;
                var dayNames = new Array("周日","周一","周二","周三","周四","周五","周六");
                $scope.isshowjia=true;
                var hasProp = false;
                for(var name in data.planweekmap) {
                    hasProp=true;
                    var newplans = {};
                    newplans['dtime'] = deterdate(new Date(name), new Date(systime));
                    newplans['curtime'] = name;
                    newplans['dweekday'] = dayNames[new Date(name).getDay()];
                    var plandata = data.planweekmap[name];
                    newplans['daydatas'] = plandata;
                    $scope.plans.push(newplans);
                    $scope.pagenum += 1;
                }
                if (!hasProp){
                    if($scope.pagenum==1){
                        $scope.isshowjia=false;
                        $scope.tipshow(0,'暂无执行计划');
                    }else{
                        $scope.isshowjia=true;
                        $scope.tipshow(0,'已经是最后一页了');
                    }

                }
            });

    };
    $scope.gettimeline(1,0);

    function deterdate(r1,r2){
        var r1_Year=r1.getFullYear();
        var r1_Month=r1.getMonth()+1;
        var r1_Date=r1.getDate();
        var getr1=r1_Year+r1_Month+r1_Date;
        var r2_Year=r2.getFullYear();
        var r2_Month=r2.getMonth()+1;
        var r2_Date=r2.getDate();
        var getr2=r2_Year+r2_Month+r2_Date;
        if(parseInt(getr2)-parseInt(getr1)==0){
            return '今天';
        }else if(parseInt(getr2)-parseInt(getr1)==1){
            return '昨天';
        }else{
            //if(r1_Month<10){
            //    r1_Month="0"+r1_Month;
            //}
            //if(r1_Date<10){
            //    r1_Date="0"+r1_Date;
            //}
            return r1_Year+'-'+r1_Month+'-'+r1_Date;
        }
    }

}]);

App.controller('planviewCtrl', ['$scope', '$http', '$location', function ($scope, $http, $location) {
    'use strict';
    $scope.planName=""; //计划名称
    $scope.planCycle="";//执行周期
    $scope.getplan = function (id) {
        var k=$("#plantypeid").val();
        $scope.listitems = [];
        $(".yyloading").show();
        $http.post('./plan_findMarketingPlanTable.action', {
            currpage: id,
            pagesize: $scope.pagesize,
            condition:k
        }, $scope.postCfg)
            .success(function (data) {
                $(".yyloading").hide();
                var plandata = data.markeplanlist;
                for (var i = 0; i < plandata.length; i++) {
                    var newdata = {};
                    newdata['planid'] = plandata[i].plan_id;
                    newdata['plantitle'] = plandata[i].plan_title;
                    switch (plandata[i].plan_type) {
                        case 0:
                            newdata['plantype'] = '提醒';
                            break;
                        case 1:
                            newdata['plantype'] = '执行';
                            break;
                    }
                    switch (plandata[i].plan_cycle) {
                        case 1:
                            newdata['plancycle'] = '月计划';
                            break;
                        case 2:
                            newdata['plancycle'] = '周计划';
                            break;
                        case 3:
                            newdata['plancycle'] = '月计划';
                            break;
                        case 4:
                            newdata['plancycle'] = '指定时间';
                            break;
                        case 5:
                            newdata['plancycle'] = '特殊节日';
                            break;
                        case 6:
                            newdata['plancycle'] = '指定具体日期';
                            break; 
                    }
                    var weeks = "";
                    var specialtime = "";
                    for (var j = 0; j < plandata[i].weeklist.length; j++) {
                        switch (plandata[i].weeklist[j].week_value) {
                            case 1:
                                if(weeks.indexOf('周一')<0){
                                    weeks = weeks + "周一,";
                                }
                                break;
                            case 2:
                                if(weeks.indexOf('周二')<0){
                                    weeks = weeks + "周二,";
                                }
                                break;
                            case 3:
                                if(weeks.indexOf('周三')<0){
                                    weeks = weeks + "周三,";
                                }
                                break;
                            case 4:
                                if(weeks.indexOf('周四')<0){
                                    weeks = weeks + "周四,";
                                }
                                break;
                            case 5:
                                if(weeks.indexOf('周五')<0){
                                    weeks = weeks + "周五,";
                                }
                                break;
                            case 6:
                                if(weeks.indexOf('周六')<0){
                                    weeks = weeks + "周六,";
                                }
                                break;
                            case 7:
                                if(weeks.indexOf('周日')<0){
                                    weeks = weeks + "周日,";
                                }
                                break;
                            case 8:
                                if(weeks.indexOf('元 旦')<0){
                                    weeks = weeks + "元 旦,";
                                    specialtime = specialtime+"元 旦:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                }
                                
                                break;
                            case 9:
                                if(weeks.indexOf('妇女节')<0){
                                    weeks = weeks + "妇女节,";
                                    specialtime = specialtime+"妇女节:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                }
                                break;
                            case 10:
                            	 if(weeks.indexOf('劳动节')<0){
                                     weeks = weeks + "劳动节,";
                                     specialtime = specialtime+"劳动节:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                 }
                                break;
                            case 11:
                            	 if(weeks.indexOf('圣诞节')<0){
                                     weeks = weeks + "圣诞节,";
                                     specialtime = specialtime+"圣诞节:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                 }
                                break;
                            case 12:
                            	 if(weeks.indexOf('春 节')<0){
                                     weeks = weeks + "春 节,";
                                     specialtime = specialtime+"春 节:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                 }
                                break;
                            case 13:
                            	 if(weeks.indexOf('元宵节')<0){
                                     weeks = weeks + "元宵节,";
                                     specialtime = specialtime+"元宵节:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                 }
                                break;
                            case 14:
                            	if(weeks.indexOf('清明节')<0){
                                    weeks = weeks + "清明节,";
                                    specialtime = specialtime+"清明节:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                }
                                break;
                            case 15:
                            	if(weeks.indexOf('端午节')<0){
                                    weeks = weeks + "端午节,";
                                    specialtime = specialtime+"端午节:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                }
                                break;
                            case 16:
                            	if(weeks.indexOf('中秋节')<0){
                                    weeks = weeks + "中秋节,";
                                    specialtime = specialtime+"中秋节:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                }
                                break;
                            case 17:
                            	if(weeks.indexOf('国庆节')<0){
                                    weeks = weeks + "国庆节,";
                                    specialtime = specialtime+"国庆节:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                }
                                break;
                            case 18:
                            	if(weeks.indexOf('儿童节')<0){
                                    weeks = weeks + "儿童节,";
                                    specialtime = specialtime+"儿童节:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                }
                                break;
                            case 19:
                            	if(weeks.indexOf('父亲节')<0){
                                    weeks = weeks + "父亲节,";
                                    specialtime = specialtime+"父亲节:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                }
                                break;
                            case 20:
                            	if(weeks.indexOf('母亲节')<0){
                                    weeks = weeks + "母亲节,";
                                    specialtime = specialtime+"母亲节:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                }
                                break;
                            case 21:
                            	if(weeks.indexOf('感恩节')<0){
                                    weeks = weeks + "感恩节,";
                                    specialtime = specialtime+"感恩节:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                }
                                break;
                            case 22:
                            	if(weeks.indexOf('印度排灯节')<0){
                                    weeks = weeks + "印度排灯节,";
                                    specialtime = specialtime+"印度排灯节:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                }
                                break;
                            case 23:
                            	if(weeks.indexOf('俄罗斯新年')<0){
                                    weeks = weeks + "俄罗斯新年,";
                                    specialtime = specialtime+"俄罗斯新年:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                }
                                break;
                            case 24:
                            	if(weeks.indexOf('伊斯兰开斋节')<0){
                                    weeks = weeks + "伊斯兰开斋节,";
                                    specialtime = specialtime+"伊斯兰开斋节:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                }
                                break;
                            case 25:
                            	if(weeks.indexOf('耶稣复活节')<0){
                                    weeks = weeks + "耶稣复活节,";
                                    specialtime = specialtime+"耶稣复活节:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                }
                                break;
                            case 26:
                            	if(weeks.indexOf('欧美万圣节')<0){
                                    weeks = weeks + "欧美万圣节,";
                                    specialtime = specialtime+"欧美万圣节:"+getDate(plandata[i].weeklist[j].week_day)+",";
                                }
                                break;
                        }
                    }
                    weeks = weeks.substring(0, weeks.length - 1);
                    specialtime = specialtime.substring(0, specialtime.length - 1);
                    newdata['planweeks'] = weeks;
                    newdata['planstatus'] = plandata[i].plan_status;
                    newdata['planexecutetime'] = plandata[i].plan_executetime;
                    newdata['plan_grouptype'] = plandata[i].plan_grouptype;
                    newdata['plan_groupname'] = plandata[i].plan_groupname;
                    newdata['plan_begintime'] = plandata[i].plan_begintime;
                    newdata['plan_endtime'] = plandata[i].plan_endtime;
                    newdata['specialtime'] = specialtime;
                    newdata['plan_differen'] = plandata[i].plan_differen;
                    $scope.listitems.push(newdata);
                }

            }).error(function (data) {
                //处理错误
            });
        
        function getDate(date){
        	//开始时间+3
        	var resulttime = "";
        	var datt = date.split('-');
        	var newDate = new Date(datt[0], datt[1]-1, datt[2]);
        	var befminuts = newDate.getTime() + 1000 * 60 * 60 * 24 * parseInt(3);//计算前几天用减,计算后几天用加,最后一个就是多少天的数量
        	var beforeDat = new Date;
        	beforeDat.setTime(befminuts);
        	var befMonth = beforeDat.getMonth()+1;
        	var mon = befMonth >= 10 ? befMonth : '0' + befMonth;
        	var befDate = beforeDat.getDate();
        	var da = befDate >= 10 ? befDate : '0' + befDate;
        	resulttime = beforeDat.getFullYear() + '-' + mon + '-' + da;
        	return resulttime;
        }; 
    };
    $scope.getplan(1);
    $scope.delplans = function (id) {
    	 $('#dialog-delete').dialog({
             position: ["center", 100],
             modal: true,
             resizable: false,
             width: 350,
             maxHeight: 350,
             close:function(){
                 $(this).dialog("destroy");
             },
             buttons: {
                 "确认删除": function () {
                	 $http.post('./plan_delMarketingPlan.action', {
                         planid: id
                     }, $scope.postCfg)
                         .success(function (data) {
                             if (parseInt(data) == 1) {
                                 $scope.tipshow(1, "删除计划成功");
                                 $scope.getplan(1);
                             } else {
                                 $scope.tipshow(0, "删除计划失败");
                             }
                         })
                     $(this).dialog("destroy");

                 },
                 "取消": function () {
                     $(this).dialog("destroy");
                 }
             }
         });
    }
    
    $scope.findPlanDetail = function(id){
    	$scope.planlists = [];
    	$http.post('./plan_getMarketingPlan.action', {planid: id}, $scope.postCfg).success(function (data) {
    		var plantime = data.plan_executetime;
            var weeks = "";
            for (var j = 0; j < data.weeklist.length; j++) {
            	var newdata = {};
            	newdata['weekday'] = data.weeklist[j].week_day;
                newdata['plantime'] = plantime;
             	  var k = data.weeklist[j].week_value;
             	  switch (parseInt(k)) {
                   case 1:
                  	 weeks = '星期一';
                       break;
                   case 2:
                  	 weeks = '星期二';
                       break;
                   case 3:
                  	 weeks = '星期三';
                       break;
                   case 4:
                  	 weeks = '星期四';
                       break;
                   case 5:
                  	 weeks = '星期五';
                       break;
                   case 6:
                  	 weeks = '星期六';
                       break;
                   case 7:
                  	 weeks = '星期日';
                       break;
                  }
             	  	newdata['weeks'] = weeks;
	             	newdata['modename'] = data.weeklist[j].mode_name;
	             	newdata['modeid'] = data.weeklist[j].mode_id;
	             	newdata['isexecution'] = data.weeklist[j].isexecution;
	             	$scope.planlists.push(newdata);
            }
          })
    },
    $scope.toviewplans = function(id,type,date,begin,end,plancycle,groupname,differen){
    	var _html1 = "";
    	var _html2 = "";
    	if(differen == 11 || differen ==12){
    		if(plancycle =="特殊节日"){
        		_html1 = "计划名称:给<span style='color:red'>“个性营销”</span><span style='color:#337ab7;cursor: pointer;' class='load_more' name='"+groupname+"'>更多  </span>分类的<span style='color:red'>“"+plancycle+"”</span>跟进计划";
            	_html2 = "执行周期:"+plancycle+"每<span style='color:red'>“"+date+"”</span>发送"
        	}else{
        		_html1 = "计划名称:给<span style='color:red'>“个性营销”</span><span style='color:#337ab7;cursor: pointer;' class='load_more' name='"+groupname+"'>更多  </span>分类的<span style='color:red'>“"+plancycle+"("+begin+"~"+end+")"+"”</span>跟进计划";
            	_html2 = "执行周期:"+plancycle+"<span style='color:red'>“"+begin+"~"+end+"”</span>每<span style='color:red'>“"+date+"”</span>发送"
        	}
    	}else{
    		if(plancycle =="特殊节日"){
        		_html1 = "计划名称:给<span style='color:red'>“"+groupname+"”</span>分类的<span style='color:red'>“"+plancycle+"”</span>跟进计划"
            	_html2 = "执行周期:"+plancycle+"每<span style='color:red'>“"+date+"”</span>发送"
        	}else{
        		_html1 = "计划名称:给<span style='color:red'>“"+groupname+"”</span>分类的<span style='color:red'>“"+plancycle+"("+begin+"~"+end+")"+"”</span>跟进计划"
            	_html2 = "执行周期:"+plancycle+"<span style='color:red'>“"+begin+"~"+end+"”</span>每<span style='color:red'>“"+date+"”</span>发送"
        	}
    	}
    	$("#planName_id").html(_html1)
    	$("#planName_week").html(_html2)
    	  $('#dialog-plan').dialog({
              modal: true,
              resizable: false,
              close: function () {
                  $(this).dialog("destroy");
              },
              width: 750,
              maxHeight: 500
          });
    	$scope.findPlanDetail(id);
    	$(".load_more").click(function(){
    		var param_name = $(this).attr("name");
    		$scope.load_moreDialog(param_name);
    	})
    },
    //撤销计划
    $scope.cancelplans = function(id){
    	$('#dialog-cancle').dialog({
            position: ["center", 100],
            modal: true,
            resizable: false,
            width: 350,
            maxHeight: 350,
            close:function(){
                $(this).dialog("destroy");
            },
            buttons: {
                "确认撤销": function () {
                 $(".yyloading").show();
               	 $http.post('./plan_editMarketingPlan.action', {
                        planid: id
                    }, $scope.postCfg)
                        .success(function (data) {
                        	$(".yyloading").hide();
                            if (parseInt(data) == 1) {
                                $scope.tipshow(1, "撤销计划成功");
                                $scope.getplan(1);
                            } else {
                                $scope.tipshow(0, "撤销计划失败");
                            }
                        })
                    $(this).dialog("destroy");
                },
                "取消": function () {
                    $(this).dialog("destroy");
                }
            }
        });
    },
    //加载更多弹窗
    $scope.load_moreDialog = function(value){
  	  	var param_str = "";
		  param_str = value.split("@espeed@");
		  var cus_classify = param_str[0]; //客户分类
		  var cus_state = param_str[1]; //客户状态
		  var cus_from = param_str[2];//客户来源
		  var cus_star = param_str[3];//客户星级
		  var cus_pro = param_str[4];//关联产品
		  var cus_pur = param_str[5];//采购偏好
		  var cus_entry = param_str[6];//入库时间
		  var cus_contact = param_str[7];//联系时间
		  var cus_nofollow = param_str[8];//未跟进时间
		  var cus_type = param_str[9];//客户类型
		  $scope.cusCf = "";
		  $scope.cusSt = "";
		  $scope.cusFm = "";
		  $scope.cusSr = "";//星级
		  $scope.cusPro = "";
		  $scope.cusPur = "";
		  //客户类型
		  if(cus_type == 1){
			  $scope.cusType = "公海客户";
		  }else{
			  $scope.cusType = "私海客户";
		  }
		  //分类
		  if(cus_classify != "no"){
			  cus_classify = cus_classify.split(',');
			  $http.post('./cus_findClassifyAll.action',{iscounts: 1},$scope.postCfg).success(function(data){
	    		if(data != null && data != "" && data != undefined){
	    			for(var i = 0; i < data.length; i++){
		   				 for(var j = 0; j < cus_classify.length; j++){
		   					 if(cus_classify[j] == data[i].id){
		   						$scope.cusCf += data[i].name+",";
		   						 break;
		   					 }
		   				 }
	   			 	}
	    		}
	    		$scope.cusCf = $scope.cusCf.substring(0,$scope.cusCf.length-1);
			  });
		  }else{
			  $scope.cusCf = "无"; 
		  }
		//状态
		  if(cus_state != "no"){
			  cus_state = cus_state.split(',');
	    	$http.post('./cus_findStatusAll.action',{iscounts: 1},$scope.postCfg).success(function(data){
	    		if(data != null && data != "" && data != undefined){
	    			for(var i = 0; i < data.length; i++){
		   				 for(var j = 0; j < cus_state.length; j++){
		   					 if(cus_state[j] == data[i].id){
		   						$scope.cusSt += data[i].name+",";
		   						 break;
		   					 }
		   				 }
	   			 	}
	    		}
	    		$scope.cusSt = $scope.cusSt.substring(0,$scope.cusSt.length-1);
	     	});
		  }else{
			  $scope.cusSt = "无"; 
		  }
		//来源
		  if(cus_from != "no"){
			  cus_from = cus_from.split(',');
			  $http.post('./cus_findFromAll.action',{iscounts: 1},$scope.postCfg).success(function(data){
		    		if(data != null && data != "" && data != undefined){
		    			for(var i = 0; i < data.length; i++){
			   				 for(var j = 0; j < cus_from.length; j++){
			   					 if(cus_from[j] == data[i].id){
			   						$scope.cusFm += data[i].name+",";
			   						 break;
			   					 }
			   				 }
		   			 	}
		    		}
		    		$scope.cusFm = $scope.cusFm.substring(0,$scope.cusFm.length-1);
		     	});
		  }else{
			  $scope.cusFm = "无"; 
		  }
		//客户星级
		  if(cus_star != "no"){
			  cus_star = cus_star.split(',');
			 for(var i = 0; i < cus_star.length; i++){
				 if(cus_star[i] == 0){
					 $scope.cusSr = "无星级,";
				 }else if(cus_star[i] == 1){
					 $scope.cusSr = $scope.cusSr+"一星级,";
				 }else if(cus_star[i] == 2){
					 $scope.cusSr = $scope.cusSr+"二星级,";
				 }else if(cus_star[i] == 3){
					 $scope.cusSr = $scope.cusSr+"三星级,";
				 }else if(cus_star[i] == 4){
					 $scope.cusSr = $scope.cusSr+"四星级,";
				 }else if(cus_star[i] == 5){
					 $scope.cusSr = $scope.cusSr+"五星级,";
				 }
			 }
		  }else{
			  $scope.cusSr = "无"; 
		  }
		//关联产品
		  if(cus_pro != "no"){
			  cus_pro = cus_pro.split('@G@');
			  $http.post('./cus_findProductAll.action',{iscounts: 1},$scope.postCfg).success(function(data){
		    		if(data != null && data != "" && data != undefined){
		    			for(var i = 0; i < data.length; i++){
			   				 for(var j = 0; j < cus_pro.length; j++){
			   					 if(cus_pro[j] == data[i].id){
			   						$scope.cusPro += data[i].name+",";
			   						 break;
			   					 }
			   				 }
		   			 	}
		    		}
		    		$scope.cusPro = $scope.cusPro.substring(0,$scope.cusPro.length-1);
		     	});
		  }else{
			  $scope.cusPro = "无"; 
		  }
		  //采购偏好
		  if(cus_pur != "no"){
			  cus_pur = cus_pur.split('@G@');
			  var jingzhun = "";
			  for(var i = 0; i < cus_pur.length; i++){
				  $scope.cusPur += cus_pur[i]+","
 			 }
			  if(cus_pur[0] == 1){
				  jingzhun = "精准"
					  $scope.cusPur = jingzhun+"###"+$scope.cusPur.replace('1,',"");
			  }else{
				  jingzhun = "不精准"
					  $scope.cusPur = jingzhun+"###"+$scope.cusPur.replace('0,',"");
			  }
		  }else{
			  $scope.cusPur = "无"; 
		  }
		  //入库时间
		  if(cus_entry != "no"){
			  var entryTime = cus_entry.split('@G@');
			  if(entryTime.length == 2){
				  $scope.cusEn = "开始时间:"+entryTime[0]+",结束时间:"+entryTime[1];
			  }else{
				  $scope.cusEn = "开始时间:"+entryTime[0];
			  }
		  }else{
			  $scope.cusEn = "无"; 
		  }
		  //联系时间
		  if(cus_contact != "no"){
			  var contactTime = cus_contact.split('@G@');
			  if(contactTime.length == 2){
				  $scope.cuslink = "开始时间:"+contactTime[0]+",结束时间:"+contactTime[1];
			  }else{
				  $scope.cuslink = "开始时间:"+contactTime[0];
			  }
		  }else{
			  $scope.cuslink = "无"; 
		  }
		  //未跟进时间
		  if(cus_nofollow != "no"){
			  if(cus_nofollow == "7"){
				  $scope.cusnofollow = "7天内"
			  }else if(cus_nofollow == "30"){
				  $scope.cusnofollow = "30天内";
			  }else{
				  var followTime = cus_nofollow.split('@G@')[1].split(',');
				  if(followTime.length == 2){
					  $scope.cusnofollow = "开始时间:"+followTime[0]+",结束时间:"+followTime[1];
				  }else{
					  $scope.cusnofollow = "开始时间:"+followTime[0];
				  }
			  }
		  }else{
			  $scope.cusnofollow = "无"; 
		  }
    	
    	$('#dialog-more').dialog({
    		position: ["center", 100],
            modal: true,
            resizable: false,
            width: 800,
            maxHeight: 600,
            close:function(){
                $(this).dialog("destroy");
            },
            buttons: {
                "关闭": function () {
                	$(this).dialog("destroy");
                }
            }
        });
    }
}]);

App.controller('planaddCtrl', function ($scope,$state,$rootScope,$http, $location,TemplateList,TempPost,MarketingPlan) {
    'use strict';
    $scope.oldChecked = ['0']; //存储选中的条件
    $scope.allClassifylist = []; //所有的客户分类
    $scope.classifylist = []; //显示在页面的客户分类
    $scope.statelist = []; //客户状态
    $scope.fromlist = []; //客户来源
    $scope.allProlist = []; //所有的关联产品
    $scope.prolist = []; //关联产品
    $scope.purchaselist = [];//采购偏好
    $scope.pvalue = ""; //选择采购偏好更多拼接
    $scope.jingzhun = 0;//是否精准
    $scope.mySeaCount = 0;//私海客户数量
    $scope.publicSeaCount = 0;//公海客户数量
    $scope.selectPro = ""; //选择关联产品更多拼接
    
    if($rootScope.userType == 0){ //0易外销用户(企业开通了客户管理模块)
    	$(".yyloading").show();
      	$http.post('./cus_findClassifyAll.action',{iscounts: 1},$scope.postCfg).success(function(data){
      		//成功之后显示数据
      		$(".yyloading").hide();
      		$rootScope.crmtype = 1;
      		$scope.typeitemscrm = data;
      		$scope.typeitems = null;//当前数据加载时,本地库地址清掉
      	});
    }else{ //1营销邮用户(企业未开通客户管理模块)
    	$(".yyloading").show();
        $http.post('./type_findFolderAddr.action', {}, $scope.postCfg).success(function (data) {
            //成功之后做一些事情
        	$(".yyloading").hide();
        	$rootScope.crmtype = 0;
            $scope.typeitems = data;
            $scope.typeitemscrm = null;//当前数据加载时,CRM库地址清掉
        });
    }
    //点击按钮加载本地库 
    $scope.getlocal = function(i){
 	   $rootScope.crmtype=i;
    }
    //本地库地址分类
//    $scope.typesort = function () {
//    	$(".yyloading").show();
//        $http.post('./type_findFolderAddr.action', {}, $scope.postCfg).success(function (data) {
//            //成功之后做一些事情
//        	var plan_differen = $("#local").val();//获取参数
//            $scope.typeitems = data;
//            $(".yyloading").hide();
//            $scope.typeitemscrm = null;//当前数据加载时,CRM库地址清掉
//        });
//    };
//    $scope.typesort();//开始默认加载本地数据
   
//   $scope.getcrm = function(i){
//	   $scope.typeCRMsort(i);
//	   $rootScope.crmtype=0;
//   }
    
    //CRM库地址分类-客户分类
   $scope.typeCRMsort = function(){
		$(".yyloading").show();
    	$http.post('./cus_findClassifyAll.action',{iscounts: 1},$scope.postCfg).success(function(data){
    		//成功之后显示数据
    		$scope.typeitemscrm = data;
    		$(".yyloading").hide();
    		$scope.typeitems = null;//当前数据加载时,本地库地址清掉
    	});
    };
    //客户状态
    $scope.customerStatus = function(){
 	   $(".yyloading").show();
     	$http.post('./cus_findStatusAll.action',{iscounts: 1},$scope.postCfg).success(function(data){
     		//成功之后显示数据
     		$scope.typeitemscrm = data;
     		$(".yyloading").hide();
     		$scope.typeitems = null;//当前数据加载时,本地库地址清掉
     	});
     };
     //客户来源
     $scope.customerFrom = function(){
  	   $(".yyloading").show();
      	$http.post('./cus_findFromAll.action',{iscounts: 1},$scope.postCfg).success(function(data){
      		//成功之后显示数据
      		$scope.typeitemscrm = data;
      		$(".yyloading").hide();
      		$scope.typeitems = null;//当前数据加载时,本地库地址清掉
      	});
      };
      //关联产品
      $scope.findProduct = function(){
   	   $(".yyloading").show();
       	$http.post('./cus_findProductAll.action',{iscounts: 1},$scope.postCfg).success(function(data){
       		//成功之后显示数据
       		$scope.typeitemscrm = data;
       		$(".yyloading").hide();
       		$scope.typeitems = null;//当前数据加载时,本地库地址清掉
       	});
       };
   //采购偏好
   $scope.findPurchaseInfo = function(){
	   $(".yyloading").show();
	   var arr = [];
	   var pdata={
            condition:1,
	    }; 
		MarketingPlan.getPurchaselist(pdata).then(function(data){
			//成功之后显示数据
    		var res = data.industries;
    		for(var i = 0; i < res.length; i++){
    			arr.push({
        			name:res[i].name,
        			counts:res[i].nums,
        			id:res[i].id,
        		})
    		}
    		$scope.typeitemscrm = arr;
    		$(".yyloading").hide();
    		$scope.typeitems = null;//当前数据加载时,本地库地址清掉
		})
    };
    //获取个性营销所需要的数据
    $scope.findPerNeedData = function(){
    	//客户类型-私海
    	$http.post('./cus_getMyCustomerCounts.action',$scope.postCfg).success(function(data){
    		$scope.mySeaCount = data;
    	});
    	//客户类型-公海
    	$http.post('./cus_getPubilcCustomerCounts.action',$scope.postCfg).success(function(data){
    		$scope.publicSeaCount = data;
    	});
    	//分类
    	$http.post('./cus_findClassifyAll.action',{iscounts: 0},$scope.postCfg).success(function(data){
    		var cusClassifyList = data;
    		$scope.allClassifylist = data;
    		var classifyValue = $('input:radio[name="cusSea"]:checked').val();
    		if(classifyValue == 1){ //表示选中公海客户
    			$.each(cusClassifyList,function(i,row){
    				if(row.is_yingxiao == 1){
    					$scope.classifylist.push({
    						id:row.id,
    						name:row.name
    					})
    				}
    			})
    		}else{  //私海客户
    			$scope.classifylist = cusClassifyList;
    		}
    	});
    	//状态
    	$http.post('./cus_findStatusAll.action',{iscounts: 0},$scope.postCfg).success(function(data){
     		$scope.statelist = data;
     	});
    	//来源
    	$http.post('./cus_findFromAll.action',{iscounts: 0},$scope.postCfg).success(function(data){
      		$scope.fromlist = data;
      	});
    	//关联产品
    	$http.post('./cus_findProductAll.action',{iscounts: 0},$scope.postCfg).success(function(data){
       		$scope.allProlist = data;
       		var res = data;
    		$scope.prolist = res.slice(0,5);
       	});
    	//采购偏好
    	$(".yyloading").show();
    	$http.post('./cus_findIndustriesAll.action',{condition: 1},$scope.postCfg).success(function(data){
    		$(".yyloading").hide();
    		var res = data.industries;
    		$scope.purchaselist2 = res.slice(0,5);
    	});
    };
    
    //清空选中的值
    $scope.emptySelected = function(){
    	$("input[name='cusClassify-1']").prop("checked",false);
    	$("input[name='cusState-1']").prop("checked",false);
    	$("input[name='cusFrom-1']").prop("checked",false);
    	$("input[name='cusStar-1']").prop("checked",false);
    	$("input[name='cusPro-1']").prop("checked",false);
    	$("input[name='personality-1']").prop("checked",false);
    	$("#beginentrytime").val("");
    	$("#endentrytime").val("");
    	$("#beginlinktime").val("");
    	$("#endlinktime").val("");
    	$("input[name='nofollow-1']").prop("checked",false);
    	$("#beginfollowtime").val("");
    	$("#endfollowtime").val("");
    	$scope.pvalue = "";
    	$scope.selectPro = "";
    	$("#selectshow").html("");
    	$("input[name='purchase-1']").prop("checked",false);
    	$("#selectshow2").html("");
    	$("input[name='mainPro-1']").prop("checked",false);
    	if($rootScope.is_yunying == 1){
    		$("input:radio[name=cusSea][value=1]").attr("checked",true);  
    	}
    };
    //个性营销
    $scope.findPersonalityInfo = function(){
    	$scope.allProlist = [];
    	$scope.classifylist = [];
    	$scope.emptySelected();//清空选中
    	$scope.findPerNeedData(); //获取需要的数据
    	if($rootScope.is_yunying == 1){
    		$("input:radio[name=cusSea][value=1]").attr("checked",true);  
    	}
    	$('#dialog-personality').dialog({
    		position: ["center", 100],
            modal: true,
            resizable: false,
            width: 800,
            maxHeight: 600,
            close:function(){
            	//获取之前选中 的值
            	var checkValue = $scope.oldChecked[$scope.oldChecked.length-2];
            	$(":radio[name='cus-classify-1'][value='" + checkValue + "']").prop("checked", "checked");
                $(this).dialog("destroy");
            },
            buttons: {
                "查询": function () {
                	$scope.purchaseHobbyInfo();
                },
                "重置": function () {
                	$scope.emptySelected();//清空选中
                }
            }
        });
    };
    //切换客户类型
    $scope.radioChecked = function(k){
    	var classifyInfos = $scope.allClassifylist;
    	$scope.classifylist = [];
    	if(k == 0){  //私有客户
    		$scope.classifylist = classifyInfos;
        }else{  //公海
        	$.each(classifyInfos,function(i,row){
				if(row.is_yingxiao == 1){
					$scope.classifylist.push({
						id:row.id,
						name:row.name
					})
				}
			})
        }
    };
    //确认采购偏好数据
    $scope.purchaseHobbyInfo = function(){
    	//获取选中的客户分类
    	var classify_value = "";
        $('input[name="cusClassify-1"]:checked').each(function(){
        	classify_value += $(this).val()+",";
        });
        if(classify_value != ""){ //选中了
        	classify_value = classify_value.substring(0,classify_value.length-1);
        }else{  //没有选中
        	$('input[name="cusClassify-1"]').each(function(){
             	classify_value += $(this).val()+",";
             });
        	classify_value = classify_value.substring(0,classify_value.length-1);
        	//classify_value = "no";
        }
    	//获取选中的客户状态
        var state_value = "";
        $('input[name="cusState-1"]:checked').each(function(){
        	state_value += $(this).val()+",";
        });
        if(state_value != ""){
        	state_value = state_value.substring(0,state_value.length-1);
        }else{
        	state_value = "no";
        }
    	//获取选中的客户来源
        var from_value = "";
        $('input[name="cusFrom-1"]:checked').each(function(){
        	from_value += $(this).val()+",";
        });
        if(from_value != ""){
        	from_value = from_value.substring(0,from_value.length-1);
        }else{
        	from_value = "no";
        }
    	//获取选中的客户星级
        var star_value = "";
        $('input[name="cusStar-1"]:checked').each(function(){
        	star_value += $(this).val()+",";
        });
        if(star_value != ""){
        	star_value = star_value.substring(0,star_value.length-1);
        }else{
        	star_value = "no";
        }
    	//获取选中的关联产品
        var pro_value = "";
        $('input[name="cusPro-1"]:checked').each(function(){
        	pro_value += $(this).val()+"@G@";
        });
        if($scope.selectPro == ""){
        	if(pro_value != ""){
            	pro_value = pro_value.substring(0,pro_value.length-3);
            }else{
            	pro_value = "no";
            }
        }else{
        	pro_value = $scope.selectPro;
        }
    	//获取选中的采购偏好
        var pur_value = "";
        $('input[name="personality-1"]:checked').each(function(){
        	pur_value += $(this).val()+"@G@";
        });
        if(pur_value == "" && $scope.pvalue == ""){
        	pur_value = "no";
        }else{
        	if($scope.jingzhun == 1){ //精准
        		pur_value = 1+"@G@"+pur_value;
        	}else{
        		pur_value = 0+"@G@"+pur_value;
        	}
        	if(pur_value == "" && $scope.pvalue != ""){
        		pur_value = $scope.pvalue;
        	}else{
        		pur_value = pur_value+$scope.pvalue.substring(4);
        	}
        	pur_value = pur_value.substring(0,pur_value.length-3);
        }
    	//获取选中的入库时间
        var entryTiem = "no";
        var beginentrytime = $("#beginentrytime").val();
        var endentrytime = $("#endentrytime").val();
        if(endentrytime != "" && beginentrytime == ""){
    		$scope.tipshow(0, '入库开始时间不能为空!');
    		return false;
        }
        //判断两个时间的大小
        var ebtt = new Date(beginentrytime.replace(/\-/g, "\/"));  
        var eett = new Date(endentrytime.replace(/\-/g, "\/"));  
        if(ebtt.getTime() > eett.getTime()){
        	$scope.tipshow(0, '入库开始时间不能大于结束时间!');
    		return false;
        }
        //判断开始时间不为空结束时间为空
        if(beginentrytime == "" && endentrytime == ""){
        	entryTiem = "no";
        }else{
        	if(endentrytime == ""){
            	entryTiem = beginentrytime;
            }else{
            	entryTiem = beginentrytime+"@G@"+endentrytime;
            }
        }
    	//获取选中的联系时间
        var contactTiem = "no";
        var beginlinktime = $("#beginlinktime").val();
        var endlinktime = $("#endlinktime").val();
        if(endlinktime != "" && beginlinktime == ""){
    		$scope.tipshow(0, '联系开始时间不能为空!');
    		return false;
        }
        //判断两个时间的大小
        var cbtt = new Date(beginlinktime.replace(/\-/g, "\/"));  
        var cett = new Date(endlinktime.replace(/\-/g, "\/"));  
        if(cbtt.getTime() > cett.getTime()){
        	$scope.tipshow(0, '联系开始时间不能大于结束时间!');
    		return false;
        }
        //判断开始时间不为空结束时间为空
        if(beginlinktime == "" && endlinktime == ""){
        	contactTiem = "no";
        }else{
        	if(endlinktime == ""){
        		contactTiem = beginlinktime;
            }else{
            	contactTiem = beginlinktime+"@G@"+endlinktime;
            }
        }
    	//获取选中的未跟进时间
        var nofollowday = $('input[name="nofollow-1"]:checked').val();//获取选中的时间
        var beginfollowtime = $("#beginfollowtime").val();
        var endfollowtime = $("#endfollowtime").val();
        var nofollow = "no";
        if(nofollowday != undefined){
        	if(nofollowday == 7 || nofollowday == 30){//7天未跟进 、30天未跟进
        		nofollow = nofollowday;
        	}else{ //自定义
        		if(beginfollowtime == ""){
        			$scope.tipshow(0, '未跟进开始时间不能为空!');
            		return false;
        		}
        		//判断两个时间的大小
                var fbtt = new Date(beginfollowtime.replace(/\-/g, "\/"));  
                var fett = new Date(endfollowtime.replace(/\-/g, "\/"));  
                if(fbtt.getTime() > fett.getTime()){
                	$scope.tipshow(0, '未跟进开始时间不能大于结束时间!');
            		return false;
                }
        		 //判断开始时间不为空结束时间为空
                if(beginfollowtime == "" && endfollowtime == ""){
                	nofollow = "no";
                }else{
                	if(endfollowtime == ""){
                		nofollow = nofollowday+"@G@"+beginfollowtime;
                    }else{
                    	nofollow = nofollowday+"@G@"+beginfollowtime+","+endfollowtime;
                    }
                }
        	}
        }
        //客户类型
        var cusType = $("input[name='cusSea']:checked").val();
        var paramValue = classify_value+"@espeed@"+state_value+"@espeed@"+from_value+"@espeed@"+
        star_value+"@espeed@"+pro_value+"@espeed@"+pur_value+"@espeed@"+entryTiem+"@espeed@"+
        contactTiem+"@espeed@"+nofollow+"@espeed@"+cusType;
        $rootScope.other_name = paramValue;
        if(classify_value != "no" || state_value != "no" || from_value != "no" || 
        		star_value != "no" || pro_value != "no" || pur_value != "no" ||
        		entryTiem != "no" || contactTiem != "no" || nofollow != "no"){
        	var arr = [];
        	$(".yyloading").show();
        	 $http.post('./cus_findCustomerByPersonSaleCounts.action',{
              	"highSearchValue":paramValue
              },$scope.postCfg).success(function(data){
            	  $rootScope.tableTitle = "个性营销";
            	  if(data > 0){
            		  var param_str = "";
            		  param_str = paramValue.split("@espeed@");
            		  var cus_classify = param_str[0]; //客户分类
            		  var cus_state = param_str[1]; //客户状态
            		  var cus_from = param_str[2];//客户来源
            		  var cus_star = param_str[3];//客户星级
            		  var cus_pro = param_str[4];//关联产品
            		  var cus_pur = param_str[5];//采购偏好
            		  var cus_entry = param_str[6];//入库时间
            		  var cus_contact = param_str[7];//联系时间
            		  var cus_nofollow = param_str[8];//未跟进时间
            		  var cus_type = param_str[9];//客户类型
            		  var cus_classify_name = "";
            		  var cus_state_name = "";
            		  var cus_from_name = "";
            		  var cus_star_name = "";
            		  var cus_pro_name = "";
            		  var cus_pur_name = "";
            		  var cus_entry_name = "";
            		  var cus_contact_name = "";
            		  var cus_follow_name = "";
            		  if(cus_type == 1){
            			  cus_classify_name = "公海客户";
            		  }else{
            			  cus_classify_name = "私海客户";
            		  }
            		  //客户分类
            		  if(cus_classify != "no"){
            			  cus_classify = cus_classify.split(',');
            			 for(var i = 0; i < $scope.classifylist.length; i++){
            				 for(var j = 0; j < cus_classify.length; j++){
            					 if(cus_classify[j] == $scope.classifylist[i].id){
            						 cus_classify_name += $scope.classifylist[i].name+",";
            						 break;
            					 }
            				 }
            			 } 
            		  }else{
            			  cus_classify_name = "no"; 
            		  }
            		//客户状态
            		  if(cus_state != "no"){
            			  cus_state = cus_state.split(',');
            			 for(var i = 0; i < $scope.statelist.length; i++){
            				 for(var j = 0; j < cus_state.length; j++){
            					 if(cus_state[j] == $scope.statelist[i].id){
            						 cus_state_name += $scope.statelist[i].name+",";
            						 break;
            					 }
            				 }
            			 } 
            		  }else{
            			  cus_state_name = "no"; 
            		  }
            		//客户来源
            		  if(cus_from != "no"){
            			  cus_from = cus_from.split(',');
            			 for(var i = 0; i < $scope.fromlist.length; i++){
            				 for(var j = 0; j < cus_from.length; j++){
            					 if(cus_from[j] == $scope.fromlist[i].id){
            						 cus_from_name += $scope.fromlist[i].name+",";
            						 break;
            					 }
            				 }
            			 } 
            		  }else{
            			  cus_from_name = "no"; 
            		  }
            		//客户星级
            		  if(cus_star != "no"){
            			  cus_star = cus_star.split(',');
            			 for(var i = 0; i < cus_star.length; i++){
            				 if(cus_star[i] == 0){
            					 cus_star_name = "无星级,";
            				 }else if(cus_star[i] == 1){
            					 cus_star_name = cus_star_name+"一星级,";
            				 }else if(cus_star[i] == 2){
            					 cus_star_name = cus_star_name+"二星级,";
            				 }else if(cus_star[i] == 3){
            					 cus_star_name = cus_star_name+"三星级,";
            				 }else if(cus_star[i] == 4){
            					 cus_star_name = cus_star_name+"四星级,";
            				 }else if(cus_star[i] == 5){
            					 cus_star_name = cus_star_name+"五星级,";
            				 }
            			 }
            		  }else{
            			  cus_star_name = "no"; 
            		  }
            		//关联产品
            		  if(cus_pro != "no"){
            			  cus_pro = cus_pro.split('@G@');
            			 for(var i = 0; i < $scope.prolist.length; i++){
            				 for(var j = 0; j < cus_pro.length; j++){
            					 if(cus_pro[j] == $scope.prolist[i].id){
            						 cus_pro_name += $scope.prolist[i].name+",";
            						 break;
            					 }
            				 }
            			 } 
            		  }else{
            			  cus_pro_name = "no"; 
            		  }
            		  //采购偏好
            		  if(cus_pur != "no"){
            			  cus_pur = cus_pur.split('@G@');
            			  var jingzhun = "";
            			  for(var i = 0; i < cus_pur.length; i++){
             				cus_pur_name += cus_pur[i]+","
             			 }
            			  if(cus_pur[0] == 1){
            				  jingzhun = "精准"
            					  cus_pur_name = jingzhun+"###"+cus_pur_name.replace('1,',"");
            			  }else{
            				  jingzhun = "不精准"
            					  cus_pur_name = jingzhun+"###"+cus_pur_name.replace('0,',"");
            			  }
            		  }else{
            			  cus_pur_name = "no"; 
            		  }
            		  //入库时间
            		  if(cus_entry != "no"){
            			  cus_entry_name = cus_entry.replace('@G@',',');
            		  }else{
            			  cus_entry_name = "no"; 
            		  }
            		  //联系时间
            		  if(cus_contact != "no"){
            			  cus_contact_name = cus_contact.replace('@G@',',');
            		  }else{
            			  cus_contact_name = "no"; 
            		  }
            		  //未跟进时间
            		  if(cus_nofollow != "no"){
            			  if(cus_nofollow == "7"){
            				  cus_follow_name = "7天内"
            			  }else if(cus_nofollow == "30"){
            				  cus_follow_name = "30天内";
            			  }else{
            				  cus_follow_name = cus_nofollow.split('@G@')[1];
            			  }
            		  }else{
            			  cus_follow_name = "no"; 
            		  }
            		  var totol_name = "";
            		  if(cus_classify_name != "no"){
            			  cus_classify_name = cus_classify_name.substring(0,cus_classify_name.length-1);
            			  totol_name = "客户分类:"+cus_classify_name+";";
            		  }
            		  if(cus_state_name != "no"){
            			  cus_state_name = cus_state_name.substring(0,cus_state_name.length-1);
            			  totol_name = totol_name+"客户状态:"+cus_state_name+";";
            		  }
            		  if(cus_from_name != "no"){
            			  cus_from_name = cus_from_name.substring(0,cus_from_name.length-1);
            			  totol_name = totol_name+"客户来源:"+cus_from_name+";";
            		  }
            		  if(cus_star_name != "no"){
            			  cus_star_name = cus_star_name.substring(0,cus_star_name.length-1);
            			  totol_name = totol_name+"客户星级:"+cus_star_name+";";
            		  }
            		  if(cus_pro_name != "no"){
            			  cus_pro_name = cus_pro_name.substring(0,cus_pro_name.length-1);
            			  totol_name = totol_name+"关联产品:"+cus_pro_name+";";
            		  }
            		  if(cus_pur_name != "no"){
            			  cus_pur_name = cus_pur_name.substring(0,cus_pur_name.length-1);
            			  totol_name = totol_name+"采购偏好:"+cus_pur_name+";";
            		  }
            		  if(cus_entry_name != "no"){
            			  totol_name = totol_name+"入库时间:"+cus_entry_name+";";
            		  }
            		  if(cus_contact_name != "no"){
            			  totol_name = totol_name+"联系时间:"+cus_contact_name+";";
            		  }
            		  if(cus_follow_name != "no"){
            			  totol_name = totol_name+"未跟进时间:"+cus_follow_name+";";
            		  }
            		  arr.push({
            			  name:totol_name,
            			  counts:data
            		  })  
            		  $scope.typeitemscrm = arr;
            	  }else{
            		  $scope.typeitemscrm = ""; 
            	  }
            	  $(".yyloading").hide();
          	});
        	 $('#dialog-personality').dialog("destroy");
        }else{
        	$scope.tipshow(0, '请选择查询条件!');
        }
    };
    
  //加载关联产品更多
    $scope.loadProductMore = function(){
    	$('#dialog-mainProduct').dialog({
    		position: ["center", 100],
            modal: true,
            resizable: false,
            width: 750,
            maxHeight: 450,
            close:function(){
            	//获取之前选中 的值
                $(this).dialog("destroy");
            },
            buttons: {
                "确认": function () {
                	var str_value = "";
                	var str_title = "";
                	$scope.selectPro = "";
                    $('input[name="mainPro-1"]:checked').each(function(){
                    	str_value += $(this).val()+"@G@";
                    	str_title += $(this).attr('proname')+",";
                    });
                    if(str_value != ""){
                    	$scope.selectPro = str_value = str_value.substring(0,str_value.length-3);
                    	str_title = str_title.substring(0,str_title.length-1);
                    	$("#selectshow2").html("您已选择了   <span style='color:red;'>"+str_title+"</span>");
                    	var str = str_value.split('@G@');
                        str_value = "已选择了"+str.length+"个";
                    }else{
                    	str_value = "请选择";
                    	$("#selectshow2").html("")
                    }
                    $("#moreTitle2").attr('title',str_value);
                    $(this).dialog("destroy");
                },
                "取消": function () {
                	$scope.selectPro = "";
                	$("#selectshow2").html("");
                	$("#moreTitle2").attr('title','请选择');
                	$("input[name='mainPro-1']").prop("checked",false);
                    $(this).dialog("destroy");
                }
            }
        });
    };
    
    //点击更多获取采购偏好
    $scope.findPurchaseMoreData = function(pdata){
   	 $(".yyloading").show();
   	 MarketingPlan.getPurchaselist(pdata).then(function(data){
   		 $(".yyloading").hide();
   		$scope.purchaselist = data.industries;
	 		$scope.TotalItems = data.pagebean.totalRecord;
		})
    };
    
    //插入模板分页
    $scope.CurrentPage=1;
    $scope.numPages = 1;
    $scope.maxSize = 5;
    $scope.setPage = function (pageNo) {
        $scope.numPages = pageNo;
    };
    $scope.pageChanged2 = function () {
    	$("input[name='purchase-1']").prop("checked",false);
    	var pdata={
            condition:2,
            currpage:$scope.CurrentPage,
        };
    	$scope.findPurchaseMoreData(pdata);//获取偏好数据
     };
    //加载采购偏好更多
    $scope.loadPurchaseMore = function(){
    	var pdata={
            condition:2,
            currpage:1,
         };
    	$scope.findPurchaseMoreData(pdata);//获取偏好数据
    	$('#dialog-purchaseHobby').dialog({
    		position: ["center", 100],
            modal: true,
            resizable: false,
            width: 750,
            maxHeight: 450,
            close:function(){
            	//获取之前选中 的值
                $(this).dialog("destroy");
            },
            buttons: {
                "确认": function () {
                	if($('input:checkbox[name="isSure"]').is(":checked")){ //选中
                		$scope.jingzhun = 1;
                	}
                	$scope.pvalue = "";
                	var str_value = ""; //title
                    $('input[name="purchase-1"]:checked').each(function(){
                    	$scope.pvalue += $(this).val()+"@G@";
                    	str_value += $(this).val()+",";
                    });
                    $scope.pvalue = $scope.jingzhun+"@G@"+ $scope.pvalue;
                    if(str_value != ""){
                    	str_value = str_value.substring(0,str_value.length-1);
                    	$("#selectshow").html("您已选择了   <span style='color:red;'>"+str_value+"</span>");
                    	var str = str_value.split(',');
                        str_value = "已选择了"+str.length+"个";
                    }else{
                    	str_value = "请选择";
                    	$("#selectshow").html("")
                    }
                    $("#moreTitle").attr('title',str_value);
                    $(this).dialog("destroy");
                },
                "取消": function () {
                	$scope.pvalue = "";
                	$("#selectshow").html("");
                	$("#moreTitle").attr('title','请选择');
                	$("input[name='purchase-1']").prop("checked",false);
                    $(this).dialog("destroy");
                }
            }
        });
    };
    
    //采购偏好查询
    $scope.purchaseBtn = function(){
    	$scope.CurrentPage=1;
    	$scope.numPages = 1;
    	var conditionValue = $("#purchasehobby").val();
    	var pdata={
            condition:3,
            conditionValue:conditionValue,
        };
    	$(".yyloading").show();
    	$http.post('./cus_findIndustriesAll.action',pdata,$scope.postCfg).success(function(data){
    		$(".yyloading").hide();
    		$scope.purchaselist = data.industries;
    		$scope.TotalItems = data.pagebean.totalRecord;
    	});
    };
    //重置采购偏好
    $scope.purchaseReset = function(){
    	$("#purchasehobby").val('');
    	var pdata={
            condition:2,
            currpage:1,
         };
    	$scope.findPurchaseMoreData(pdata);//获取偏好数据
    };
    //本地库
    $scope.localRunNow = function(id){
    	var pdata = {
			currpage:1,
			pagesize:9999,
			condition:1,
			conditionvalue:id
    	}
    	$(".yyloading").show();
    	$http.post('./addr_findAddressByCondition.action',pdata,$scope.postCfg).success(function(data){
    		$(".yyloading").hide();
    		var emails = "";
    		for(var i = 0; i < data.addresslist.length; i++){
    			emails += data.addresslist[i].user_addr_email+",";
    		}
        	if(emails==""){//无客户信息
        		$rootScope.tipshow(0,"无邮件地址信息");
        	}else{
        		$rootScope.runType = 1;
        		emails = emails.substring(0,emails.length-1);
        		$state.go('app.email',{'emails':emails});
        	}
    	});
    };
    //CRM库立即执行
    $scope.crmRunNow = function(id,name){
    	var customerids = "";//客户id,多个以逗号分割
    	if($rootScope.crmtype == 1){ //客户分类
    		$(".yyloading").show();
    		$http.post('./cus_findCustomersByClassify.action',{classifyid:id},$scope.postCfg).success(function(data){
    			$(".yyloading").hide();
    			for(var i = 0; i < data.length; i++){
        			customerids += 	data[i].customer_id+",";
        		}
            	if(customerids==""){//无客户信息
            		$rootScope.tipshow(0,"无客户信息");
            	}else{
            		$rootScope.runType = 2;
            		customerids = customerids.substring(0,customerids.length-1);
            		$state.go('app.email',{'customerid':customerids});
            	}
        	});
    	}else if($rootScope.crmtype == 3){ //客户状态
    		$(".yyloading").show();
    		$http.post('./cus_findCustomersByStatus.action',{statusid:id},$scope.postCfg).success(function(data){
    			$(".yyloading").hide();
    			for(var i = 0; i < data.length; i++){
        			customerids += 	data[i].customer_id+",";
        		}
            	if(customerids==""){//无客户信息
            		$rootScope.tipshow(0,"无客户信息");
            	}else{
            		$rootScope.runType = 2;
            		customerids = customerids.substring(0,customerids.length-1);
            		$state.go('app.email',{'customerid':customerids});
            	}
        	});
    	}else if($rootScope.crmtype == 5){ //客户来源
    		$(".yyloading").show();
    		$http.post('./cus_findCustomersByFrom.action',{fromid:id},$scope.postCfg).success(function(data){
    			$(".yyloading").hide();
    			for(var i = 0; i < data.length; i++){
        			customerids += 	data[i].customer_id+",";
        		}
            	if(customerids==""){//无客户信息
            		$rootScope.tipshow(0,"无客户信息");
            	}else{
            		$rootScope.runType = 2;
            		customerids = customerids.substring(0,customerids.length-1);
            		$state.go('app.email',{'customerid':customerids});
            	}
        	});
    	}else if($rootScope.crmtype == 7){ //关联产品
    		$(".yyloading").show();
    		$http.post('./cus_findCustomersByProduct.action',{productid:id},$scope.postCfg).success(function(data){
    			$(".yyloading").hide();
    			for(var i = 0; i < data.length; i++){
        			customerids += 	data[i].customer_id+",";
        		}
            	if(customerids==""){//无客户信息
            		$rootScope.tipshow(0,"无客户信息");
            	}else{
            		$rootScope.runType = 2;
            		customerids = customerids.substring(0,customerids.length-1);
            		$state.go('app.email',{'customerid':customerids});
            	}
        	});
    	}else if($rootScope.crmtype == 9){ //采购偏好
    		$(".yyloading").show();
    		$http.post('./cus_findCustomersByIndustries.action',{caigou:name},$scope.postCfg).success(function(data){
    			$(".yyloading").hide();
    			for(var i = 0; i < data.length; i++){
        			customerids += 	data[i].customer_id+",";
        		}
            	if(customerids==""){//无客户信息
            		$rootScope.tipshow(0,"无客户信息");
            	}else{
            		$rootScope.runType = 2;
            		customerids = customerids.substring(0,customerids.length-1);
            		$state.go('app.email',{'customerid':customerids});
            	}
        	});
    	}else if($rootScope.crmtype == 11){ //个性营销
    		$(".yyloading").show();
    		$http.post('./cus_findCustomerByPersonSaleList.action',{highSearchValue:$rootScope.other_name},$scope.postCfg).success(function(data){
    			$(".yyloading").hide();
    			for(var i = 0; i < data.length; i++){
        			customerids += 	data[i].customer_id+",";
        		}
            	if(customerids==""){//无客户信息
            		$rootScope.tipshow(0,"无客户信息");
            	}else{
            		$rootScope.runType = 2;
            		customerids = customerids.substring(0,customerids.length-1);
            		$state.go('app.email',{'customerid':customerids});
            	}
        	});
    	}
    };
    //添加模板
    $scope.temptypelist=function(i) {
        TempPost.gettypelist({
            condition:i
        }).then(function(data){
            $scope.usertypes=data;
        })
    };
  //插入模板分页
    $scope.CurrentPage=1;
    $scope.numPages = 1;
    $scope.maxSize = 5;
    $scope.setPage = function (pageNo) {
        $scope.numPages = pageNo;
    };
    $scope.pageChanged = function () {
    	var pdata = {};
        if($rootScope.levelType == 2){//企业
        	 pdata={
        	    condition:2,
	            conditionvalue:"",
	            currpage:$scope.CurrentPage,
	            pagesize:20
             };
        }else if($rootScope.levelType == 3){ //个人
        	pdata={
    		    condition:3,
	            conditionvalue:"",
	            currpage:$scope.CurrentPage,
	            pagesize:20
             };
        }
        $scope.temphomelist(pdata);
     };
    
    
    $scope.temphomelist=function(pdata){
    	$scope.templistitems = [];
    	$(".yyloading").show();
        TemplateList.getlist(pdata).then(function(data){
        	$(".yyloading").hide();
        	var stencillist = data.stencillist;
        	if(stencillist!= null && stencillist != "" && stencillist != undefined){
        		$.each(stencillist,function(i,row){
            		var temp_thumbnail = row.stencil_thumbnail;
            		if(row.stencil_thumbnail == null || row.stencil_thumbnail == "" || row.stencil_thumbnail == undefined){
            			temp_thumbnail = row.stencil_pic;
            		}
            		$scope.templistitems.push({
        				temp_thumbnail:temp_thumbnail,
        				stencil_id:row.stencil_id,
        				stencil_name:row.stencil_name,
        			})
            	})
        	}
        	$scope.TotalItems = data.pagebean.totalRecord;
        })
    };
    //企业
    $scope.comtemp=function(){
    	$rootScope.levelType = 2;
        $scope.tempname="企业模板";
        $scope.temptypelist(2);
        var pdata={
            condition:2,
            conditionvalue:"",
            currpage:1,
            pagesize:20
        };
        $scope.temphomelist(pdata);
    };
    //个人
    $scope.usertemp=function(){
    	$rootScope.levelType = 3;
        $scope.tempname="个人模板";
        $scope.temptypelist(3);
        var pdata={
            condition:3,
            conditionvalue:"",
            currpage:1,
            pagesize:20
        };
        $scope.temphomelist(pdata);
    };
    $scope.usertemp();//默认首先调用个人模板
    
  //特殊节假日提示语
    $scope.clicktag = function(){
    	$scope.tipshow(1,"特殊节假日,邮件将提前3天发送");
    };
});


App.directive('openPic', function (TempPost) {
    'use strict';

    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.on('click',function (e) {
                var opencheck = $(this).parent().parent().find('.photo-view');
                if (opencheck.attr('opencheck') == 0) {
                    opencheck.attr('opencheck', 1);
                    TempPost.info({
                        stencilid:attrs.planid
                    }).then(function(data){
                        if(data!=null && data!=""){
                            $("#showmodelid"+attrs.planid).attr("src",data.stencil_pic);
                        }

                    });
                    opencheck.show(500);
                } else {
                    opencheck.attr('opencheck', 0);
                    opencheck.hide(500);
                }
            });
        }
    };
})
    //按条件查询
    .directive('planTypeClick', function () {
        'use strict';

        return {
            restrict: 'AE',
            link: function (scope, element, attrs) {
                element.on('change',function(){
                    scope.getplan(1);
                });
            }
        };
    })
    .directive('tempLoadMore', function () {
    'use strict';

    return {
        restrict: 'AE',
        link: function (scope, element, attrs) {
            element.on('click',function(){
                scope.gettimeline(1,1);
            });
        }
    };
}).directive('planStatus', function () {
    'use strict';

    return {
        restrict: 'E',
        replace : true,
        scope:{
            statusid:'=statusid'
        },
        transclude : true,
        link: function (scope, element, attrs) {
            if (scope.statusid==0){
                element.html('<label class="label label-success">未执行</label>');
            }else if(scope.statusid==1){
                element.html('<label class="label label-default">已执行</label>');
            }
        }
    };
}).directive('delWeekDay', function ($http,$rootScope) {
    'use strict';

    return {
        restrict: 'A',
        scope:{
            delid:'=delWeekDay',
            gettimeline:'&'
        },
        link: function (scope, element, attrs) {
            element.on('click',function(){
                $http.post('./plan_delMarketingPlanDay.action', {
                    planid: scope.delid
                }, $rootScope.postCfg)
                    .success(function (data) {
                        if(parseInt(data)==1){
                            $rootScope.tipshow(1, "删除成功");
                            scope.gettimeline();
                        }else{
                            $rootScope.tipshow(0, "删除失败");
                        }
                    })
            })
        }
    };
}).directive('planclassify', function ($http,$rootScope) {
    'use strict';
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.click(function (e) {
                e.stopPropagation();
                var k = this.value;
                $rootScope.crmtype = k;
                if(k == 1){//客户分类
                	$rootScope.tableTitle = "客户分类";
                	scope.typeCRMsort();
                }else if(k == 3){ //客户状态
                	$rootScope.tableTitle = "客户状态";
                	scope.customerStatus();
                }else if(k == 5){ //客户来源
                	$rootScope.tableTitle = "客户来源";
                	scope.customerFrom();
                }else if(k == 7){ //关联产品
                	$rootScope.tableTitle = "关联产品";
                	scope.findProduct();
                }else if(k == 9){ //采购偏好
                	$rootScope.tableTitle = "采购偏好";
                	scope.findPurchaseInfo();
                }else if(k == 11){ //个性营销
                	scope.findPersonalityInfo();
                }
                scope.oldChecked.push(k)
            });
        }
    };
});