/**
 * Created by lgy on 2015/10/20.
 */ 
App.controller('addressCtrl', function ($rootScope, $scope, $state, $http, $location,GetUserinfo) {
    'use strict';
    //初始化参数
    $scope.erroradrress = [];
    $scope.planshow = 0;
    $scope.plantype = 0;
    $scope.weekshow = true;
    $scope.CurrentPage=1;
    $rootScope.hcalendar = [];
    //GetUserinfo.usertype().then(function(data){
    //    $scope.usertypes=data;
    //    console.log(data)
    //});

    //地址列表
    $scope.viewaddress = function (datapost) {
        $(".yyloading").show();
        $http.post('./addr_findAddressByCondition.action', datapost, $scope.postCfg)
            .success(function (data) {
                $(".yyloading").hide();
                $(".checkall").attr("allcheck", 0);
                $(".checkall").removeClass("checkbox-active");
                $scope.listitems = data.addresslist;
                $scope.TotalItems = data.pagebean.totalRecord;
            });
    };
    
    //分类查询
    $scope.typesort = function () {
        $http.post('./type_findFolderAll.action', {}, $scope.postCfg).success(function (data) {
            //成功之后做一些事情
            $scope.typeitems = data;
        });
    };
    $scope.typesort();
    
    $scope.showeidtmore=false;
    //展开更多信息
    $scope.showmorecon = function () {
        if($scope.showeidtmore){
            $scope.showeidtmore=false;
        }else{
            $scope.showeidtmore=true;
        }
    };
    //添加分类
    $scope.addtypeaddr = function (txt) {
        $http.post('./type_addUserFolder.action', {
            foldername: txt
        }, $scope.postCfg).success(function (data) {
            //成功之后做一些事情
            if (parseInt(data) == 1) {
                $scope.tipshow(1, "添加成功");
                $scope.typesort();
            } else {
                $scope.tipshow(0, "添加失败");
            }
        })
    };

   
    //地址详细信息
    $scope.readaddrinfo = function (id) {
        $scope.isshowmore=false;
        $http.post('./addr_findaddressinfo.action', {
            addressid: id
        }, $scope.postCfg).success(function (data) {
            //成功之后做一些事情
            $scope.addrinfo=data;
            $("#user_id").val(data.user_addr_id);
            $("#type_id").val(data.user_addr_type_id);
            $("#user_update_name").val(data.user_addr_name);
            $("#user_update_email").val(data.user_addr_email);
            $("#user_update_variable").val(data.user_addr_variable);
            $("#user_update_company").val(data.companyname);
            $("#user_update_web").val(data.user_addr_web);
            $("#addrdate").html(data.user_addr_add_date);
            $("#user_update_facebook").val(data.facebook);
            $("#user_update_twitter").val(data.twitter);
            $("#user_update_linkedin").val(data.linkedin);
            $("#user_update_pinterest").val(data.pinterest);
            $("#user_update_google").val(data.google);
            $("#user_update_tumblr").val(data.tumblr);
            $("#user_update_instagram").val(data.instagram);
            $("#user_update_vk").val(data.vk);

            if(data.user_addr_sex=='女'){
                $("input:radio[name=updatesex]").eq(1).attr("checked","checked");
            }else{
                $("input:radio[name=updatesex]").eq(0).attr("checked","checked");
            }
            $scope.showeidtmore=false;
            $("#dialog-addressinfooredit").dialog({
                position:["center", 100],
                modal: true,
                resizable: false,
                width: 550,
                close:function(){
                    $(this).dialog("destroy");
                },
                buttons: {
                    "编辑": function () {
                        if($scope.isshowmore){
                        var userid=$("#user_id").val();
                        var typeid=$("#type_id").val();
                        var user_name=$("#user_update_name").val();
                        var user_email=$("#user_update_email").val();
                        var user_variable=$("#user_update_variable").val();
                        var user_company=$("#user_update_company").val();
                        var user_web=$("#user_update_web").val();
                        var facebook=$("#user_update_facebook").val();
                        var twitter=$("#user_update_twitter").val();
                        var linkedin=$("#user_update_linkedin").val();
                        var pinterest=$("#user_update_pinterest").val();
                        var google=$("#user_update_google").val();
                        var tumblr=$("#user_update_tumblr").val();
                        var instagram=$("#user_update_instagram").val();
                        var vk=$("#user_update_vk").val();
                        if(user_web.indexOf('http')<0 && user_web!=""){
                            user_web='http://'+user_web
                        }
                        var user_sex=$("input:radio[name=updatesex]:checked").val();
                        if(user_sex==""){
                            user_sex='男';
                        }
                        $scope.addressaddandupdate(userid,typeid,user_name,user_email,user_variable,
                            user_company,user_web,user_sex,facebook,twitter,linkedin,pinterest,google,tumblr,instagram,vk);
                        //$(this).dialog("destroy");
                        }else{
                            $scope.isshowmore =true;
                            $scope.$apply();
                        }
                    },
                    "取消": function () {
                        $(this).dialog("destroy");
                    }
                }
            });

        });
    };

    //删除地址
    $scope.deladdr = function (ids) {
        $http.post('./addr_delYxyAddress.action', {
            addressidstr: ids
        }, $scope.postCfg).success(function (data) {
            //成功之后做一些事情
            if (parseInt(data) == 1) {
                var tid=$("#addresstypeid").val();
                $("#addresstypeid").val(tid)
                $scope.tipshow(1, "删除成功");
                $scope.viewaddress({
                    currpage: 1,
                    pagesize: $scope.pagesize,
                    condition: 1,
                    conditionvalue: tid
                });
            }
        })
    };

    //删除选中
    $scope.deladdrall = function () {
        var ids = "";
        $(".addrcheck").each(function () {
            if ($(this).attr("datafilecheck") == "1") {
                ids = $(this).attr("cid") + "," + ids
            }
        });
        ids = ids.substring(0, ids.length - 1);
        if (ids.length == 0) {
        	$scope.tipshow(0,"请选择邮件地址");
				return;
		}
        $("#dialog-addressip").dialog({
            modal: true,
            resizable: false,
            close:function(){
                $(this).dialog("destroy");
            },
            width: 350,
            buttons: {
                "确认删除": function () {
                	$scope.deladdr(ids);
                    $(this).dialog("destroy");
                },
                "取消": function () {
                    $(this).dialog("destroy");
                }
            }
        });
    };
   
    //添加地址信息
    $scope.addressaddandupdate = function (userid,typeid,name,email,variavle,company,web,sex,facebook,twitter,linkedin,pinterest,google,tumblr,instagram,vk) {

        if (name==""){
            $scope.tipshow(0, "姓名不能为空");
            return false;
        }
        if (email==""){
            $scope.tipshow(0, "邮件地址不能为空");
            return false;
        }
        $http.post('./addr_addEditAddress.action', {
            "address.user_addr_id": userid,
            "address.user_addr_type_id": typeid,
            "address.user_addr_name": name,
            "address.user_addr_email": email,
            "address.user_addr_variable": variavle,
            "address.companyname": company,
            "address.user_addr_web": web,
            "address.user_addr_sex": sex,
            "address.facebook": facebook,
            "address.twitter": twitter,
            "address.linkedin": linkedin,
            "address.pinterest": pinterest,
            "address.google": google,
            "address.tumblr": tumblr,
            "address.instagram": instagram,
            "address.vk": vk
        }, $scope.postCfg).success(function (data) {
            //成功之后做一些事情
            if(parseInt(data)==1){
            	//0:添加地址   否则:修改
                if(userid==0) {
                    $scope.tipshow(1, "添加地址成功");
                   // $scope.typesort();/重新加载分组数据
                    $("#dialog-manageaddress").dialog("destroy");
                }else{
                    $scope.tipshow(1, "修改地址成功");
                    $("#dialog-addressinfooredit").dialog("destroy");
                }
     /**-------------修改(手动添加地址时之后页面跳转到添加地址的页面)---之前----------------------------*/
                $("#addresstypeid").val(typeid);
                if(typeid == 0){
                	$scope.viewaddress({
                		 currpage:$scope.CurrentPage,
                         pagesize:$scope.pagesize,
                         condition:0,
                         conditionvalue:""
                	});
                }else{
                	$scope.viewaddress({
               		 	currpage:1,
                        pagesize:$scope.pagesize,
                        condition:1,
                        conditionvalue:typeid
                });
                	$scope.CurrentPage=1;
                }
                
      /**-------------修改(手动添加地址时之后页面跳转到添加地址的页面)---之后----------------------------*/
//             var datapost = {
//                    currpage: 1,
//                    pagesize: $scope.pagesize,
//                    condition: 1,
//                    conditionvalue: typeid
//                };
//                $scope.viewaddress(datapost);
            }else{
                $scope.tipshow(0, "添加或修改失败");
            }

        });
    };

    $(".registerForm").bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            user_addr_name: {
                validators: {
                    notEmpty: {
                        message: '姓名不能为空'
                    }
                }
            },
            user_addr_email: {
                validators: {
                    notEmpty: {
                        message: '邮件地址不能为空'
                    },
                    regexp: {
                        regexp: /^\w+([\.\'-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
                        message: '邮件地址错误'
                    }
                }
            }
        }
    });

    $(".lg-tab button").unbind('click').click(function () {
        var i = $(this).index();
        $(".lg-tab button").removeClass("btn-primary");
        $(this).addClass("btn-primary");
        $(".lg-pane").hide();
        $(".lg-pane").eq(i).show();
    });

    //查询错误信息
    $scope.addrerror=function(i){
        switch (i) {
            case 0:
                var txt = $scope.importaddressinfo.importaddress.unaddr;
                $scope.erroradrress = filtererror(txt);
                break;
            case 1:
                var txt = $scope.importaddressinfo.importaddress.fcaddr;
                $scope.erroradrress = filtererror(txt);
                break;
            case 2:
                var txt = $scope.importaddressinfo.importaddress.selfaddr;
                $scope.erroradrress = filtererror(txt);
                break;
            case 3:
                var txt = $scope.importaddressinfo.importaddress.crmaddr;
                $scope.erroradrress = filtererror(txt);
                break;
            case 4:
                var txt = $scope.importaddressinfo.importaddress.noaddr;
                $scope.erroradrress = filtererror(txt);
                break;
            case 5:
                var txt = $scope.importaddressinfo.importaddress.filtersys;
                $scope.erroradrress = filtererror(txt);
                break;
            case 6:
                var txt = $scope.importaddressinfo.importaddress.filtercustom;
                $scope.erroradrress = filtererror(txt);
                break;
        }
    };

    function filtererror(mails){
        var mz=[];
        if (mails!=""){
            mails=mails.substring(0,mails.length-1);
            var marray=mails.split(",");
            for(var i=0;i<marray.length;i++){
                mz.push(marray[i])
            }
        }
        return mz;
    }
}).controller('addressmailCtrl', function ($scope,$state, $http, $location) {
    'use strict';
    $scope.exporttypevalue=1;
    $("input:radio[name=exporttype]").on('click',function(){
        $scope.exporttypevalue=$(this).val();
        $scope.$apply();
    });
 /**---------------只能调用当前addressmailCtrl---之前---------------------------------*/   
    //分类查询
    $scope.typesort = function () {
        $http.post('./type_findFolderAll.action', {}, $scope.postCfg).success(function (data) {
            //成功之后做一些事情
            $scope.typeitems = data;
        });
    };
    $scope.typesort();
/**---------------只能调用当前addressmailCtrl---之后---------------------------------*/   
    var datapost = {
        currpage: 1,
        pagesize: $scope.pagesize,
        condition: 0,
        conditionvalue: 0
    };
    
    $scope.numPages = 1;
    $scope.maxSize = 10;
    $scope.CurrentPage = 1;
    $scope.condition = 0;
    
    $scope.setPage = function (pageNo) {
        $scope.numPages = pageNo;
    };
    $scope.pageChanged = function () {
       //分类查询条件
       var tid=$("#addresstypeid").val();
       var t=$("#addresssearchcon").val();
       //tid--分类查询条件 0:默认分组
       if(tid==0){
    /**------------------根据条件进行地址查询--之前--------------------------------*/
    	   if(t==""||t.length==0){
    		   //搜索框没输入值则查询全部
    		   $scope.condition=0;
    		   datapost = {
       	            currpage: $scope.CurrentPage,
       	            pagesize: $scope.pagesize,
       	            condition: 0,
       	            conditionvalue: ""
       	        };
    	   }else{
    		   //搜索框有输入值则条件查询
    		   $scope.condition=2;
               datapost = {
                   currpage: $scope.CurrentPage,
                   pagesize: $scope.pagesize,
                   condition: $scope.condition,
                   conditionvalue: t
               };
    	   }
       }else{
    	   //根据分组进行查询
    	   $scope.condition=1;
    	   datapost = {
	            currpage:$scope.CurrentPage,
	            pagesize: $scope.pagesize,
	            condition: $scope.condition,
	            conditionvalue: tid
    	   };
       }
        $scope.viewaddress(datapost);
    };

    $scope.viewaddress(datapost);
    //发邮件
    $scope.addresssend=function(){
        var mails = "";
        $(".addrcheck").each(function () {
            if ($(this).attr("datafilecheck") == "1") {
                mails = $(this).attr("email") + ";" + mails
            }
        });
        mails = mails.substring(0, mails.length - 1);
        if(mails!=""){
            $state.go('app.email',{'emails':mails,utype:6});
        }else{
            $scope.tipshow(0,"请选择邮件地址")
        }

    };


}).controller('typelistCtrl', function ($scope,$state,$rootScope, $http, $location,TemplateList,TempPost) {
    'use strict';
    var chooseIndex = 0;//添加执行任务时选择模板
    //分类查询
    $scope.typesort = function () {
        $http.post('./type_findFolderAll.action', {}, $scope.postCfg).success(function (data) {
            //成功之后做一些事情
            $scope.typeitems = data;
        });
    };
    $scope.typesort();
    
    $scope.temptypelist=function(i) {
        TempPost.gettypelist({
            condition:i
        }).then(function(data){
            $scope.usertypes=data;
        })
    };
    //编辑分类
    $scope.edittypeaddr = function (id,txt) {
        $http.post('./type_editMailFolder.action', {
            typeid:id,
            foldername: txt
        }, $scope.postCfg).success(function (data) {
            //成功之后做一些事情
            if (parseInt(data) == 1) {
            	$scope.typesort();
                $scope.tipshow(1, "修改成功");
            } else {
                $scope.tipshow(0, "修改失败");
            }
        })
    };
    //删除类别(单选)
    $scope.deladdrtype = function (id, i) {
        $http.post('./type_delMailFolder.action', {
            typeid: id,
            deltype: i
        }, $scope.postCfg).success(function (data) {
            //成功之后做一些事情
            if (parseInt(data) == 1) {
                var t = i == 1 ? "删除(不保留)成功" : "删除(保留)成功";
                $scope.typesort();
                $scope.tipshow(1, t);
            } else {
                $scope.tipshow(0, "删除失败");
            }
        }).error(function (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){
    	 $(".yyloading").show();
    	 $scope.templistitems = [];
        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.comtemp();
    //个人
    $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.exportmails=function(tid,i){
        TempPost.exportemail({
            condition:4,
            conditionvalue:i,
            typeid:tid,
            addressidstr:""
        }).then(function(data){
            if(data==1){
                $scope.tipshow(1,"导出成功");
                window.location.href="dowload.action?filename=emailaddress.xls&filedir=tempUserFile";
            }else if(data==-1){
                $scope.tipshow(0,"无可用地址");
            }else{
                $scope.tipshow(0,"导出失败");
            }
        })
    };

    //发邮件
    $scope.addressendmail=function(id,typename){
        $state.go('app.email',{typeid:id,typename:typename})
    };
    //去掉空格
    $scope.removeTrim = function(str){ 
    	return str.replace(/\s+/g, "");
    };
    
    //特殊节假日提示语
    $scope.clicktag = function(){
    	$scope.tipshow(1,"特殊节假日,邮件将提前3天发送");
    };
   
});


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

    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            //####### Dialogs

            element.click(function (e) {
                e.stopPropagation();
                $("#dialog-message").dialog({
                    modal: true,
                    resizable: false,
                    close:function(){
                        $(this).dialog("destroy");
                    },
                    width: 650,
                    maxHeight: 500
                });
            });
        }
    };
}) .directive('lookErrorInfo', function () {
    'use strict';

    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            //####### Dialogs
            element.on('click',function (e) {
                $("#dialog-addressimportinfo").dialog("destroy");
                $("#dialog-erroraddress").dialog({
                    modal: true,
                    resizable: false,
                    width: 700,
                    close:function(){
                        $(this).dialog("destroy");
                    },
                    maxHeight: 500
                });
            });
        }
    };
}).directive('addresssave', function (AddressManage) {
    'use strict';
    //添加地址
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.on('click',function (e) {
                if($(".has-error").length>0){
                    scope.tipshow(0,"信息有误,请检查后再次提交");
                    return false;
                }
                var user_addr_type_id=$("#user_addr_type_id").val();
                var user_addr_name=$("#user_addr_name").val();
                var user_addr_email= $.trim($("#user_addr_email").val());
                var user_addr_variable=$("#user_addr_variable").val();
                var user_addr_company=$("#user_addr_company").val();
                var user_addr_web=$("#user_addr_web").val();
                var facebook=$("#user_addr_facebook").val();
                var twitter=$("#user_addr_twitter").val();
                var linkedin=$("#user_addr_linkedin").val();
                var pinterest=$("#user_addr_pinterest").val();
                var google=$("#user_addr_google").val();
                var tumblr=$("#user_addr_tumblr").val();
                var instagram=$("#user_addr_instagram").val();
                var vk=$("#user_addr_vk").val();
                if(user_addr_web.indexOf('http')<0){
                    user_addr_web='http://'+user_addr_web
                }
                var user_addr_sex=$("input:radio[name=addsex]:checked").val();
                //验证分组地址是否满了
                AddressManage.typeisfull({
                    typeid:user_addr_type_id
                }).then(function(data){
                    if(parseInt(data)==1){
                        AddressManage.isexits({
                            verifistr:user_addr_email
                        }).then(function(data){
                            if(parseInt(data)==1){
                                scope.addressaddandupdate(0,user_addr_type_id,user_addr_name,user_addr_email,user_addr_variable,user_addr_company,user_addr_web,user_addr_sex,facebook,twitter,linkedin,pinterest,google,tumblr,instagram,vk);
                            }else if(parseInt(data)==2){
                                scope.tipshow(0,"与CRM库地址重复");
                            }else if(parseInt(data)==0){
                            	scope.tipshow(0,"与本地库地址重复");
                            }
                        });
                    }else{
                        scope.tipshow(0,"此类别存放的地址已满");
                    }
                });
            });
        }
    };
}).directive('dropclick', function () {
    'use strict';

    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.click(function (e) {
                element.parent().parent().parent().find('.addressid').attr('value',attrs.cid);
                element.parent().parent().parent().find('.btn-show').html(element.html());
            });
        }
    };
}).directive('delTypeAddr', function () {
    'use strict';
    //删除类别提示
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            //####### Dialogs
            element.click(function (e) {
                $("#dialog-deltype").dialog({
                    modal: true,
                    resizable: false,
                    width: 350,
                    close:function(){
                        $(this).dialog("destroy");
                    },
                    buttons: {
                        "删除(保留)": function () {
                            var cid = attrs.cid;
                            scope.deladdrtype(cid, 0);
                            $(this).dialog("destroy");

                        },
                        "删除(不保留)": function () {
                            var cid = attrs.cid;
                            scope.deladdrtype(cid, 1);
                            $(this).dialog("destroy");
                        }
                    }
                });
            });
        }
    };
}).directive('addFileType', function (AddressManage) {
    'use strict';

    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            //####### Dialogs
            element.on('click',function (e) {
                scope.clearinput();
                $("#dialog-addtype").dialog({
                    modal: true,
                    resizable: false,
                    width: 350,
                    close:function(){
                        $(this).dialog("destroy");
                    },
                    buttons: {
                        "保存": function () {
                            var v = $.trim($("#addrtypename").val());
                            if(v==""){
                                scope.tipshow(0,"分组名不能为空");
                                return false;
                            }
                            AddressManage.istypeexits({
                                verifystr:v
                            }).then(function(data){
                                if(parseInt(data)==1){
                                    scope.addtypeaddr(v);
                                }else{
                                    scope.tipshow(0,"分组名已存在");
                                }
                            });

                            $(this).dialog("destroy");

                        },
                        "取消": function () {
                            $(this).dialog("destroy");
                        }
                    }
                });
            });
        }
    };

}).directive('addAddressManage', function ($rootScope) {
    'use strict';
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            //####### Dialogs
            element.on('click',function (e) {
                scope.showeidtmore=false;
//                var tid=$("#addresstypeid").val();
                $(".lg-tab button").removeClass("btn-primary");
                $(".lg-tab button").eq(0).addClass("btn-primary");
                $(".lg-pane").hide();
                $(".lg-pane").eq(0).show();
                $rootScope.clearinput();
                $("#user_addr_type_id, #addr_importtype_id").val(attrs.planid);
                $(".has-success").removeClass("has-success");
                $(".has-error").removeClass("has-error");
                $(".form-control-feedback").hide();
                $("#dialog-manageaddress").dialog({
                    modal: true,
                    close:function(){
                        $(this).dialog("destroy");
                    },
                    resizable: false,
                    width: 550
                });
            });
        }
    };
}).directive('addressInfo', function () {
    'use strict';
    //详细信息
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            //####### Dialogs
            element.on('click',function() {
                scope.readaddrinfo(attrs.cid);
            });
        }
    };
})
    //编辑分组
.directive('editAddress', function (AddressManage) {
    'use strict';
    //详细信息
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.on('click',function(){
            	var oldname = scope.removeTrim(attrs.tname);
               $("#edittypename").val(oldname);
                var cid=attrs.cid;
                $("#dialog-edittype").dialog({
                    modal: true,
                    resizable: false,
                    width: 350,
                    close:function(){
                        $(this).dialog("destroy");
                    },
                    buttons: {
                        "保存": function () {
                        	var newname = scope.removeTrim($("#edittypename").val());
                        	if(newname == ""){
	                    		  scope.tipshow(0,"分组名不能为空");
	                              return false;
                        	}
                        	if(newname != oldname){
                        		 AddressManage.istypeexits({
                                     verifystr:newname
                                 }).then(function(data){
                                     if(parseInt(data)==1){
                                         scope.edittypeaddr(cid,newname);
                                     }else{
                                         scope.tipshow(0,"分组名已存在");
                                     }
                                 });
                        	}else{
                        		scope.tipshow(1,"编辑成功");
                        	}
                           
                            $(this).dialog("destroy");
                        },
                        "取消": function () {
                            $(this).dialog("destroy");
                        }
                    }
                });


            });
        }
    };
})

    //高级搜索
    .directive('addressSeniorSearch', function () {
        'use strict';
        //详细信息
        return {
            restrict: 'AE',
            link: function (scope, element, attrs) {
                //####### Dialogs
                element.on('click',function() {
                    var sendnum=$("#address_sendnum").val();
                    if(sendnum==''){
                        sendnum=0
                    }
                    var readnum=$("#address_readnum").val();
                    if(readnum==''){
                        readnum=0
                    }
                    var replaynum=$(".address_replay").attr("datasinglecheck");
                    var seniorval=sendnum+"#"+readnum+"#"+replaynum;

                    var datapost = {
                        currpage: 1,
                        pagesize: scope.pagesize,
                        condition: 3,
                        conditionvalue: seniorval
                    };
                    scope.viewaddress(datapost);
                });
            }
        };
    })
//营销计划
.directive('addplan', function ($http,$rootScope,$state) {
    'use strict';
    return {
        restrict: 'E',
        replace : true,
        transclude : true,
        scope : {
            tid : '=planid',
            mnum:'=mailnum',
            pname:'=planname',
        },
        template: '<div><button ng-show="mnum>0" class="btn btn-info btn-xs" ng-click="addplans(tid)">新建计划</button><button ng-show="mnum<=0" class="btn btn-default btn-xs" planid={{tid}} add-address-manage>添加地址</button></div>',
        controller: ['$scope', function ($scope) {
            $scope.addplans = function (id) {
                $rootScope.clearinput();
                var myDate = new Date();
                var day = myDate.getDay();
                var month = myDate.getMonth()+1;
                var year  = myDate.getFullYear();//获取当前年份
                var date = myDate.getDate();//获取当前日期
                if(month < 10){
                	month="0"+month;
    	        }
    	        if(date<10){
    	        	date="0"+date;
    	        }
    	        $(".lg-checkbox-n").attr('datasinglecheck',0);
                $(".lg-checkbox-n").removeClass("checkbox-n-active");
                $(".lg-checkbox-n").removeClass("yetCheck");
                var nowdate = year +"-"+month+"-"+date;
                var nextyear = year+1 +"-01-01";
                var input_value = "给"+$scope.pname+"分类的跟进计划";
                $("#plantitle").val(input_value);
                $(".weekday label").removeAttr('datasinglecheck');
                $(".weekday label").each(function(){
                    var wday=parseInt($(this).attr("weekdate"));
                    if(wday-day<=0){
                        //console.log( $(this).attr('datasinglecheck'));
                        $(this).after('<label class="lg-checkbox-n lg-plan-week"></label>').remove();
                    }
                });
                $rootScope.hcalendar = [];//清空
            	$(".holiday label").each(function(){
                    var wday=parseInt($(this).attr("weekdate"));
                    var Dholiday = GetHoliday2(wday);
                	if(nowdate > Dholiday){
                		$(this).after('<label class="lg-checkbox-n lg-plan-holiday"></label>').remove();
                	}
                });
            	//添加title
            	$('.holiday span').each(function () {
                    var k = $(this).attr('hdate');
                    var Dholiday2 = GetHoliday(k);
                    $rootScope.hcalendar.push(Dholiday2.split("###")[0])
            	})
                
                $('#dialog-addressplan').dialog({
                    position: ["center", 100],
                    modal: true,
                    resizable: false,
                    width: 720,
                    close:function(){
                        $(this).dialog("destroy");
                    },
                    buttons: {
                        "保存计划": function () {
                        	
                            var v1 = $('input:radio[name="plan-1"]:checked').val();//计划类型
                            var v2 = $('input:radio[name="plan-2"]:checked').val();//计划周期
                            var runtime = $('#runtime').val();//设置时间
                            var temptable = $('.conformrunplan tbody');//保存执行计划
                            var temptabletip = $('.conformtipplan tbody');//保存提醒计划
                            
                            //先清空
                            temptable.html('');
                            temptabletip.html('');
                            var plantitle=$('#plantitle').val();//计划主题
                            if(plantitle==""){
                                $rootScope.tipshow(0,"主题不能为空");
                                return false;
                            }
                            if(v2 == undefined){
                            	$rootScope.tipshow(0,"请选择计划周期");
                                return false;	
                            }
                            if(v2 != 6){ //制定具体日期
                            	if(!$("label").is(".yetCheck")){
                        			 $rootScope.tipshow(0,"请选择计划周期的执行时间");
                                     return false;
                                }
                            }else{
                            	if($rootScope.specificTime == ""){
                            		 $rootScope.tipshow(0,"请选择计划周期的执行时间");
                                     return false;
                            	}
                            }
                            if(runtime==""){
                                $rootScope.tipshow(0,"请选择执行的详细时间");
                                return false;
                            }
                            var con1 = ''; //时间类型例:每月
                            var realtime = ''; //对应的日期 2015-10-20
                            switch (parseInt(v2)) {
                                case 1:
                                	//每月
                                    con1 = '每月';
                                    break;
                                case 2:
                                	//一周内
                                    con1 = '一周内';
                                    break;
                                case 3:
                                	//30内
                                    con1 = '30天内';
                                    break;
                                case 4:
                                	//指定时间内
                                    var begintime = $('#begintime').val();//开始时间
                                    var endtime = $('#endtime').val();//结束时间
                                    con1 = begintime + '--' + endtime + '内';
                                    break;
                                case 5:
                                	//特殊节假日
                                    con1 = '特殊节假日';
                                    break;
                                case 6:
                                	//指定日期内
                                    con1 = '指定具体日期';
                                    break;
                            }
                            var myDate = new Date();
                            var day = myDate.getDay();
                            
                            var thtmlhead = '<tr>'
                                + '<td colspan="3">您本次营销计划周期为: <span class="color-red">' + con1 + '发送</span> 计划,提交的发送邮件地址数共 <span class="color-red">'+$scope.mnum+'</span> 个,提交的详细计划日期如下</td>'
                                + '</tr>';

                            temptable.append(thtmlhead);
                            var thtmlheadtip = '<tr>'
                                + '<td colspan="2">您本次营销计划周期为: <span class="color-red">' + con1 + '提醒</span> 计划,提交的详细计划日期如下</td>'
                                + '</tr>';
                            temptabletip.append(thtmlheadtip);
                          var advancehtml = '';
                            var atime = $('#advancetime').val();
                            if (atime > 0) {
                                advancehtml = '提前 <span class="color-red">' + atime + '</span> 分钟提醒';
                            }
                            //计划周期中的具体时间
                            if(v2 == 6){
                                //选择为提醒时
                                con1 = '指定具体日期';
                                if (parseInt(v1) == 0) {
                                     	var str_time = $rootScope.specificTime;
                                     	for(var n=0; n<str_time.length;n++){
                                     		  realtime = '( 对应日期: <span class="color-red">' + str_time[n].date + '</span> )';
                                               var thtml = '<tr class="lg-tr" tag="' + n + '" week="' + str_time[n].chooseTime + '" realtime='+str_time[n].date+' modelid="0">';
                                               thtml += '<td>' + con1 + ' 的 <span class="color-red">' + str_time[n].chooseTime + '</span> ' + realtime + ' <span class="color-red runtime">' + runtime + '</span> 进行计划提醒</td><td>' + advancehtml + '</td>';
                                               thtml += '</tr>';
                                               
                                               temptabletip.append(thtml);
                                     	}
                                } else {
                                	var str_time = $rootScope.specificTime;
                                 	for(var n=0; n<str_time.length;n++){
                                            realtime = '( 对应日期: <span class="color-red">' + str_time[n].date + '</span> )';
                                            var thtml = '<tr class="lg-tr" tag="' + n + '" week="' + str_time[n].chooseTime + '" realtime='+str_time[n].date+' modelid="0">';
                                            thtml += '<td>' + con1 + ' 的 <span class="color-red">' + str_time[n].chooseTime + '</span>' + realtime + '<span class="color-red runtime">' + runtime + '</span> 进行邮件发送</td><td></td><td width="120"><button class="btn btn-info btn-xs" onclick="addtempaddr(' + n + ')"><i class="fa fa-newspaper-o"></i> 选择模板</button></td>';
                                            thtml += '</tr>';
                                            temptable.append(thtml);
                                        }
                                    }
                            }else{
                            	$('.addplantable [datasinglecheck="1"]').each(function () {
                                    var k = $(this).attr('weekdate');
                                    var weekday = '';
                                    var today = day;
                                    switch (parseInt(k)) {
                                        case 1:
                                            weekday = '星期一';
                                            break;
                                        case 2:
                                            weekday = '星期二';
                                            break;
                                        case 3:
                                            weekday = '星期三';
                                            break;
                                        case 4:
                                            weekday = '星期四';
                                            break;
                                        case 5:
                                            weekday = '星期五';
                                            break;
                                        case 6:
                                            weekday = '星期六';
                                            break;
                                        case 7:
                                            weekday = '星期日';
                                            break;
                                        case 8:
                                            weekday = '元 旦';
                                            break;
                                        case 9:
                                            weekday = '妇女节';
                                            break;
                                        case 10:
                                            weekday = '劳动节';
                                            break;
                                        case 11:
                                            weekday = '圣诞节';
                                            break;
                                        case 12:
                                            weekday = '春 节';
                                            break;
                                        case 13:
                                            weekday = '元宵节';
                                            break;
                                        case 14:
                                            weekday = '清明节';
                                            break;
                                        case 15:
                                            weekday = '端午节';
                                            break;
                                        case 16:
                                            weekday = '中秋节';
                                            break;
                                        case 17:
                                            weekday = '国庆节';
                                            break;
                                        case 18:
                                            weekday = '儿童节';
                                            break;
                                        case 19:
                                            weekday = '父亲节';
                                            break;
                                        case 20:
                                            weekday = '母亲节';
                                            break;
                                        case 21:
                                            weekday = '感恩节';
                                            break;
                                        case 22:
                                            weekday = '印度排灯节';
                                            break;
                                        case 23:
                                            weekday = '俄罗斯新年';
                                            break;
                                        case 24:
                                            weekday = '伊斯兰开斋节';
                                            break;
                                        case 25:
                                            weekday = '耶稣复活节';
                                            break;
                                        case 26:
                                            weekday = '欧美万圣节';
                                            break;
                                    }
                                    //选择为提醒时
                                    if (parseInt(v1) == 0) {
                                        //判断
                                        switch (parseInt(v2)) {
                                            case 1:
                                                con1 = '每月';
                                                var thtml = '<tr class="lg-tr" tag="' + k + '" week="' + k + '" realtime='+realtime+' modelid="0">';
                                                thtml += '<td>' + con1 + ' 的 <span class="color-red">' + weekday + '</span> ' + realtime + ' <span class="color-red">' + runtime + '</span> 进行计划提醒</td><td>' + advancehtml + '</td>';
                                                thtml += '</tr>';
                                                temptabletip.append(thtml);
                                                break;
                                            case 2:
                                                if (k > today) {
                                                    var addday = k - today;
                                                    realtime = '( 对应日期: <span class="color-red">' + GetDateStr(addday) + '</span> )';
                                                    var thtml = '<tr class="lg-tr"  tag="' + k + '" week="' + k + '" realtime='+GetDateStr(addday)+' modelid="0">';
                                                    thtml += '<td>' + con1 + ' 的 <span class="color-red">' + weekday + '</span> ' + realtime + ' <span class="color-red">' + runtime + '</span> 进行计划提醒</td><td>' + advancehtml + '</td>';
                                                    thtml += '</tr>';
                                                    temptabletip.append(thtml);
                                                }
                                                
                                                break;
                                            case 3:
                                                for (var i = 0; i < 30; i++) {
                                                    if (today > 7) {
                                                        today = 1;
                                                    }
                                                    if (today == parseInt(k)) {
                                                        realtime = '( 对应日期: <span class="color-red">' + GetDateStr(i) + '</span> )';
                                                        var thtml = '<tr class="lg-tr" tag="' + i + '" week="' + k + '" realtime='+GetDateStr(i)+' modelid="0">';
                                                        thtml += '<td>' + con1 + ' 的 <span class="color-red">' + weekday + '</span> ' + realtime + ' <span class="color-red">' + runtime + '</span> 进行计划提醒</td><td>' + advancehtml + '</td>';
                                                        thtml += '</tr>';
                                                        temptabletip.append(thtml);
                                                    }
                                                    today += 1;
                                                }
                                                break;
                                            case 4:
                                            	 var begintime = $('#begintime').val();
                                                 var endtime = $('#endtime').val();
                                                 con1 = begintime + '--' + endtime + '内';
                                                 var begindate = new Date(begintime);
                                                 var beginday = begindate.getDay();//系统当期周几
                                                 var d = DateDiff(begintime, endtime);
                                                 for (var i = 0; i < d; i++) {
                                                     if (beginday > 7) {
                                                         beginday = 1;
                                                     }
                                                     if (beginday == parseInt(k)) {
                                                         realtime = '( 对应日期: <span class="color-red">' + GetDateDiffStr(begintime, i) + '</span> )';
                                                         var thtml = '<tr class="lg-tr" tag="' + i + '" week="' + k + '" realtime='+GetDateDiffStr(begintime, i)+' modelid="0">';
                                                         thtml += '<td>' + con1 + ' 的 <span class="color-red">' + weekday + '</span> ' + realtime + ' <span class="color-red">' + runtime + '</span> 进行计划提醒</td><td>' + advancehtml + '</td>';
                                                         thtml += '</tr>';
                                                         temptabletip.append(thtml);
                                                     }
                                                     beginday += 1;
                                                 }
                                                 break;
                                            case 5:
                                                con1 = '特殊节假日';
                                                 var Dholiday = GetHoliday(k);
                                                 var str = Dholiday.split("###")[0];
                                                 var str2 = Dholiday.split("###")[1];
                                                 realtime = '( 对应日期: <span class="color-red">' + str + '</span> )';
                                                            var thtml = '<tr class="lg-tr" tag="' + k + '" week="' + k + '" realtime='+str+' modelid="0" sendtime="' + str2 + '">';
                                                            thtml += '<td>' + con1 + ' 的 <span class="color-red">' + weekday + '</span> ' + realtime + ' <span class="color-red">' + runtime + '</span> 进行计划提醒</td><td>' + advancehtml + '</td>';
                                                            thtml += '</tr>';
                                                            temptabletip.append(thtml);
                                                break;
                                            case 6:
                                                con1 = '指定具体日期';
                                                if(v2 == 6){
                                                	var str_time = $rootScope.specificTime;
                                                	for(var n=0; n<str_time.length;n++){
                                                		  realtime = '( 对应日期: <span class="color-red">' + str_time[n].date + '</span> )';
                                                          var thtml = '<tr class="lg-tr" tag="' + n + '" week="' + k + '" realtime='+str_time[n].date+' modelid="0">';
                                                          thtml += '<td>' + con1 + ' 的 <span class="color-red">' + str_time[n].chooseTime + '</span> ' + realtime + ' <span class="color-red runtime">' + runtime + '</span> 进行计划提醒</td><td>' + advancehtml + '</td>';
                                                          thtml += '</tr>';
                                                          
                                                          temptabletip.append(thtml);
                                                	}
                                                }
                                                break;
                                            default:
                                                var thtml = '<tr class="lg-tr" tag="' + k + '" week="' + k + '" realtime='+realtime+' modelid="0">';
                                                thtml += '<td>' + con1 + ' 的 <span class="color-red">' + weekday + '</span> ' + realtime + ' <span class="color-red">' + runtime + '</span> 进行计划提醒</td><td>' + advancehtml + '</td>';
                                                thtml += '</tr>';
                                                temptabletip.append(thtml);
                                        }
                                    } else {
                                        //判断(执行计划)
                                        switch (parseInt(v2)) {
                                            case 1:
                                                con1 = '每月';
                                                var thtml = '<tr class="lg-tr" tag="' + k + '" week="' + k + '" realtime='+realtime+' modelid="0">';
                                                thtml += '<td>' + con1 + ' 的 <span class="color-red">' + weekday + '</span> <span class="realtime">' + realtime + '</span> <span class="color-red">' + runtime + '</span> 进行邮件发送</td><td></td><td width="120"><button class="btn btn-info btn-xs" onclick="addtempaddr(' + k + ')"><i class="fa fa-newspaper-o"></i> 选择模板</button></td>';
                                                thtml += '</tr>';
                                                temptable.append(thtml);
                                                break;
                                            case 2:
                                                if (k > today) {
                                                    var addday = k - today;
                                                    realtime = '( 对应日期: <span class="color-red">' + GetDateStr(addday) + '</span> )';
                                                    var thtml = '<tr class="lg-tr" tag="' + k + '" week="' + k + '" realtime='+GetDateStr(addday)+' modelid="0">';
                                                    thtml += '<td>' + con1 + ' 的 <span class="color-red">' + weekday + '</span>' + realtime + '<span class="color-red">' + runtime + '</span> 进行邮件发送</td><td></td><td width="120"><button class="btn btn-info btn-xs" onclick="addtempaddr(' + k + ')"><i class="fa fa-newspaper-o"></i> 选择模板</button></td>';
                                                    thtml += '</tr>';
                                                    temptable.append(thtml);
                                                }
                                                break;
                                            case 3:
                                                for (var i = 0; i < 30; i++) {
                                                    if (today > 7) {
                                                        today = 1;
                                                    }
                                                    if (today == parseInt(k)) {
                                                        realtime = '( 对应日期: <span class="color-red">' + GetDateStr(i) + '</span> )';
                                                        var thtml = '<tr class="lg-tr" tag="' + i + '" week="' + k + '" realtime='+GetDateStr(i)+' modelid="0">';
                                                        thtml += '<td>' + con1 + ' 的 <span class="color-red">' + weekday + '</span>' + realtime + '<span class="color-red runtime">' + runtime + '</span> 进行邮件发送</td><td></td><td width="120"><button class="btn btn-info btn-xs" onclick="addtempaddr(' + i + ')"><i class="fa fa-newspaper-o"></i> 选择模板</button></td>';
                                                        thtml += '</tr>';
                                                        temptable.append(thtml);
                                                    }
                                                    today += 1;
                                                }
                                                break;
                                            case 4:
                                            	  var begintime = $('#begintime').val();
                                                  var endtime = $('#endtime').val();
                                                  con1 = begintime + '--' + endtime + '内';
                                                  var begindate = new Date(begintime);
                                                  var beginday = begindate.getDay();
                                                  var d = DateDiff(begintime, endtime);
                                                  for (var i = 0; i < d; i++) {
                                                      if (beginday > 7) {
                                                          beginday = 1;
                                                      }
                                                      if (beginday == parseInt(k)) {
                                                          realtime = '( 对应日期: <span class="color-red">' + GetDateDiffStr(begintime, i) + '</span> )';
                                                          var thtml = '<tr class="lg-tr" tag="' + i + '" week="' + k + '" realtime='+GetDateDiffStr(begintime, i)+' modelid="0">';
                                                          thtml += '<td>' + con1 + ' 的 <span class="color-red">' + weekday + '</span>' + realtime + '<span class="color-red runtime">' + runtime + '</span> 进行邮件发送</td><td></td><td width="120"><button class="btn btn-info btn-xs" onclick="addtempaddr(' + i + ')"><i class="fa fa-newspaper-o"></i> 选择模板</button></td>';
                                                          thtml += '</tr>';
                                                          temptable.append(thtml);
                                                      }
                                                      beginday += 1;
                                                  }
                                                  break;
                                            case 5:
                                                con1 = '特殊节假日';
                                                var Dholiday = GetHoliday(k);
                                                var str = Dholiday.split("###")[0];
                                                var str2 = Dholiday.split("###")[1];
                                            	realtime = '( 对应日期: <span class="color-red">' + str + '</span> )';
  	                                            var thtml = '<tr class="lg-tr" tag="' + k + '" week="' + k + '" realtime='+str+' modelid="0" sendtime="' + str2 + '">';
  	                                            thtml += '<td>' + con1 + ' 的 <span class="color-red">' + weekday + '</span>' + realtime + '<span class="color-red runtime">' + runtime + '</span> 进行邮件发送</td><td></td><td width="120"><button class="btn btn-info btn-xs" onclick="addtempaddr(' + k + ')"><i class="fa fa-newspaper-o"></i> 选择模板</button></td>';
  	                                            thtml += '</tr>';
  	                                            temptable.append(thtml);
                                                break;
                                            default:
                                                var thtml = '<tr class="lg-tr" tag="' + k + '" week="' + k + '" realtime='+realtime+' modelid="0">';
                                                thtml += '<td>' + con1 + ' 的 <span class="color-red">' + weekday + '</span> <span class="realtime">' + realtime + '</span> <span class="color-red runtime">' + runtime + '</span> 进行邮件发送</td><td></td><td width="120"><button class="btn btn-info btn-xs" onclick="addtempaddr(' + k + ')"><i class="fa fa-newspaper-o"></i> 选择模板</button></td>';
                                                thtml += '</tr>';
                                                temptable.append(thtml);
                                        }
                                    }
                                });	
                            }
                            //提交计划
                            function submitplan(){
                                var plantype=$("input:radio[name=plan-1]:checked").val();
                                var plancycle=$("input:radio[name=plan-2]:checked").val();
                                var planweekmodel="";
                                //0:提醒计划   1:执行计划
                                if(plantype==0){
                                	//保存提醒计划
                                	$(".conformtipplan .lg-tr").each(function(i){
                                		if(plancycle == 6){
                                			var weekday=$(this).attr("week");
                                			 switch (weekday) {
                                             case '星期一':
                                                 w = 1;
                                                 break;
                                             case '星期二':
                                                 w = 2;
                                                 break;
                                             case '星期三':
                                                 w = 3;
                                                 break;
                                             case '星期四':
                                                 w = 4;
                                                 break;
                                             case '星期五':
                                                 w = 5;
                                                 break;
                                             case '星期六':
                                                 w = 6;
                                                 break;
                                             case '星期日':
                                                 w = 7;
                                                 break;
                                         }
                                			var q=$(this).attr("realtime");
                                		}else if(plancycle == 5){
                                			var w=$(this).attr("week");
                                			var q = $(this).attr("sendtime");
                                		}else{
                                			var w=$(this).attr("week");
                                			var q=$(this).attr("realtime");
                                		}
                                		var m=$(this).attr("modelid");
                                        planweekmodel+=w+","+q+","+m+"#";
                                    });
                                }else{
                                	var checkmodelid=0;
                                    //保存执行计划
                                	 $(".conformrunplan .lg-tr").each(function(i){
                                		 if(plancycle == 6){
                                 			var weekday=$(this).attr("week");
                                 			 switch (weekday) {
                                              case '星期一':
                                                  w = 1;
                                                  break;
                                              case '星期二':
                                                  w = 2;
                                                  break;
                                              case '星期三':
                                                  w = 3;
                                                  break;
                                              case '星期四':
                                                  w = 4;
                                                  break;
                                              case '星期五':
                                                  w = 5;
                                                  break;
                                              case '星期六':
                                                  w = 6;
                                                  break;
                                              case '星期日':
                                                  w = 7;
                                                  break;
                                          }
                                 			 var q=$(this).attr("realtime");
                                 		}else if(plancycle == 5){
                                 			var w=$(this).attr("week");
                                 			var q = $(this).attr("sendtime");
                                 		}else{
                                 			var w=$(this).attr("week");
                                 			var q=$(this).attr("realtime");
                                 		}
                                		 var m=$(this).attr("modelid");
                                        if(parseInt(m)==0){
                                            checkmodelid=1;
                                        }
                                        planweekmodel+=w+","+q+","+m+"#";
                                    });
                                }
                                if(checkmodelid==1){
                                    $rootScope.tipshow(0,"还有任务没选择模板,请选择模板");
                                    return false;
                                }
                                planweekmodel=planweekmodel.substring(0,planweekmodel.length-1);
                                var planexecutetime=$('#runtime').val();
                                var plantitle=$('#plantitle').val();
                                var begintime=$('#begintime').val();
                                var endtime=$('#endtime').val();
                                if(plancycle == 6){ //指定具体日期
                                	var lasttime = $rootScope.specificTime[$rootScope.specificTime.length-1];//取最后时间 
                                	endtime = lasttime.date;
                                }else if(plancycle == 5){ //特殊节假日
                                	begintime = nowdate;
                                	endtime = nextyear;
                                }
                                //提醒计划
                               if($rootScope.crmtype == 9){ //采购偏好
                            	   id = $scope.mnum;
                            	   $rootScope.other_name = $scope.pname; 
                               }else if($rootScope.crmtype ==11){ //个性营销
                            	   id = $scope.mnum;
                               }
                               //plantype==0:提醒计划
                                if($rootScope.crmtype == 0 || plantype == 0){ //区分本地库:0 和crm库:1
                                	$("#loading").show();
                                	if(plantype == 1){
                                		$http.post('./plan_beforeAddMarketingPlan.action', {
                                			  addressnum: $scope.mnum,
                                            planweekmodel: planweekmodel
                                        }, $rootScope.postCfg).success(function (data) {
                                      	  $("#loading").hide();
                                      	  if(data.importaddress.result == 1){  //成功
                                      		  $http.post('./plan_addMarketingPlan.action', {
	                                      			 plancycle: plancycle,
	                                                 plangroupid: id,//如果是采购偏好和个性营销则id就是数量,否则就是具体的id
	                                                 planweekmodel: planweekmodel,
	                                                 planexecutetime: planexecutetime,
	                                                 plantype: plantype,
	                                                 plantitle: plantitle,
	                                                 begintime: begintime,
	                                                 endtime: endtime,
	                                                 other_name: $rootScope.other_name,//如果是采购偏好和个性营销则就是查询条件值
	                                                 plan_differen:$rootScope.crmtype
                                                }, $rootScope.postCfg).success(function (data) {
                                                	//成功之后做一些事情
                                                	$("#loading").hide();
                                                    if(parseInt(data)==1){
                                                        if(parseInt(plantype)==0){
                                                            $rootScope.tipshow(1,'添加提醒成功');
                                                            $('#dialog-addressplan').dialog("destroy");
                                                        }else{
                                                            $rootScope.tipshow(1,'添加计划成功');
                                                            $('#dialog-addressplan').dialog("destroy");
                                                            $('#dialog-conform').dialog("destroy");
                                                        }
                                                        $(".lg-checkbox-n").attr('datasinglecheck',0);
                                                        $(".lg-checkbox-n").removeClass("checkbox-n-active");
                                                        $state.go('app.plan.planview');
                                                    }else{
                                                        $rootScope.tipshow(0,'添加计划失败,请检查参数是否正确');
                                                    }
                                                });
                                      		  $(this).dialog("destroy");
                                      	  }else if(data.importaddress.result == 0){ //异常
                                      		  $rootScope.tipshow(0,data.importaddress.reason);
                                      	  }else if(data.importaddress.result == -1){  //总发送量超标
                                      		  $rootScope.tipshow(0,data.importaddress.reason);
                                      	  }else if(data.importaddress.result == -2){  //月发送量超标
                                      		  $rootScope.tipshow(0,data.importaddress.reason);
                                      	  }else if(data.importaddress.result == -3){  //日发送量超标
                                      		  $rootScope.tipshow(0,data.importaddress.reason);
                                      	  }
                                        });
                                	}else{
                                		$http.post('./plan_addMarketingPlan.action', {
                                            plancycle: plancycle,
                                            plangroupid: id,//如果是采购偏好和个性营销则id就是数量,否则就是具体的id
                                            planweekmodel: planweekmodel,
                                            planexecutetime: planexecutetime,
                                            plantype: plantype,
                                            plantitle: plantitle,
                                            begintime: begintime,
                                            endtime: endtime,
                                            other_name: $rootScope.other_name,//如果是采购偏好和个性营销则就是查询条件值
                                            plan_differen:$rootScope.crmtype
                                        }, $rootScope.postCfg).success(function (data) {
                                            //成功之后做一些事情
                                        	$("#loading").hide();
                                            if(parseInt(data)==1){
                                                if(parseInt(plantype)==0){
                                                    $rootScope.tipshow(1,'添加提醒成功');
                                                    $('#dialog-addressplan').dialog("destroy");
                                                }else{
                                                    $rootScope.tipshow(1,'添加计划成功');
                                                    $('#dialog-addressplan').dialog("destroy");
                                                    $('#dialog-conform').dialog("destroy");
                                                }
                                                $(".lg-checkbox-n").attr('datasinglecheck',0);
                                                $(".lg-checkbox-n").removeClass("checkbox-n-active");
                                                $state.go('app.plan.planview');
                                            }else{
                                                $rootScope.tipshow(0,'添加计划失败,请检查参数是否正确');
                                            }
                                        });
                                	}
                                }else{
                                	if(plantype!=0){//执行计划
                                		$("#loading").show();
                                		$http.post('./plan_getMonthSendLimit.action', {
                                          	plangroupid:id,//如果是采购偏好和个性营销则id就是数量,否则就是具体的id
                                          	planweekmodel:planweekmodel,
                                          	crmtype:$rootScope.crmtype//4就是采购偏好,5就是个性营销
                                          }, $rootScope.postCfg).success(function (data) {
                                        	  $("#loading").hide();
                                        	  //判断分类
                                        	  if(data.importaddress.result==1){//没超标
                                        		  $http.post('./plan_beforeAddMarketingPlan.action', {
                                          			  addressnum: $scope.mnum,
                                                      planweekmodel: planweekmodel
                                                  }, $rootScope.postCfg).success(function (data) {
                                                	  $("#loading").hide();
                                                	  if(data.importaddress.result == 1){  //成功
                                                		  $http.post('./plan_addMarketingPlan.action', {
                                                              plancycle: plancycle,
                                                              plangroupid: id,//如果是采购偏好和个性营销则id就是数量,否则就是具体的id
                                                              planweekmodel: planweekmodel,
                                                              planexecutetime: planexecutetime,
                                                              plantype: plantype,
                                                              plantitle: plantitle,
                                                              begintime: begintime,
                                                              endtime: endtime,
                                                              plan_differen:$rootScope.crmtype,
                                                              other_name: $rootScope.other_name,//如果是采购偏好和个性营销则就是查询条件值
                                                          }, $rootScope.postCfg).success(function (data) {
                                                              //成功之后做一些事情
                                                              if(parseInt(data)==1){
                                                                  if(parseInt(plantype)==0){
                                                                      $rootScope.tipshow(1,'添加提醒成功');
                                                                      $('#dialog-addressplan').dialog("destroy");
                                                                  }else{
                                                                      $rootScope.tipshow(1,'添加计划成功');
                                                                      $('#dialog-addressplan').dialog("destroy");
                                                                      $('#dialog-conform').dialog("destroy");
                                                                  }
                                                                  $(".lg-checkbox-n").attr('datasinglecheck',0);
                                                                  $(".lg-checkbox-n").removeClass("checkbox-n-active");
                                                                  $state.go('app.plan.planview');
                                                              }else{
                                                                  $rootScope.tipshow(0,'添加计划失败,请检查参数是否正确');
                                                              }
                                                          });
                                                		  $(this).dialog("destroy");
                                                	  }else if(data.importaddress.result == 0){ //异常
                                                		  $rootScope.tipshow(0,data.importaddress.reason);
                                                	  }else if(data.importaddress.result == -1){  //总发送量超标
                                                		  $rootScope.tipshow(0,data.importaddress.reason);
                                                	  }else if(data.importaddress.result == -2){  //月发送量超标
                                                		  $rootScope.tipshow(0,data.importaddress.reason);
                                                	  }else if(data.importaddress.result == -3){  //日发送量超标
                                                		  $rootScope.tipshow(0,data.importaddress.reason);
                                                	  }
                                                  });
                                        	  }else if(data.importaddress.result== -1){ //单次发量超标
                                        		  var cusType = 2;
                                        		  if($rootScope.crmtype == 1){ //客户分类
                                        			  cusType = 2;
     	                                         	}else if($rootScope.crmtype == 3){  //客户状态
     	                                         		cusType = 4;
     	                                         	}else if($rootScope.crmtype == 5){ //客户来源
     	                                         		cusType = 6;
     	                                         	}else if($rootScope.crmtype == 7){//意向产品
     	                                         		cusType = 8;
     	                                         	}else if($rootScope.crmtype == 9){//采购偏好
     	                                         		cusType = 10;
     	                                         	}else if($rootScope.crmtype == 11){//个性营销
     	                                         		cusType = 12;
     	                                         	}
                                        		  	var point = $(".plandaylimit span");
	                                               	point.html('');//
	                                               	var pointContent = data.importaddress.reason+",如需继续发送将使用<span class='color-red'>系统代发模式</span>";
	                                               	point.append(pointContent);
	                                               	$('#dialog-planOverweightDay').dialog({
	                                                    position: ["center", 100],
	                                                    modal: true,
	                                                    resizable: false,
	                                                    width: 350,
	                                                    maxHeight: 320,
	                                                    close:function(){
	                                                        $(this).dialog("destroy");
	                                                    },
	                                                    buttons: {
	                                                    	"继续执行提交计划": function () {
	                                                    		$("#loading").show();
	                                                    		 $http.post('./plan_beforeAddMarketingPlan.action', {
	                                                     			 addressnum: $scope.mnum,
	                                                                 planweekmodel: planweekmodel
	                                                             }, $rootScope.postCfg).success(function (data) {
	                                                            	 $("#loading").hide();
	                                                           	  if(data.importaddress.result == 1){  //成功
	                                                           		$http.post('./plan_addMarketingPlan.action', {
		                                                                plancycle: plancycle,
		                                                                plangroupid: id,
		                                                                planweekmodel: planweekmodel,
		                                                                planexecutetime: planexecutetime,
		                                                                plantype: plantype,
		                                                                plantitle: plantitle,
		                                                                begintime: begintime,
		                                                                endtime: endtime,
		                                                                plan_differen:cusType,
		                                                                other_name: $rootScope.other_name,//如果是采购偏好和个性营销则就是查询条件值
		                                                            }, $rootScope.postCfg).success(function (data) {
		                                                                //成功之后做一些事情
		                                                                if(parseInt(data)==1){
		                                                                    if(parseInt(plantype)==0){
		                                                                        $rootScope.tipshow(1,'添加提醒成功');
		                                                                        $('#dialog-addressplan').dialog("destroy");
		                                                                    }else{
		                                                                        $rootScope.tipshow(1,'添加计划成功');
		                                                                        $('#dialog-addressplan').dialog("destroy");
		                                                                        $('#dialog-conform').dialog("destroy");
		                                                                    }
		                                                                    $(".lg-checkbox-n").attr('datasinglecheck',0);
		                                                                    $(".lg-checkbox-n").removeClass("checkbox-n-active");
		                                                                    $state.go('app.plan.planview');
		                                                                }else{
		                                                                    $rootScope.tipshow(0,'添加计划失败,请检查参数是否正确');
		                                                                }
		                                                            });
	                                                           		$(this).dialog("destroy");
	                                                           	  }else if(data.importaddress.result == 0){ //异常
	                                                           		  $rootScope.tipshow(0,data.importaddress.reason);
	                                                           	  }else if(data.importaddress.result == -1){  //总发送量超标
	                                                           		  $rootScope.tipshow(0,data.importaddress.reason);
	                                                           	  }else if(data.importaddress.result == -2){  //月发送量超标
	                                                           		  $rootScope.tipshow(0,data.importaddress.reason);
	                                                           	  }else if(data.importaddress.result == -3){  //日发送量超标
	                                                           		  $rootScope.tipshow(0,data.importaddress.reason);
	                                                           	  }
	                                                             });
	                                           				},
	                                           				"取消计划": function () {
	                                           					 $(this).dialog("destroy");
	                                           				}
	                                                    }
	                                                }); 
                                        	  }else if(data.importaddress.result== -2){ //月发量超标
                                        		  var cusType = 2;
                                        		  if($rootScope.crmtype == 1){ //客户分类
                                        			  cusType = 2;
     	                                         	}else if($rootScope.crmtype == 3){  //客户状态
     	                                         		cusType = 4;
     	                                         	}else if($rootScope.crmtype == 5){ //客户来源
     	                                         		cusType = 6;
     	                                         	}else if($rootScope.crmtype == 7){//意向产品
     	                                         		cusType = 8;
     	                                         	}else if($rootScope.crmtype == 9){//采购偏好
     	                                         		cusType = 10;
     	                                         	}else if($rootScope.crmtype == 11){//个性营销
     	                                         		cusType = 12;
     	                                         	}
                                        		  var point = $(".plandaylimit span");
	                                               	point.html('');//
	                                               	var pointContent = data.importaddress.reason+",如需继续发送将使用<span class='color-red'>系统代发模式</span>";
	                                               	point.append(pointContent);
	                                            	$('#dialog-planOverweightMonth').dialog({
	                                                    position: ["center", 100],
	                                                    modal: true,
	                                                    resizable: false,
	                                                    width: 350,
	                                                    maxHeight: 320,
	                                                    close:function(){
	                                                        $(this).dialog("destroy");
	                                                    },
	                                                    buttons: {
	                                                    	"继续执行提交计划": function () {
	                                                    		$("#loading").show();
	                                                    		$http.post('./plan_beforeAddMarketingPlan.action', {
	                                                     			 addressnum: $scope.mnum,
	                                                                 planweekmodel: planweekmodel
	                                                             }, $rootScope.postCfg).success(function (data) {
	                                                            	 $("#loading").hide();
	                                                           	  if(data.importaddress.result == 1){  //成功
	                                                           		$http.post('./plan_addMarketingPlan.action', {
		                                                                plancycle: plancycle,
		                                                                plangroupid: id,
		                                                                planweekmodel: planweekmodel,
		                                                                planexecutetime: planexecutetime,
		                                                                plantype: plantype,
		                                                                plantitle: plantitle,
		                                                                begintime: begintime,
		                                                                endtime: endtime,
		                                                                plan_differen:cusType,
		                                                                other_name: $rootScope.other_name,//如果是采购偏好和个性营销则就是查询条件值
		                                                            }, $rootScope.postCfg).success(function (data) {
		                                                                //成功之后做一些事情
		                                                                if(parseInt(data)==1){
		                                                                    if(parseInt(plantype)==0){
		                                                                        $rootScope.tipshow(1,'添加提醒成功');
		                                                                        $('#dialog-addressplan').dialog("destroy");
		                                                                    }else{
		                                                                        $rootScope.tipshow(1,'添加计划成功');
		                                                                        $('#dialog-addressplan').dialog("destroy");
		                                                                        $('#dialog-conform').dialog("destroy");
		                                                                    }
		                                                                    $(".lg-checkbox-n").attr('datasinglecheck',0);
		                                                                    $(".lg-checkbox-n").removeClass("checkbox-n-active");
		                                                                    $state.go('app.plan.planview');
		                                                                }else{
		                                                                    $rootScope.tipshow(0,'添加计划失败,请检查参数是否正确');
		                                                                }
		                                                            });
	                                                           		$(this).dialog("destroy");
	                                                           	  }else if(data.importaddress.result == 0){ //异常
	                                                           		  $rootScope.tipshow(0,data.importaddress.reason);
	                                                           	  }else if(data.importaddress.result == -1){  //总发送量超标
	                                                           		  $rootScope.tipshow(0,data.importaddress.reason);
	                                                           	  }else if(data.importaddress.result == -2){  //月发送量超标
	                                                           		  $rootScope.tipshow(0,data.importaddress.reason);
	                                                           	  }else if(data.importaddress.result == -3){  //日发送量超标
	                                                           		  $rootScope.tipshow(0,data.importaddress.reason);
	                                                           	  }
	                                                             });
	                                           				},
	                                           				"取消计划": function () {
	                                           					 $(this).dialog("destroy");
	                                           				}
	                                                    }
	                                                }); 
                                        	  }else{
                                        		  $rootScope.tipshow(0,data.importaddress.reason); 
                                        	  }
                                          })
                                	}
                                }
                            }
                            if (parseInt(v1) == 0) {
                                $('#dialog-contipform').dialog({
                                    position: ["center", 100],
                                    modal: true,
                                    resizable: false,
                                    width: 720,
                                    maxHeight: 500,
                                    close:function(){
                                        $(this).dialog("destroy");
                                    },
                                    buttons: {
                                        "确认保存": function () {
                                            submitplan();
                                            $(this).dialog("destroy");

                                        },
                                        "返回修改": function () {
                                            $(this).dialog("destroy");
                                        }
                                    }
                                });
                            } else {
                                $('#dialog-conform').dialog({
                                    position: ["center", 100],
                                    modal: true,
                                    resizable: false,
                                    width: 720,
                                    maxHeight: 500,
                                    close:function(){
                                        $(this).dialog("destroy");
                                    },
                                    buttons: {
                                        "确认提交执行计划": function () {
                                            submitplan();
                                        },
                                        "返回修改": function () {
                                            $(this).dialog("destroy");
                                        }
                                    }
                                });
                            }
                        },
                        "取消": function () {
                            $(".lg-checkbox-n").attr('datasinglecheck',0);
                            $(".lg-checkbox-n").removeClass("checkbox-n-active");
                            $(this).dialog("destroy");
                        }
                    }
                });
            };

        }]
    };
    function GetDateStr(AddDayCount) {
        var dd = new Date();
        dd.setDate(dd.getDate() + AddDayCount);//获取AddDayCount天后的日期
        var y = dd.getFullYear();
        var m = dd.getMonth() + 1;//获取当前月份的日期
        if(m<10){
            m="0"+m;
        }
        var d = dd.getDate();
        if(d<10){
            d="0"+d;
        }
        return y + "-" + m + "-" + d;
    }

    function GetDateDiffStr(begtime, AddDayCount) {
        var dd = new Date(begtime);
        dd.setDate(dd.getDate() + AddDayCount);//获取AddDayCount天后的日期
        var y = dd.getFullYear();
        var m = dd.getMonth() + 1;//获取当前月份的日期
        if(m<10){
            m="0"+m;
        }
        var d = dd.getDate();
        if(d<10){
            d="0"+d;
        }
        return y + "-" + m + "-" + d;
    }
    
    /**----------------修改(添加特殊节假日)之前--4------------------------*/
   //获取当前年份,为特殊节假日提供
    function GetHoliday(type){
    	 var myDate = new Date();
         var sdate,befDate = "";
     	if(type == 8){ //元旦
     		sdate = myDate.getFullYear()+1 + "-01-01";//正确时间
     		befDate = myDate.getFullYear() + "-12-29";//提前3天
     		return sdate+"###"+befDate;
     	}else if(type == 9){ //妇女节
     		sdate = myDate.getFullYear() + "-03-08";
     		befDate = myDate.getFullYear() + "-03-05";//提前3天
     		return sdate+"###"+befDate;
     	}else if(type == 10){ //劳动节
     		sdate = myDate.getFullYear() + "-05-01";
     		befDate = myDate.getFullYear() + "-04-28";//提前3天
     		return sdate+"###"+befDate;
     	}else if(type == 11){ //圣诞节
     		sdate = myDate.getFullYear() + "-12-25";
     		befDate = myDate.getFullYear() + "-12-22";//提前3天
     		return sdate+"###"+befDate;
     	}else if(type == 12){ //春 节
     		var obj = calendar.lunar2solar(myDate.getFullYear(),1,1);
     		var chunjie = obj.cYear + '-' + (obj.cMonth >= 10 ? obj.cMonth : '0' + obj.cMonth) + '-' + (obj.cDay >= 10 ? obj.cDay : '0' + obj.cDay);//获取当前时间
     		var datt = chunjie.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;
 			var newDate = beforeDat.getFullYear() + '-' + mon + '-' + da;
 			return chunjie+"###"+newDate;
     	}else if(type == 13){ //元宵节
     		var obj = calendar.lunar2solar(myDate.getFullYear(),1,15);
     		var yuanxiao = obj.cYear + '-' + (obj.cMonth >= 10 ? obj.cMonth : '0' + obj.cMonth) + '-' + (obj.cDay >= 10 ? obj.cDay : '0' + obj.cDay);//获取当前时间
     		var datt = yuanxiao.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;
 			var newDate = beforeDat.getFullYear() + '-' + mon + '-' + da;
 			return yuanxiao+"###"+newDate;
     	}else if(type == 14){ //清明节
     		sdate = myDate.getFullYear() + "-04-05";//正确时间
     		befDate = myDate.getFullYear() + "-04-02";//提前3天
     		return sdate+"###"+befDate;
     	}else if(type == 15){ //端午节
     		var obj = calendar.lunar2solar(myDate.getFullYear(),5,5);
     		var duanwu = obj.cYear + '-' + (obj.cMonth >= 10 ? obj.cMonth : '0' + obj.cMonth) + '-' + (obj.cDay >= 10 ? obj.cDay : '0' + obj.cDay);//获取当前时间
     		var datt = duanwu.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;
 			var newDate = beforeDat.getFullYear() + '-' + mon + '-' + da;
 			return duanwu+"###"+newDate;
     	}else if(type == 16){ //中秋节
     		var obj = calendar.lunar2solar(myDate.getFullYear(),8,15);
     		var zhongqiu = obj.cYear + '-' + (obj.cMonth >= 10 ? obj.cMonth : '0' + obj.cMonth) + '-' + (obj.cDay >= 10 ? obj.cDay : '0' + obj.cDay);//获取当前时间
     		var datt = zhongqiu.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;
 			var newDate = beforeDat.getFullYear() + '-' + mon + '-' + da;
 			return zhongqiu+"###"+newDate;
     	}else if(type == 17){ //国庆节
     		sdate = myDate.getFullYear() + "-10-01";
     		befDate = myDate.getFullYear() + "-09-28";
     		return sdate+"###"+befDate;
     	}else if(type == 18){ //儿童节
     		sdate = myDate.getFullYear() + "-06-01";
     		befDate = myDate.getFullYear() + "-05-29";
     		return sdate+"###"+befDate;
     	}else if(type == 19){ //父亲节
     		myDate.setMonth(5);
 			myDate.setDate(1);
 			if(myDate.getDay()==1){//星期1
 				myDate.setDate(21);
 			}else if(myDate.getDay()==2){//星期2
 				myDate.setDate(20);
 			}else if(myDate.getDay()==3){//星期3
 				myDate.setDate(19);
 			}else if(myDate.getDay()==4){//星期4
 				myDate.setDate(18);
 			}else if(myDate.getDay()==5){//星期5
 				myDate.setDate(17);
 			}else if(myDate.getDay()==6){//星期6
 				myDate.setDate(16);
 			}else{//星期7
 				myDate.setDate(15);
 			}
 			var oMonth = myDate.getMonth()+1;
 			var oDay  =myDate.getDate();
 			var fuqin = myDate.getFullYear() + '-' + (oMonth >= 10 ? oMonth : '0' + oMonth) + '-' + (oDay >= 10 ? oDay : '0' + oDay);//获取当前时间
     		var datt = fuqin.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;
 			var newDate = beforeDat.getFullYear() + '-' + mon + '-' + da;
 			return fuqin+"###"+newDate;
     	}else if(type == 20){ //母亲节
     		myDate.setMonth(4);
 			myDate.setDate(1);
 			if(myDate.getDay()==1){//星期1
 				myDate.setDate(14);
 			}else if(myDate.getDay()==2){//星期2
 				myDate.setDate(13);
 			}else if(myDate.getDay()==3){//星期3
 				myDate.setDate(12);
 			}else if(myDate.getDay()==4){//星期4
 				myDate.setDate(11);
 			}else if(myDate.getDay()==5){//星期5
 				myDate.setDate(10);
 			}else if(myDate.getDay()==6){//星期6
 				myDate.setDate(9);
 			}else{//星期7
 				myDate.setDate(8);
 			}
 			var oMonth = myDate.getMonth()+1;
 			var oDay  =myDate.getDate();
 			var muqin = myDate.getFullYear() + '-' + (oMonth >= 10 ? oMonth : '0' + oMonth) + '-' + (oDay >= 10 ? oDay : '0' + oDay);//获取当前时间
     		var datt = muqin.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;
 			var newDate = beforeDat.getFullYear() + '-' + mon + '-' + da;
 			return muqin+"###"+newDate;
     	}else if(type == 21){ //感恩节
     		myDate.setMonth(10);
 			myDate.setDate(1);
 			if(myDate.getDay()==1){//星期1
				myDate.setDate(25);
			}else if(myDate.getDay()==2){//星期2
				myDate.setDate(24);
			}else if(myDate.getDay()==3){//星期3
				myDate.setDate(23);
			}else if(myDate.getDay()==4){//星期4
				myDate.setDate(22);
			}else if(myDate.getDay()==5){//星期5
				myDate.setDate(28);
			}else if(myDate.getDay()==6){//星期6
				myDate.setDate(27);
			}else{//星期7
				myDate.setDate(26);
			}
 			var oMonth = myDate.getMonth()+1;
 			var oDay  =myDate.getDate();
 			var ganen = myDate.getFullYear() + '-' + (oMonth >= 10 ? oMonth : '0' + oMonth) + '-' + (oDay >= 10 ? oDay : '0' + oDay);//获取当前时间
     		var datt = ganen.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;
 			var newDate = beforeDat.getFullYear() + '-' + mon + '-' + da;
 			return ganen+"###"+newDate;
     	}else if(type == 22){ //印度排灯节
     		sdate = myDate.getFullYear() + "-10-30";
     		befDate = myDate.getFullYear() + "-10-27";
     		return sdate+"###"+befDate;
     	}else if(type == 23){ //俄罗斯新年
     		sdate = myDate.getFullYear() + "-01-14";
     		befDate = myDate.getFullYear() + "-01-11";
     		return sdate+"###"+befDate;
     	}else if(type == 24){ //伊斯兰开斋节
     		sdate = myDate.getFullYear() + "-06-15";
     		befDate = myDate.getFullYear() + "-06-12";
     		return sdate+"###"+befDate;
     	}else if(type == 25){ //耶稣复活节
     		sdate = myDate.getFullYear() + "-04-01";
     		befDate = myDate.getFullYear() + "-03-29";
     		return sdate+"###"+befDate;
     	}else if(type == 26){ //欧美万圣节
     		sdate = myDate.getFullYear() + "-10-31";
     		befDate = myDate.getFullYear() + "-10-28";
     		return sdate+"###"+befDate;
     	}
    }
    /**----------------修改(添加特殊节假日)之后--4------------------------*/
    //计算日期差
    function DateDiff(sDate1, sDate2) {  //sDate1和sDate2是yyyy-MM-dd格式

        var aDate, oDate1, oDate2, iDays;
        aDate = sDate1.split("-");
        oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);  //转换为yyyy-MM-dd格式
        aDate = sDate2.split("-");
        oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);
        iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数

        return iDays;  //返回相差天数
    }
    
    //获取当前年份,为特殊节假日提供
    function GetHoliday2(type){
        var myDate = new Date();
    	if(type == 8){ //元旦
    		return myDate.getFullYear() + "-12-29";
    	}else if(type == 9){ //妇女节
    		return myDate.getFullYear() + "-03-05";
    	}else if(type == 10){ //劳动节
    		return myDate.getFullYear() + "-04-28";
    	}else if(type == 11){ //圣诞节
    		return myDate.getFullYear() + "-12-22";
    	}else if(type == 12){ //春 节
    		var obj = calendar.lunar2solar(myDate.getFullYear(),1,1);
    		var chunjie = obj.cYear + '-' + (obj.cMonth >= 10 ? obj.cMonth : '0' + obj.cMonth) + '-' + (obj.cDay >= 10 ? obj.cDay : '0' + obj.cDay);//获取当前时间
    		var datt = chunjie.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;
			var newDate = beforeDat.getFullYear() + '-' + mon + '-' + da;
			return newDate;//提前3天
    	}else if(type == 13){ //元宵节
    		var obj = calendar.lunar2solar(myDate.getFullYear(),1,15);
    		var yuanxiao = obj.cYear + '-' + (obj.cMonth >= 10 ? obj.cMonth : '0' + obj.cMonth) + '-' + (obj.cDay >= 10 ? obj.cDay : '0' + obj.cDay);//获取当前时间
    		var datt = yuanxiao.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;
			var newDate = beforeDat.getFullYear() + '-' + mon + '-' + da;
			return newDate;//提前3天
    	}else if(type == 14){ //清明节
    		return myDate.getFullYear() + "-04-05";
    	}else if(type == 15){ //端午节
    		var obj = calendar.lunar2solar(myDate.getFullYear(),5,5);
    		var duanwu = obj.cYear + '-' + (obj.cMonth >= 10 ? obj.cMonth : '0' + obj.cMonth) + '-' + (obj.cDay >= 10 ? obj.cDay : '0' + obj.cDay);//获取当前时间
    		var datt = duanwu.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;
			var newDate = beforeDat.getFullYear() + '-' + mon + '-' + da;
			return newDate;//提前3天
    	}else if(type == 16){ //中秋节
    		var obj = calendar.lunar2solar(myDate.getFullYear(),8,15);
    		var zhongqiu = obj.cYear + '-' + (obj.cMonth >= 10 ? obj.cMonth : '0' + obj.cMonth) + '-' + (obj.cDay >= 10 ? obj.cDay : '0' + obj.cDay);//获取当前时间
    		var datt = zhongqiu.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;
			var newDate = beforeDat.getFullYear() + '-' + mon + '-' + da;
			return newDate;//提前3天
    	}else if(type == 17){ //国庆节
    		return myDate.getFullYear() + "-09-28";
    	}else if(type == 18){ //儿童节
    		return myDate.getFullYear() + "-05-29";
    	}else if(type == 19){ //父亲节
    		myDate.setMonth(5);
			myDate.setDate(1);
			if(myDate.getDay()==1){//星期1
				myDate.setDate(21);
			}else if(myDate.getDay()==2){//星期2
				myDate.setDate(20);
			}else if(myDate.getDay()==3){//星期3
				myDate.setDate(19);
			}else if(myDate.getDay()==4){//星期4
				myDate.setDate(18);
			}else if(myDate.getDay()==5){//星期5
				myDate.setDate(17);
			}else if(myDate.getDay()==6){//星期6
				myDate.setDate(16);
			}else{//星期7
				myDate.setDate(15);
			}
			var oMonth = myDate.getMonth()+1;
			var oDay  =myDate.getDate();
			var fuqin = myDate.getFullYear() + '-' + (oMonth >= 10 ? oMonth : '0' + oMonth) + '-' + (oDay >= 10 ? oDay : '0' + oDay);//获取当前时间
    		var datt = fuqin.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;
			var newDate = beforeDat.getFullYear() + '-' + mon + '-' + da;
			return newDate;//提前3天
    	}else if(type == 20){ //母亲节
    		myDate.setMonth(4);
			myDate.setDate(1);
			if(myDate.getDay()==1){//星期1
				myDate.setDate(14);
			}else if(myDate.getDay()==2){//星期2
				myDate.setDate(13);
			}else if(myDate.getDay()==3){//星期3
				myDate.setDate(12);
			}else if(myDate.getDay()==4){//星期4
				myDate.setDate(11);
			}else if(myDate.getDay()==5){//星期5
				myDate.setDate(10);
			}else if(myDate.getDay()==6){//星期6
				myDate.setDate(9);
			}else{//星期7
				myDate.setDate(8);
			}
			var oMonth = myDate.getMonth()+1;
			var oDay  =myDate.getDate();
			var muqin = myDate.getFullYear() + '-' + (oMonth >= 10 ? oMonth : '0' + oMonth) + '-' + (oDay >= 10 ? oDay : '0' + oDay);//获取当前时间
    		var datt = muqin.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;
			var newDate = beforeDat.getFullYear() + '-' + mon + '-' + da;
			return newDate;//提前3天
    	}else if(type == 21){ //感恩节
    		myDate.setMonth(10);
			myDate.setDate(1);
			if(myDate.getDay()==1){//星期1
				myDate.setDate(25);
			}else if(myDate.getDay()==2){//星期2
				myDate.setDate(24);
			}else if(myDate.getDay()==3){//星期3
				myDate.setDate(23);
			}else if(myDate.getDay()==4){//星期4
				myDate.setDate(22);
			}else if(myDate.getDay()==5){//星期5
				myDate.setDate(28);
			}else if(myDate.getDay()==6){//星期6
				myDate.setDate(27);
			}else{//星期7
				myDate.setDate(26);
			}
			var oMonth = myDate.getMonth()+1;
			var oDay  =myDate.getDate();
			var ganen = myDate.getFullYear() + '-' + (oMonth >= 10 ? oMonth : '0' + oMonth) + '-' + (oDay >= 10 ? oDay : '0' + oDay);//获取当前时间
    		var datt = ganen.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;
			var newDate = beforeDat.getFullYear() + '-' + mon + '-' + da;
			return newDate;//提前3天
    	}else if(type == 22){ //印度排灯节
    		return myDate.getFullYear() + "-10-27";
    	}else if(type == 23){ //俄罗斯新年
    		return myDate.getFullYear() + "-01-11";
    	}else if(type == 24){ //伊斯兰开斋节
    		return myDate.getFullYear() + "-06-12";
    	}else if(type == 25){ //耶稣复活节
    		return myDate.getFullYear() + "-03-29";
    	}else if(type == 26){ //欧美万圣节
    		return myDate.getFullYear() + "-10-28";
    	}
    }
})
    .directive('planradio2', function (CheckboxClick,$rootScope) {
        'use strict';

        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.click(function (e) {
                    CheckboxClick.plancheckinit();
                    scope.weekshow = true;
                    $('.temptable tbody').html('');
                    $('label').removeClass("yetCheck");
                    $rootScope.specificTime =[];//清空
                    $(".kalendae .k-days span").removeClass("k-selected");
                    $("#specifiedtime").html('');
                    var k = this.value;
                    
                    //获取当前日期
            		var mydate = new Date();
            		var weekdate = new Date(mydate);
            		
            		var gainYear = mydate.getFullYear();//获取当前年份
            		var gainMonth = mydate.getMonth()+1;//获取当前月份
	    	        if(gainMonth < 10){
	    	        	gainMonth="0"+gainMonth;
	    	        }
	    	        var gainDate = mydate.getDate();//获取当前日期
	    	        if(gainDate<10){
	    	        	gainDate="0"+gainDate;
	    	        }
            		//系统当前时间
            		var nowdate = gainYear +"-"+gainMonth+"-"+gainDate;
            		//一周后的时间
            		weekdate.setDate(mydate.getDate()+7);
            		var weekYear = weekdate.getFullYear();//获取当前年份
            		var weekMonth = weekdate.getMonth()+1;//获取一周后的月份
            		var weekDate = weekdate.getDate();//获取一周后的日期
            		 if(weekMonth < 10){
            			 weekMonth="0"+weekMonth;
 	    	        }
 	    	        if(weekDate<10){
 	    	        	weekDate="0"+weekDate;
 	    	        }
            		var nowWeekDate = weekYear +"-"+weekMonth+"-"+weekDate;
            		
                    $('#begintime').val(nowdate);//将系统当前时间指定开始时间
                    $('#endtime').val(nowWeekDate);//结束时间设置当前系统一周后的时间
                    if(k == 6){
                    	var oNav_span=$(".kalendae").length;
                    	if(oNav_span != 1){
                    		new Kalendae(document.getElementById("specifiedtime"), {
                                months:1,
                                mode:'multiple',
                                direction:'future',
                                subscribe: {
                                       'date-clicked': function (date) {
                                    	   var weekDay = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];  
                                           var dateStr = date._i;  
                                           var myDate = new Date(Date.parse(dateStr.replace(/-/g, "/")));  
                                    	   $rootScope.specificTime.push({
                                    		   date:date._i,
                                    		   chooseTime:weekDay[myDate.getDay()],
                                    	   })
                                    	   var array = $rootScope.specificTime;
                                    	   var newArray = [];
                                    	   var newArray2 = [];
	                                    	for(var i=0;i<array.length;i++){
	                                    	    var count = 0;
	                                    	    for(var j=0;j<array.length;j++){
	                                    	        if(array[i].date==array[j].date){
	                                    	            count++;
	                                    	        }
	                                    	    }
	                                    	    if(count==1){
	                                    	        newArray.push({
	                                    	        	date:array[i].date,
	                                    	        	chooseTime:array[i].chooseTime
	                                    	        });
	                                    	    }
	                                    	}
	                                    	//对时间进行排序
	                                    	var rows = newArray;
	                                    	rows.sort(function(a,b){
	                                    	    return Date.parse(a.date) - Date.parse(b.date);//时间正序
	                                    	});
	                                    	for(var i =0,l=rows.length;i<l;i++){
	                                    		newArray2.push({
	                                    	        	date:rows[i].date,
	                                    	        	chooseTime:rows[i].chooseTime
	                                    	       });
	                                    	}
	                                    	$rootScope.specificTime=newArray2;
                                       }
                                   }
                            });
                    	}
                    }
                    scope.$apply(function () {
                        scope.planshow = k;
                    });
                });
            }
        };
    }).directive('planradio1', function (CheckboxClick) {
        'use strict';

        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.click(function (e) {
                    CheckboxClick.plancheckinit();
                    scope.weekshow = true;
                    $('.temptable tbody').html('');
                    $('label').removeClass("yetCheck");
                    var k = this.value;
                    scope.$apply(function () {
                        scope.plantype = k;
                    });

                });
            }
        };
    }).directive('plancheckmon', function () {
        'use strict';
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.click(function (e) {
                	 var k = element.attr('weekdate');
                     var e = element.attr('datasinglecheck');
                     var temptable = $('.temptable tbody');
                	if(e == 0){
                		element.addClass("yetCheck");
                	}else{
                		element.removeClass("yetCheck");
                	}
                });
            }
        };
    }).directive('viewModelClick2', function ($state,$rootScope) {
        'use strict';

        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.on('click',function () {
                	  var tid = $(this).attr("tid");
                	  var url = $state.href('app.template.preview');
                	  if($rootScope.levelType == 2){ //公司模板
                		  window.open(url+"#mid"+tid+"@@@userType"+$rootScope.userType+"@@@ismanager"+$rootScope.ismanager,'_blank');
                	  }else if($rootScope.levelType == 3){//个人模板
                		  window.open(url+"#mid"+tid+"@@@userType"+$rootScope.userType,'_blank');
                	  }
                });
            }
        };
    }).directive('usringModelClick2', function (TempPost,$rootScope,$state) {
        'use strict';

        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.on('click',function () {
                	var modelid = $(this).attr("tid");
                	var modeltitle = $(this).attr("modeltitle");
                    $("tr[tag=" + chooseIndex + "]").attr('modelid',modelid);
                    $("tr[tag=" + chooseIndex + "] td").eq(1).html("<span class='label label-success' title='" + modeltitle + "'>模板ID: " + modelid + "</span>");
                    $('#dialog-choosetemp').dialog("destroy");
                });
            }
        };
    });

//选择模板
function addtempaddr(k) {
	chooseIndex = k;
    $('#dialog-choosetemp').dialog({
        position: ["center", 100],
        modal: true,
        resizable: false,
        width: 745,
        height:560,
        close:function(){
            $(this).dialog("destroy");
        },
//        buttons: {
//            "确定": function () {
//                var modelid=$(".modeltype").find('[photoclick=1]').attr('photoid');
//                if(modelid==undefined){
//                    alert("请选择模板");
//                    return false;
//                }
//                var modeltitle=$(".modeltype").find('[photoclick=1]').attr('modeltitle');
//                $("tr[tag=" + k + "]").attr('modelid',modelid);
//                $("tr[tag=" + k + "] td").eq(1).html("<span class='label label-success' title='" + modeltitle + "'>模板ID: " + modelid + "</span>");
//                $(this).dialog("destroy");
//                $('#dialog-choosetemp')
//            },
//            "取消": function () {
//                $(this).dialog("destroy");
//            }
//        }
    });
}


//删除退订地址
App.directive('deladdress', function () {
    'use strict';

    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            //####### Dialogs
            element.click(function (e) {
                e.stopPropagation();
                $("#dialog-addressip").dialog({
                    modal: true,
                    resizable: false,
                    close:function(){
                        $(this).dialog("destroy");
                    },
                    width: 350,
                    buttons: {
                        "确认删除": function () {
                        	scope.deladdr(attrs.cid);
                            $(this).dialog("destroy");
                        },
                        "取消": function () {
                            $(this).dialog("destroy");
                        }
                    }
                });
                
            });
        }
    };
}).directive('moveAddress', function (AddressManage) {
    'use strict';

    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.on('click',function (e) {
                //scope.clearinput();
                var ids = "";
                $(".addrcheck").each(function () {
                    if ($(this).attr("datafilecheck") == "1") {
                        ids = $(this).attr("cid") + "," + ids
                    }
                });
                ids = ids.substring(0, ids.length - 1);
                if(ids==""){
                    scope.tipshow(0,"请选择要移动的邮件地址");
                    return false;
                }
                $('#dialog-movetoaddresstype').dialog({
                    modal: true,
                    resizable: false,
                    width: 360,
                    close:function(){
                        $(this).dialog("destroy");
                    },
                    buttons: {
                        "确定": function () {
                            var id=$("#addressmovetypeid").val();
                            var tid=$("#addresstypeid").val();
                            AddressManage.moveto(ids,id).then(function(data){
                   /**-------------------修改移动成功后页面显示数据之前----------------------------*/
                                if(parseInt(data)==1){
                                	$("#addresstypeid").val(id);
                                    scope.tipshow(1,"移动成功");
                                    if(id==0){
                                    	scope.viewaddress({
                                            currpage:scope.CurrentPage,
                                            pagesize:scope.pagesize,
                                            condition:0,
                                            conditionvalue:""
                                        });
                                    }else{
                                    	scope.viewaddress({
                                            currpage:1,
                                            pagesize:scope.pagesize,
                                            condition:1,
                                            conditionvalue:id
                                        });
                                    	 scope.CurrentPage=1;
                                    }
                   /**-------------------修改移动成功后页面显示数据之后----------------------------*/
                                    /*scope.viewaddress({
                                        currpage: 1,
                                        pagesize: scope.pagesize,
                                        condition: 1,
                                        conditionvalue: tid,
                                    });*/
                  /**-------------------移动地址判断是否存在 --之前---------------------------*/        
                                }else if(parseInt(data)==-1){
                                	scope.tipshow(0,"地址已存在");
                                	$("#addresstypeid").val(id);
                                }
                   /**-------------------移动地址判断是否存在 --之后---------------------------*/  
                                else{
                                    scope.tipshow(0,"移动失败");
                                }
                            });
                            $(this).dialog("destroy");
                        },
                        "取消": function () {
                            $(this).dialog("destroy");
                        }
                    }
                });
            });
        }
    };
}).directive('manageAddressClick', function () {
    'use strict';
    
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            //####### Dialogs
            element.on('change',function (e) {
                scope.numPages = 1;
                var tid=this.value;
                scope.CurrentPage=1;
                $("#addresssearchcon").val("");
                if(tid==0){
                	var datapost = {
                        currpage: 1,
                        pagesize: scope.pagesize,
                        condition: 0,
                        conditionvalue: tid
                        };
                }else{
                	var datapost = {
                        currpage: 1,
                        pagesize: scope.pagesize,
                        condition: 1,
                        conditionvalue: tid
                        };
                }
                scope.viewaddress(datapost);
            });
        }
    };
})
//导出地址
.directive('exportAddress', function (AddressManage) {
    'use strict';

    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            //####### Dialogs
            element.on('click',function (e) {
                $('#dialog-addressexport').dialog({
                    modal: true,
                    resizable: false,
                    width: 360,
                    close:function(){
                        $(this).dialog("destroy");
                    },
                    buttons: {
                        "确定": function () {
                            var q=$("input:radio[name=exporttype]:checked").val();
                            if(q==1){
                                var ids = "";
                                $(".addrcheck").each(function () {
                                    if ($(this).attr("datafilecheck") == "1") {
                                        ids = $(this).attr("cid") + "," + ids
                                    }
                                });
                                ids = ids.substring(0, ids.length - 1);
                                if(ids == ""){
                                	scope.tipshow(0,"请选择要导出的邮件地址");
                                }
                                var postdata={
                                    condition:q,
                                    typeid:"",
                                    addressidstr:ids
                                }
                            }else{
                                var i=$("#addressexportid").val();
                                var postdata={
                                    condition:q,
                                    typeid:i,
                                    addressidstr:""
                                }
                            }
                            AddressManage.exportmail(postdata).then(function(data){
                                if(parseInt(data)==1){
                                    window.location.href="dowload.action?filename=emailaddress.xls&filedir=tempUserFile";
                                    scope.tipshow(1,"导出成功");
                                }else{
                                    scope.tipshow(0,"导出失败");
                                }
                            });
                            $(this).dialog("destroy");
                        },
                        "取消": function () {
                            $(this).dialog("destroy");
                        }
                    }
                });
            });
        }
    };
})
//导入地址文件
    .directive('importAddressFile', function (AddressManage) {
        'use strict';

        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                scope.clearinput();
                //####### Dialogs
                element.on('click',function (e) {
                    var addr_importtype_id=$("#addr_importtype_id").val();
                    var importaddressfile=$("#importaddressfile").val();
                    var option={
                        type: 'post',
                        url: './addr_addAddressImport.action',
                        dataType:'json',
                        iframe: true,
                        cache:false,
                        data:{
                            typeid:addr_importtype_id,
                            addrfilename:importaddressfile
                        },
                        success: function(msg){
                            scope.importaddressinfo=msg;
                            if (msg.importmap.result==1){
                  /**-----------修改--(批量添加数据时跳转页面为添加的分组页面)--之前--------------------------*/
                                $("#addresstypeid").val(addr_importtype_id);
                                if(addr_importtype_id == 0){
                                	scope.viewaddress({
                                		 currpage: scope.CurrentPage,
                                         pagesize: scope.pagesize,
                                         condition: 0,
                                         conditionvalue: ""
                                	});
                                }else{
                                	scope.viewaddress({
                               		 	currpage: 1,
                                        pagesize: scope.pagesize,
                                        condition: 1,
                                        conditionvalue: addr_importtype_id
                                	});
                                	scope.CurrentPage=1;	
                                }
                     /**-----------修改--(批量添加数据时跳转页面为添加的分组页面)--之后--------------------------*/ 	
//                                var datapost = {
//                                    currpage: scope.CurrentPage,
//                                    pagesize: scope.pagesize,
//                                    condition: 1,
//                                    conditionvalue: addr_importtype_id
//                                };
//                                scope.viewaddress(datapost);
                             //   scope.typesort();
                                $('#dialog-addressimportinfo').dialog({
                                    modal: true,
                                    resizable: false,
                                    width:700
                                });
                            }else if(msg.importmap.result==-1){
                                scope.tipshow(0,'上传的文件格式不支持');
                            }else if(msg.importmap.result==-2){
                                scope.tipshow(0,'上传的文件无数据');
                            }else if(msg.importmap.result==-3){
                                scope.tipshow(0,'上传的地址超过了此类别的最大存放量,还可导入'+msg.importmap.scnum+'条');
                            }else if(msg.importmap.result==-4){
                                scope.tipshow(0,'上传的地址超过了地址库的最大存放量,还可导入'+msg.importmap.scnum+'条');
                            }else if(msg.importmap.result==-5){
                                scope.tipshow(0,'文件最大导入条数超标,还可导入'+msg.importmap.scnum+'条');
                            }else{
                                scope.tipshow(0,'操作失败,请重试');
                            }
                            $("#dialog-manageaddress").dialog("destroy");
                        }
                    };
                    $("#addressimportForm").ajaxSubmit(option);
                });
            }
        };
    })
    //清空地址
    .directive('clearAddress', function (AddressManage) {
        'use strict';

        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                //####### Dialogs
                element.on('click', function () {
                    var id=attrs.cid;
                    $("#dialog-clearip").dialog({
                        modal: true,
                        resizable: false,
                        close:function(){
                            $(this).dialog("destroy");
                        },
                        width: 350,
                        buttons: {
                            "确认清空": function () {
                            	 AddressManage.clearmails(id).then(function(data){
                                     if(data==1){
                                         scope.typesort();
                                         scope.tipshow(1,"该组地址已被清空");
                                     }else{
                                         scope.tipshow(0,"清空失败");
                                     }
                                 })
                                $(this).dialog("destroy");
                            },
                            "取消": function () {
                                $(this).dialog("destroy");
                            }
                        }
                    });
                });
            }
        }
    })
    //查询地址
    .directive('addressStartSearch', function (AddressManage) {
        'use strict';

        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                //####### Dialogs
                element.on('click', function () {
                    var t=$("#addresssearchcon").val();
                    $("#addresstypeid").val(0);//当根据条件进行查询时,分类默认为0
                    scope.condition=2;
                    scope.CurrentPage=1;
                    var datapost = {
                        currpage: 1,
                        pagesize: scope.pagesize,
                        condition: 2,
                        conditionvalue: t
                    };
                    scope.viewaddress(datapost);
                });
            }
        }
    })
//所有点读-发邮件
    .directive('readSendMail', function ($state) {
        'use strict';

        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                //####### Dialogs
                element.on('click', function () {
                    var mails = "";
                    $(".addrcheck").each(function () {
                        if ($(this).attr("datafilecheck") == "1") {
                            mails = $(this).attr("email") + "," + mails
                        }
                    });
                    mails = mails.substring(0, mails.length - 1);
                    $state.go('app.email',{emails:mails,utype:6});
                });
            }
        }
    })
//点读导出
    .directive('sendReadExport', function ($rootScope,$http,ExportReadInfo){
        'use strict';
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.on('click',function(){
                    $("#dialog-sendreadinfo").dialog({
                        modal: true,
                        resizable: false,
                        width: 320,
                        maxHeight: 200,
                        close:function(){
                            $(this).dialog("destroy");
                        },
                        buttons: {
                            "立即导出": function () {
                                var readids="";
                                //判断复选框是否选中(选中:导出当前页,不选中:导出全部)
                                $(".addrcheck[datafilecheck=1]").each(function(){
                                    readids+=$(this).attr("cid")+",";
                                });
                                readids=readids.substring(0,readids.length-1);
                                var isrepeat=0;
                                if($("input:checkbox[name='read_repeat']").is(':checked')){
                                    isrepeat=1;
                                }
                                if(readids==""){
                                    scope.tipshow(0,"请选择用户导出");
                                    $(this).dialog("destroy");
                                    return false;
                                }
                                $("#dialog-loading").dialog({
                                    modal: true,
                                    resizable: false,
                                    autoOpen: true,
                                    dialogClass:'noTitleStuff',
                                    height:45
                                });
                                ExportReadInfo.exportinfo(isrepeat,0,readids).then(function (data) {
                                    if(parseInt(data)==1){
                                        $("#dialog-loading").dialog("destroy");
                                        window.location.href="dowload.action?filename=readinfo.xls&filedir=tempUserFile";
                                   /**--------------修改-导出数据后刷新数据-之前-------------------*/     
                                        scope.tipshow(1,"导出成功");
                                        var readpost={
                                                currpage:scope.CurrentPage,
                                                pagesize:scope.pagesize,
                                                condition:0,
                                                conditionvalue:""
                                            };
                                        scope.readlistall(readpost);
                                    /**-------------修改--导出数据后刷新数据-之后-------------------*/     
                                    }else{
                                        $("#dialog-loading").dialog("destroy");
                                        scope.tipshow(0,"导出失败");
                                    }
                                });
                                //var isrepeat
                                $(this).dialog("destroy");
                            },
                            "取消": function () {
                                $(this).dialog("destroy");
                            }
                        }
                    });

                })
            }
        }
    })

//所有点读-查询点读
    .directive('readSendSearch', function (AddressManage) {
        'use strict';
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                //####### Dialogs
                element.on('click', function () {
                    var year=$("#readbeginvalue").val();
                    var month=$("#readendvalue").val();
                    var e = year + "#" + month;
                    scope.condition=1;//定义全局变量
                    scope.CurrentPage = 1;
                    var readpost={
                        currpage:scope.CurrentPage,
                        pagesize:scope.pagesize,
                        condition:1,
                        conditionvalue:e
                    };
                    scope.readlistall(readpost);
                });
            }
        };
    }).directive('exportall', function (GetUserinfo) {
        'use strict';
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.on('click', function () {
                	$(".yyloading").show();//加载框
                	GetUserinfo.exportall().then(function(data){
                		$(".yyloading").hide();
                		 if(data == 1){
                			 window.location.href="dowload.action?filename=readinfo.xls&filedir=tempUserFile";
                			 scope.tipshow(1,"导出成功")
                		 }else{
                			 scope.tipshow(0,"导出失败");
                		 }
                	})
                });
            }
        };
    });