'设计',
						'2'=>'造价管理',
						'3'=>'业主',
						'4'=>'交通局',
						'5'=>'公路局',
						'6'=>'审计',
						'7'=>'财政',
						'8'=>'审核',
						'9'=>'施工',
						'10'=>'咨询',
						'11'=>'招标代理',
						'12'=>'监理',
						'13'=>'学校',
						'14'=>'个人',
						'15'=>'合作伙伴',
						);
	
	public $tooltip=array('1'=>array('L','点击筛选标签'),
						'2'=>array('M','点击筛选标签'),
						'3'=>array('N','点击筛选标签'),
						'4'=>array('O','点击筛选标签'),
						'5'=>array('P','点击筛选标签'),
						'6'=>array('Q','点击筛选标签'),
						'7'=>array('R','点击筛选标签'),
	);					
	public $webPath="http://cld.smartcost.com.cn/upload/emailAnnex/";
	
	function __construct() {
		//include './protected/config/common.conf.php';
		//include $config['BASE_PATH'].'diagnostic/debug.php';
		if(isset($_COOKIE["staff"])){
			if(!empty($_COOKIE["staff"])){
				Doo::loadModel ( 'staff' );
				$staff = new staff ();
				$this->staff=$staff->getUserByIdList($_COOKIE["staff"]);
				self::$NEW= $this->getReceiptCount();
				include './protected/controller/ReceiptController.php';
				include './protected/controller/MainController.php';
				ReceiptController::$NEW=self::$NEW;
				MainController::$NEW=self::$NEW;
				return "/";
			}
		}
		
		Doo::loadCore ( 'uri/DooUriRouter' );
		$router = new DooUriRouter ();
		$routeRs = $router->execute ( Doo::app ()->route, Doo::conf ()->SUBFOLDER );
			
		if($routeRs['1']!="login"){
			header ( 'Content-Type:text/html;charset=utf-8' );
			@header ( "Location: /login"  );
		}
	}
	
	function sms(){
		
		Doo::loadModel('tag');
		$tag=new tag();
		Doo::loadModel('district');
		$district= new district();
		
		$tagList=$tag->getAllBySid($this->staff[0]['sid']);
		$districtList=$district->get_lv(1);
		
		$data['tagList']=$tagList;
		$data['districtList']=$districtList;
		$data['memu']="eMailTask";
		$data['staff']=$this->staff;
		$data['mailMemu']='sms';
		
		$this->render ( "/sms_create", $data );
	}
	
	function createSms(){
		$title=$this->get_args('title')?$this->get_args('title'):"";
		$content=isset($_POST['content'])?$_POST['content']:"";
		$tagId=$this->get_args('tagId')?$this->get_args('tagId'):array();
		
		$did=$this->get_args('did')?$this->get_args('did'):"";
		$stype=$this->get_args('stype')?$this->get_args('stype'):"";
		$kind=$this->get_args('kind')?$this->get_args('kind'):1;
		
		if (!empty($content)&&(!empty($tagId)||!empty($did))){
			Doo::loadModel('sms');
			$sms=new sms();
			Doo::loadModel('tag_client');
			$tagClient=new tag_client();
			Doo::loadModel('client');
			$client=new client();
			
			$tagCondition="";$tagArray=array();
			foreach ($tagId as $value){
				array_push($tagArray, " tag like '%".$value."%' ");
			}
			if(!empty($tagArray))
				$tagCondition=' and ('.implode(" or ", $tagArray).')';
			$clientList=$tagClient->find(array('select'=>'client','where'=>'sid='.$this->staff[0]['sid'].$tagCondition,'asArray'=>true));
			
			$clientArray=array();
			foreach ($clientList as $value){
				array_push($clientArray, $value['client']);
			}
			$clientEmailList=array();
			if (!empty($clientArray))
				$clientEmailList=$client->find(array('select'=>'nicename as clientname,companyname,telephone','where'=>'cid in ('.implode(",", $clientArray).')','asArray'=>true));
			
			if ($stype==2)	
				$clientEmailList=$client->find(array('select'=>'nicename as clientname,companyname,telephone','where'=>'district like "'.$did.',%" ','asArray'=>true));
			
			$list=array();$illegal=array();	
			foreach ($clientEmailList as $value){	
				if (preg_match("/^13[0-9]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$/",$value['telephone']))
					array_push($list, $value);
				else
					array_push($illegal, $value);
			}
			
			if ($stype==1){
				$sms->tag=implode(",", $tagId);
				$sms->districtId=0;
			}
			if ($stype==2){
				$sms->tag="";
				$sms->districtId=$did;
			}
			
			$sms->date=date("Y-m-d");
			$sms->content=$content;//base64_encode(gzcompress(json_encode($emailArray)));
			$sms->title=$title;
			$sms->client=base64_encode(gzcompress(json_encode($list)));
			$sms->illegal=json_encode(array_slice($illegal,0,100));
			$sms->signature=1;
			$sms->status=1;
			$sms->kind=$kind;
			$sms->date=date("Y-m-d");
			//$sms->tag=implode(",", $tagId);
			//$sms->districtId=$did;
			$sms->category=$this->staff[0]['category'];
			$sms->staffId=$this->staff[0]['sid'];
			$sms->staffName=$this->staff[0]['username'];
			$sms->insert();
			return '/smsList';
		}
		return '/createSms';
	}
	
	function editSmsView(){
		$sid=isset($this->params['sid'])?$this->params['sid']:0;
		//$sid=$this->get_args('sid')?$this->get_args('sid'):0;
		
		Doo::loadModel('tag');
		$tag=new tag();
		Doo::loadModel('district');
		$district= new district();
		
		$smsInfo=array();
		if(!empty($sid)){
			Doo::loadModel('sms');
			$sms=new sms();
			$smsInfo=$sms->getOne(array('where'=>'sid = '.$sid,'asArray'=>true));
			$smsInfo['tagList']=explode(",", $smsInfo['tag']);
		}else 
			return "/smsList";
		
		$tagList=$tag->getAllBySid($this->staff[0]['sid']);
		$districtList=$district->get_lv(1);
		
		$tagHtml='';
		foreach ($tagList as $key=>$value){
			$tagHtml.='';
		}
		
		$districtHtml='';
		foreach ($districtList as $key=>$value){
			$districtHtml.='';
		}
		
		$data['districtHtml']=$districtHtml;
		$data['tagHtml']=$tagHtml;
		$data['smsInfo']=$smsInfo;
		$data['tagList']=$tagList;
		$data['districtList']=$districtList;
		$data['memu']="eMailTask";
		$data['staff']=$this->staff;
		$data['mailMemu']='smsList';
		
		$this->render ( "/sms_edit", $data );
	}
	
	function editSms(){
		$sid=$this->get_args('sid')?$this->get_args('sid'):0;
		$title=$this->get_args('title')?$this->get_args('title'):"";
		$content=isset($_POST['content'])?$_POST['content']:"";
		$tagId=$this->get_args('tagId')?$this->get_args('tagId'):array();
		
		$did=$this->get_args('did')?$this->get_args('did'):"";
		$stype=$this->get_args('stype')?$this->get_args('stype'):"";
		$kind=$this->get_args('kind')?$this->get_args('kind'):1;
		
		if (!empty($content)&&!empty($sid)&&(!empty($tagId)||!empty($did))){
			Doo::loadModel('sms');
			$sms=new sms();
			Doo::loadModel('tag_client');
			$tagClient=new tag_client();
			Doo::loadModel('client');
			$client=new client();
			
			$tagCondition="";$tagArray=array();
			foreach ($tagId as $value){
				array_push($tagArray, " tag like '%".$value."%' ");
			}
			if(!empty($tagArray))
				$tagCondition=' and ('.implode(" or ", $tagArray).')';
			$clientList=$tagClient->find(array('select'=>'client','where'=>'sid='.$this->staff[0]['sid'].$tagCondition,'asArray'=>true));
			
			$clientArray=array();
			foreach ($clientList as $value){
				array_push($clientArray, $value['client']);
			}
			$clientEmailList=array();
			if (!empty($clientArray))
				$clientEmailList=$client->find(array('select'=>'nicename as clientname,companyname,telephone','where'=>'cid in ('.implode(",", $clientArray).')','asArray'=>true));
			
			if ($stype==2)	
				$clientEmailList=$client->find(array('select'=>'nicename as clientname,companyname,telephone','where'=>'district like "'.$did.',%" ','asArray'=>true));
			
			$list=array();$illegal=array();	
			foreach ($clientEmailList as $value){	
				if (preg_match("/^13[0-9]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$/",$value['telephone'])){
					array_push($list, $value);
				}else{
					array_push($illegal, $value);
				}
			}
			
			$sms->date=date("Y-m-d");
			$sms->content=$content;//base64_encode(gzcompress(json_encode($emailArray)));
			$sms->title=$title;
			$sms->client=base64_encode(gzcompress(json_encode($list)));
			$sms->illegal=json_encode(array_slice($illegal,0,100));
			$sms->signature=1;
			$sms->status=1;
			$sms->kind=$kind;
			$sms->date=date("Y-m-d");
			
			if ($stype==1){
				$sms->tag=implode(",", $tagId);
				$sms->districtId=0;
			}
			if ($stype==2){
				$sms->tag="";
				$sms->districtId=$did;
			}
			
			$sms->staffId=$this->staff[0]['sid'];
			$sms->staffName=$this->staff[0]['username'];
			$sms->update(array('where'=>'sid='.$sid,'asArray'=>true));
			return '/smsList';
		}
		return '/smsList';
	}
		
	function smsList(){
		Doo::loadModel('sms');
		$sms=new sms();
		Doo::loadModel('tag');
		$tag=new tag();
		
		$mailList=$sms->find(array('where'=>'staffId='.$this->staff[0]['sid'],'asc'=>'status','asArray'=>true));
		
		foreach ($mailList as $key=>$value){
			$mailList[$key]['clientName']=json_decode(gzuncompress(base64_decode($value['client'])),true);
			$mailList[$key]['illegalEmail']=json_decode($value['illegal'],true);
			$mailList[$key]['clientCount']=count($mailList[$key]['client']);
			$mailList[$key]['tag']=array();
			if($value['kind']==1)
				$mailList[$key]['kindName']='营销';
			else 
				$mailList[$key]['kindName']='通知';
			if (!empty($value['tag']))
				$mailList[$key]['tag']=$tag->find(array('where'=>'tid in ( '.$value['tag'].') ','asArray'=>true));
		}
		
		$data['mailList']=$mailList;
		$data['memu']="eMailTask";
		$data['staff']=$this->staff;
		$data['mailMemu']='smsList';
		
		$this->render ( "/sms_list", $data );
	}
	
	function smsCenter(){
		$year=$this->get_args('year')?$this->get_args('year'):date("Y");
		$month=$this->get_args('month')?$this->get_args('month'):0;
		
		Doo::loadModel('sms');
		$sms=new sms();
		Doo::loadModel('tag');
		$tag=new tag();
		
		$dateCondition="Year(date) =".$year;	
		if(!empty($month))
			$dateCondition="Year(date) =".$year." and Month(date) = ".$month;
		$mailList=$sms->find(array('where'=>$dateCondition,'asc'=>'status','asArray'=>true));
		
		foreach ($mailList as $key=>$value){
			$mailList[$key]['clientName']=json_decode(gzuncompress(base64_decode($value['client'])),true);
			$mailList[$key]['illegalEmail']=json_decode($value['illegal'],true);
			$mailList[$key]['clientCount']=count($mailList[$key]['client']);
			if($value['kind']==1)
				$mailList[$key]['kindName']='营销';
			else 
				$mailList[$key]['kindName']='通知';
			$mailList[$key]['tag']=array();
			if (!empty($value['tag']))
				$mailList[$key]['tag']=$tag->find(array('where'=>'tid in ( '.$value['tag'].') ','asArray'=>true));
		}
		
		$dateHtml="";$now=date("Y");
		for ($YEARD=2014;$YEARD<=2050;$YEARD++){
			if ($YEARD<=$now){
				$dateHtml.='';
			}
		}
		$monthHtml='';
		for ($i=1;$i<=12;$i++){
			$monthHtml.='';
		}
		
		$data['monthHtml']=$monthHtml;
		$data['dateHtml']=$dateHtml;
		$data['mailList']=$mailList;
		$data['memu']="eMailTask";
		$data['staff']=$this->staff;
		$data['mailMemu']='smsCenter';
		
		$this->render ( "/sms_center", $data );
	}
	
	function authOrize(){
		$kind=isset($this->params['kind'])?$this->params['kind']:0;
		$sid=isset($this->params['sid'])?$this->params['sid']:0;
		if (!empty($kind)&&!empty($sid)){
			Doo::loadModel('sms');
			$sms=new sms();
			if ($kind==1)
				$sms->status=3;
			else 
				$sms->status=2;
			
			$sms->mark=$this->staff[0]['username']."已同意";
			$sms->update(array('where'=>'sid='.$sid,'asArray'=>true));
		}
		return '/smsCenter';
	}
	
	function delete(){
		$sid=isset($this->params['sid'])?$this->params['sid']:0;
		if (!empty($sid)){
			Doo::loadModel('sms');
			$sms=new sms();
			$sms->delete(array('where'=>'sid='.$sid));
		}
		return '/smsList';
	}
	function sendSms(){
		$sid=isset($this->params['sid'])?$this->params['sid']:0;
		
		Doo::loadModel('sms');
		$sms=new sms();
		
		if(!empty($sid)){
			$smsInfo=$sms->getOne(array('where'=>'sid='.$sid,'asArray'=>true));
			if(!empty($smsInfo)&&$smsInfo['kind']==2&&$smsInfo['status']==2){
				$smsPhone=json_decode(gzuncompress(base64_decode($smsInfo['client'])),true);
				
				$telephoneMun=array();$clientName=array();
				foreach ($smsPhone as $key=>$value){
					array_push($telephoneMun, $value['telephone']);
					array_push($clientName, $value['clientname']);
				}
				$telephoneMun=implode(",", $telephoneMun);
				$clientName=implode("{|}", $clientName);
				
				$url='http://smsapi.c123.cn/OpenPlatform/OpenApi?';
				$ac='1001@501046820001';
				$authkey = 'DD59699A324759EACB0ECECE564D1256';
				$csid='4496';  //签名编号 
				$cgid='2733'; //通道组编号
				
				$t=date('YmdGis',strtotime(" +10 seconds ")); //发送时间
				$c = '{p1}您好!'.$smsInfo['content'];
				$m= $telephoneMun;	//号码
				$p1=$clientName;
				
				$data = array('action'=>'sendParam',  //发送类型 ,可以有sendOnce短信发送,sendBatch一对一发送,sendParam	动态参数短信接口
							  'ac'=>$ac,'authkey'=>$authkey,'cgid'=>$cgid,        
							  'm'=>$m,		     //号码
				  			  'c'=>$c,		    //如果页面是gbk编码,则转成utf-8编码,如果是页面是utf-8编码,则不需要转码,内容用{|},如测试一{|}测试二
							  'csid'=>$csid,            //签名编号 ,可以为空,为空时使用系统默认的签名编号
							  't'=>$t,                      //定时发送,为空时表示立即发送,yyyyMMddHHmmss 如:20130721182038
							  'p1'=>$p1  
						);
				
				$re= $this->postSMS($url,$data);
				preg_match_all('/result="(.*?)"/',$re,$res);
				if(trim($res[1][0]) == '1' ){
					$sms->status=3;
					$sms->errorInfo="";
					$sms->update(array('where'=>'sid='.$sid));
				}else{
					switch(trim($res[1][0])){
					case  0: $sms->errorInfo="帐户格式不正确(正确的格式为:员工编号@企业编号)";break; 
					case  -1: $sms->errorInfo="服务器拒绝(速度过快、限时或绑定IP不对等)如遇速度过快可延时再发";break;
					case  -2: $sms->errorInfo=" 密钥不正确";break;
					case  -3: $sms->errorInfo="密钥已锁定";break;
					case  -4: $sms->errorInfo="参数不正确(内容和号码不能为空,手机号码数过多,发送时间错误等)";break;
					case  -5: $sms->errorInfo="无此帐户";break;
					case  -6: $sms->errorInfo="帐户已锁定或已过期";break;
					case  -7: $sms->errorInfo="帐户未开启接口发送";break;
					case  -8: $sms->errorInfo="不可使用该通道组";break;
					case  -9: $sms->errorInfo="帐户余额不足";break;
					case  -10: $sms->errorInfo="内部错误";break;
					case  -11: $sms->errorInfo="扣费失败";break;
					default:break;
					}
					$sms->update(array('where'=>'sid='.$sid));
				}
			}
		}
		return "/smsList";
	}  
	
	function downLoadSms(){
		//include Doo::conf()->BASE_PATH.'diagnostic/debug.php';
		$sid=isset($this->params['sid'])?$this->params['sid']:0;
		Doo::loadModel('sms');
		$sms=new sms();
		if(!empty($sid)){
			$smsInfo=$sms->getOne(array('where'=>'sid='.$sid,'asArray'=>true));
			$smsPhone=json_decode(gzuncompress(base64_decode($smsInfo['client'])),true);
			$fileContent="";
			$filepath=DOO::conf()->SITE_PATH."upload/sms/telephone.txt";
			foreach ($smsPhone as $key=>$value){
				$fileContent.=$value['telephone'].','.$value['clientname'].'您好!'.$smsInfo['content'].PHP_EOL;
			}
			file_put_contents($filepath, $fileContent);
			
			header('Content-Description: File Transfer');
			header('Content-Type: application/octet-stream');
			header('Content-Disposition: attachment; filename='.basename($filepath));
			header('Content-Transfer-Encoding: binary');
			header('Expires: 0');
			header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
			header('Pragma: public');
			header('Content-Length: ' . filesize($filepath));
			readfile($filepath);
		}
	}
	
	private function postSMS($url,$data=''){
		$row = parse_url($url);
		$host = $row['host'];
		$port = $row['port'] ? $row['port']:80;
		$file = $row['path'];
		while (list($k,$v) = each($data)) {
			//$post .= rawurlencode($k)."=".rawurlencode($v)."&";	//转URL标准码
			$post .= $k."=".$v."&";
		}
		$post = substr( $post , 0 , -1 );
		$len = strlen($post);
		$fp = @fsockopen( $host ,$port, $errno, $errstr, 10);
		if (!$fp) {
			return "$errstr ($errno)\n";
		} else {
			$receive = '';
			$out = "POST $file HTTP/1.0\r\n";
			$out .= "Host: $host\r\n";
			$out .= "Content-type: application/x-www-form-urlencoded\r\n";
			$out .= "Connection: Close\r\n";
			$out .= "Content-Length: $len\r\n\r\n";
			$out .= $post;		
			fwrite($fp, $out);
			while (!feof($fp)) {
				$receive .= fgets($fp, 128);
			}
			fclose($fp);
			$receive = explode("\r\n\r\n",$receive);
			unset($receive[0]);
			return implode("",$receive);
		}
	}
	
	
	private function getReceiptCount(){
		
		$status=2;
		$year=date('Y');
		
		Doo::loadModel('receipt');
		$receipt=new receipt();
		Doo::loadModel('verify');
		$verify=new verify();
		
		//user verify ID
		$vidList=array();
		$verifyDetail=$verify->find(array('where'=>'staff like "%\"'.$this->staff[0]['sid'].'\"%"','asArray'=>true));
		foreach ($verifyDetail as $key=>$value){
			array_push($vidList, $value['vid']);
		}
		$vid=implode(",", $vidList);
		if(empty($verifyDetail))
			$vid=0;
		
		$dateCondition=" and Year(date) =".$year;	
		$approvalCondition=' and verifyStaff not like "%\"'.$this->staff[0]['sid'].'\":{%" ';
			
		$receiptList=$receipt->find(array('where'=>'verify in('.$vid.') and status='.$status.$dateCondition.$approvalCondition,'desc'=>'rid','asArray'=>true));
		
		return count($receiptList);
	}
	
	private function _GetFileEXT($filename) {
		$pics = explode ( '.', $filename );
		$num = count ( $pics );
		return $pics [$num - 1];
	}
	/**
	 * 获取get或者POST值
	 * @param string $name 属性名称
	 * @return fixed 值
	 */
	private function get_args($name) {
		if (isset ( $_GET [$name] )) {
			if (is_array ( $_GET [$name] ))
				return $_GET [$name];
			else {
				return addslashes ( $_GET [$name] );
		//return  $_GET [$name] ;
			}
		
		} elseif (isset ( $_POST [$name] )) {
			if (is_array ( $_POST [$name] ))
				return $_POST [$name];
			else {
				return addslashes ( $_POST [$name] );
		//return $_POST [$name];
			}
		} else 
			return false;
	}
}
?>