<?php

    if (!defined('BASEPATH'))
        exit('No direct script access allowed');


    class Pushzhou_model extends MY_Model
    {

        function __construct()
        {
            parent::__construct();
            $this->memkey='mypush'.GB_CITY;
			$this->load->model("user_model");
            $this->load->model("house_model");
            $this->load->model("block_model");
            $this->load->model("broker_model");

        }
		
		 /**
         * 查找是否有求购信息加入推送表
         * @param type $uid
         * @return array
         */
        function addbuy($uid,$city=GB_CITY,$sendtime)
        {
		  global $house;
          $buydetail = $this->user_model->get_buy_by_uid($uid,0,1,$sendtime);
		  if(is_array($buydetail) && !empty($buydetail) && $buydetail[0]['infofrom']!=1){
		  $arr['uid'] = $uid;
		  $arr['addtime'] = time();
		  $arr['level'] = 5;
		  $content['address'] = $buydetail[0]['address'];
		  $content['infotype'] = $house['infotype'][$buydetail[0]['infotype']];
		  $content['buildarea'] = $buydetail[0]['buildarea1'].'-'.$buydetail[0]['buildarea2'];
		  $content['price'] = $buydetail[0]['price1'].'-'.$buydetail[0]['price2'];
		  $content['buildyear'] = $buydetail[0]['buildyear1'].'-'.$buydetail[0]['buildyear2'];
		  $content['remark'] = $buydetail[0]['remark'];
		  $content['priceunit'] = '万元';
		  $arr['content'] = serialize($content);
		  $arr['telno'] =  $buydetail[0]['telno'];
		  $arr['sendid'] = $buydetail[0]['id'];
		  $arr['sendkind'] = 1;
		  $arr['tbl'] = 'sell';
		  $arr['cityname'] = GB_CITY;
		  $return = $this->addpush($arr);
		  if($return>0)
		  {
		  return 1;
		  }else{
		  return 0;
		  }
		  }else{
		  return 0;
		  }
         
        }
		
	    /**
         * 查找是否有求购信息加入推送表
         * @param type $uid
         * @return array
         */
        function addrentwanted($uid,$city=GB_CITY,$sendtime)
        {
		  global $house;
          $rentwantdetail = $this->user_model->get_rentwant_by_uid($uid,0,1,$sendtime);
		  if(is_array($rentwantdetail) && !empty($rentwantdetail) && $rentwantdetail[0]['infofrom']!=1){
		  $arr['uid'] = $uid;
		  $arr['addtime'] = time();
		  $arr['level'] = 5;
		  $content['address'] = $rentwantdetail[0]['address'];
		  $content['infotype'] = $house['infotype'][$rentwantdetail[0]['infotype']];
		  $content['buildarea'] = $rentwantdetail[0]['buildarea1'].'-'.$rentwantdetail[0]['buildarea2'];
		  $content['price'] = $rentwantdetail[0]['price1'].'-'.$rentwantdetail[0]['price2'];
          $content['priceunit'] = '元/月';
		  $content['renttype'] = $house['renttype'][$rentwantdetail[0]['renttype']];
		  $content['remark'] = $rentwantdetail[0]['remark'];
		 
		  $arr['content'] = serialize($content);
		  $arr['telno'] =  $rentwantdetail[0]['telno'];
		  $arr['sendid'] = $rentwantdetail[0]['id'];
		  $arr['sendkind'] = 1;
		  $arr['tbl'] = 'rent';
		  $arr['cityname'] = GB_CITY;
		  $return = $this->addpush($arr);
		  if($return>0)
		  {
		  return 1;
		  }else{
		  return 0;
		  }
		  }else{
		  return 0;
		  }
         
        }

	    /**
         * 查找是否有求购信息加入推送表
         * @param type $uid
         * @return array
         */
        function addseehouse($uid,$telno,$sendtime)
        {
          global $house;
          $seehousedetail = $this->user_model->get_seehouse_by_telno($telno,$sendtime);
          if(!empty($seehousedetail)){
          //获取房源信息
          $where = array('id'=>$seehousedetail[0]['rowid']);
          if($seehousedetail[0]['tbl']=='sell'){
          $select = array('id','infotype','uid','infofrom','district','streetid','blockshowname','price','buildarea','floor','subfloor','totalfloor','room','hall','toilet','kitchen','fitment','buildyear'); 
          $housedetail = $this->house_model->gethousebywhere($where,'sell',$select,0,1);
          }else{
          $select = array('id','infotype','uid','infofrom','district','streetid','blockshowname','price','buildarea','floor','subfloor','totalfloor','room','hall','toilet','kitchen','fitment','renttype','priceunit'); 
          $housedetail = $this->house_model->gethousebywhere($where,'rent',$select,0,1);          
          }
          if(empty($housedetail)) return 0;
          //获取街道和经纪人信息
          $streetname = $this->block_model->getstreetname($housedetail[0]['streetid']);
          $brokername = $this->broker_model->getbrokerdetail($housedetail[0]['uid']);
		  $arr['uid'] = $uid;
		  $arr['addtime'] = time();
		  $arr['level'] = 5;
		  $content['infotype'] = $house['infotype'][$housedetail[0]['infotype']];
		  $content['brokername'] = $brokername['truename'];
		  $content['district'] = $housedetail[0]['district'];
		  $content['streetname'] = $streetname['streetname'] ;
		  $content['blockshowname'] = $housedetail[0]['blockshowname'];
		  $content['buildarea'] = $housedetail[0]['buildarea'];
          $content['floor'] = empty($housedetail[0]['subfloor'])?$housedetail[0]['floor'].'/'.$housedetail[0]['totalfloor'].'层':$housedetail[0]['subfloor'].'-'.$housedetail[0]['floor'].'/'.$housedetail[0]['totalfloor'].'层';
          $content['room'] = $housedetail[0]['room']?$housedetail[0]['room'].'室':'';
          $content['hall'] = $housedetail[0]['hall']?$housedetail[0]['hall'].'厅':'';
          $content['toilet'] = $housedetail[0]['room']?$housedetail[0]['room'].'卫':'';
          $content['kitchen'] = $housedetail[0]['room']?$housedetail[0]['room'].'厨':'';
          $content['fitment'] = $housedetail[0]['fitment'];
          if($seehousedetail[0]['tbl']=='sell'){
          $content['buildyear'] = $housedetail[0]['buildyear']?$housedetail[0]['buildyear']:'';
          $content['price'] = $housedetail[0]['price']?$housedetail[0]['price']:'';
		  $content['priceunit'] = '万元';
           $content['averprice'] = floor($housedetail[0]['price']*10000/$housedetail[0]['buildarea']).'元/平方米'; 
          }else{
          $content['price'] = $housedetail[0]['price']?$housedetail[0]['price']:'';
          $content['priceunit'] = $house['priceunit'][$housedetail[0]['priceunit']];
          $content['renttype'] =  $housedetail[0]['renttype'];
          }

		  $arr['content'] = serialize($content);
		  $arr['telno'] =  $telno;
		  $arr['sendid'] = $seehousedetail[0]['id'];
		  $arr['sendkind'] = 2;
		  $arr['tbl'] = $seehousedetail[0]['tbl'];
		  $arr['cityname'] = GB_CITY;
          
		  $return = $this->addpush($arr);
          if($return>0)
		  {
		  return 1;
		  }else{
		  return 0;
		  }
		  }else{
		  return 0;
		  }
        }

	    /**
         * 查找是否有关注信息加入推送表
         * @param type $uid
         * @return array
         */
        function addcollecthouse($uid,$telno,$sendtime)
        {
          global $house;
          $collecthousedetail = $this->user_model->get_collecthouse_by_uid($uid,GB_CITY,$sendtime);
          if(!empty($collecthousedetail)){
          //获取房源信息
          $where = array('id'=>$collecthousedetail['collect_id']);
          if($collecthousedetail['kind']=='3'){
          $select = array('id','infotype','uid','infofrom','district','streetid','blockshowname','price','buildarea','floor','subfloor','totalfloor','room','hall','toilet','kitchen','fitment','buildyear'); 
          $housedetail = $this->house_model->gethousebywhere($where,'sell',$select,0,1);
          }else{
          $select = array('id','infotype','uid','infofrom','district','streetid','blockshowname','price','buildarea','floor','subfloor','totalfloor','room','hall','toilet','kitchen','fitment','renttype','priceunit'); 
          $housedetail = $this->house_model->gethousebywhere($where,'rent',$select,0,1);          
          }
          if(empty($housedetail)) return 0;
          //获取街道和经纪人信息
          $streetname = $this->block_model->getstreetname($housedetail[0]['streetid']);
          $brokername = $this->broker_model->getbrokerdetail($housedetail[0]['uid']);
		  $arr['uid'] = $uid;
		  $arr['addtime'] = time();
		  $arr['level'] = 4;
		  $content['infotype'] = $house['infotype'][$housedetail[0]['infotype']];
		  $content['brokername'] = $brokername['truename'];
		  $content['district'] = $housedetail[0]['district'];
		  $content['streetname'] = $streetname['streetname'] ;
		  $content['blockshowname'] = $housedetail[0]['blockshowname'];
		  
          $content['buildarea'] = $housedetail[0]['buildarea'];
          $content['floor'] = empty($housedetail[0]['subfloor'])?$housedetail[0]['floor'].'/'.$housedetail[0]['totalfloor'].'层':$housedetail[0]['subfloor'].'-'.$housedetail[0]['floor'].'/'.$housedetail[0]['totalfloor'].'层';
          $content['room'] = $housedetail[0]['room']?$housedetail[0]['room'].'室':'';
          $content['hall'] = $housedetail[0]['hall']?$housedetail[0]['hall'].'厅':'';
          $content['toilet'] = $housedetail[0]['room']?$housedetail[0]['room'].'卫':'';
          $content['kitchen'] = $housedetail[0]['room']?$housedetail[0]['room'].'厨':'';
          $content['fitment'] = $housedetail[0]['fitment'];
          if($collecthousedetail['kind']=='3'){
          $content['buildyear'] = $housedetail[0]['buildyear']?$housedetail[0]['buildyear']:'';
          $content['price'] = $housedetail[0]['price']?$housedetail[0]['price']:'';
		  $content['priceunit'] = '万元';
          $content['averprice'] = floor($housedetail[0]['price']*10000/$housedetail[0]['buildarea']).'元/平方米'; 

          }else{
          $content['price'] = $housedetail[0]['price']?$housedetail[0]['price']:'';
          $content['priceunit'] = $house['priceunit'][$housedetail[0]['priceunit']];
          $content['renttype'] =  $housedetail[0]['renttype'];
          }

		  $arr['content'] = serialize($content);
		  $arr['telno'] =  $telno;
		  $arr['sendid'] = $collecthousedetail['id'];
		  $arr['sendkind'] = 3;
		  $arr['tbl'] = $collecthousedetail['kind']==3?'sell':'rent';
		  $arr['cityname'] = GB_CITY;

		  $return = $this->addpush($arr);
          if($return>0)
		  {
		  return 1;
		  }else{
		  return 0;
		  }
		  }else{
		  return 0;
		  }
        }
		
	    /**
         * 查找是否有发送到手机加入推送表
         * @param type $uid
         * @return array
         */		
		 function addsmshouse($uid,$telno,$sendtime)
		 {
		  global $house;

		  if(!$telno) return 0;

          $smshousedetail = $this->user_model->get_smshouse_by_telno($telno,0,1,$sendtime);
          if(!empty($smshousedetail)){
          //获取房源信息
          $where = array('id'=>$smshousedetail['rowid']);
          if($smshousedetail['tbl']=='sell'){
          $select = array('id','infotype','uid','infofrom','district','streetid','blockshowname','price','buildarea','floor','subfloor','totalfloor','room','hall','toilet','kitchen','fitment','buildyear'); 
          $housedetail = $this->house_model->gethousebywhere($where,'sell',$select,0,1);
          }else{
          $select = array('id','infotype','uid','infofrom','district','streetid','blockshowname','price','buildarea','floor','subfloor','totalfloor','room','hall','toilet','kitchen','fitment','renttype','priceunit'); 
          $housedetail = $this->house_model->gethousebywhere($where,'rent',$select,0,1);          
          }
          if(empty($housedetail)) return 0;
          //获取街道和经纪人信息
          $streetname = $this->block_model->getstreetname($housedetail[0]['streetid']);
          $brokername = $this->broker_model->getbrokerdetail($housedetail[0]['uid']);
		  $arr['uid'] = $uid;
		  $arr['addtime'] = time();
		  $arr['level'] = 4;
		  $content['infotype'] = $house['infotype'][$housedetail[0]['infotype']];
		  $content['brokername'] = $brokername['truename'];
		  $content['district'] = $housedetail[0]['district'];
		  $content['streetname'] = $streetname['streetname'] ;
		  $content['blockshowname'] = $housedetail[0]['blockshowname'];
		  
          $content['buildarea'] = $housedetail[0]['buildarea'];
          $content['floor'] = empty($housedetail[0]['subfloor'])?$housedetail[0]['floor'].'/'.$housedetail[0]['totalfloor'].'层':$housedetail[0]['subfloor'].'-'.$housedetail[0]['floor'].'/'.$housedetail[0]['totalfloor'].'层';
          $content['room'] = $housedetail[0]['room']?$housedetail[0]['room'].'室':'';
          $content['hall'] = $housedetail[0]['hall']?$housedetail[0]['hall'].'厅':'';
          $content['toilet'] = $housedetail[0]['room']?$housedetail[0]['room'].'卫':'';
          $content['kitchen'] = $housedetail[0]['room']?$housedetail[0]['room'].'厨':'';
          $content['fitment'] = $housedetail[0]['fitment'];
          if($smshousedetail['tbl']=='sell'){
          $content['buildyear'] = $housedetail[0]['buildyear']?$housedetail[0]['buildyear']:'';
          $content['price'] = $housedetail[0]['price']?$housedetail[0]['price']:'';
		  $content['priceunit'] = '万元';
           $content['averprice'] = floor($housedetail[0]['price']*10000/$housedetail[0]['buildarea']).'元/平方米'; 
          }else{
          $content['price'] = $housedetail[0]['price']?$housedetail[0]['price']:'';
          $content['priceunit'] = $house['priceunit'][$housedetail[0]['priceunit']];
          $content['renttype'] =  $housedetail[0]['renttype'];
          }

		  $arr['content'] = serialize($content);
		  $arr['telno'] =  $telno;
		  $arr['sendid'] = $smshousedetail['id'];
		  $arr['sendkind'] = 4;
		  $arr['tbl'] = $smshousedetail['tbl'];
		  $arr['cityname'] = GB_CITY;
		  
		  $return = $this->addpush($arr);
          if($return>0)
		  {
		  return 1;
		  }else{
		  return 0;
		  }
		  }else{
		  return 0;
		  }
		 }
		 
		 /**
         * 查找是否有发送到手机加入推送表
         * @param type $uid
         * @return array
         */		
		 function addcollectblock($uid,$telno,$sendtime)
		 {
		  $collectblockdetail = $this->user_model->getcollectbyuid($uid,2,GB_CITY,$sendtime);
          $select=array('blockname','district','streetid','address','averprice');
          $blockdetail = $this->block_model->getblockdetail($collectblockdetail['collect_id'],$select);
          if(!empty($blockdetail)){
          $streetname = $this->block_model->getstreetname($blockdetail['streetid']);
		  $arr['uid'] = $uid;
		  $arr['addtime'] = time();
		  $arr['level'] = 4;
		  $content['district'] = $blockdetail['district'];
		  $content['streetname'] = $streetname['streetname'];
		  $content['blockname'] = $blockdetail['blockname'];
          $content['averprice'] = $blockdetail['averprice'];
		  $content['priceunit'] = '元/平';
          $arr['content'] = serialize($content);
		  $arr['telno'] =  $telno;
		  $arr['sendid'] = $collectblockdetail['id'];
		  $arr['sendkind'] = 5;
		  $arr['tbl'] = 'sell';
		  $arr['cityname'] = GB_CITY;
        
          $return = $this->addpush($arr);
          if($return>0)
		  {
		  return 1;
		  }else{
		  return 0;
		  }
		  }else{
		  return 0;
		  }
		 }
		
		
		/**
         * 加入推送表
         * @param type $arr
         * @return array
         */
        function addpush($arr)
        {
		//设置表
		$this->user_model->set_table('push_user');
		//过滤表结构
		$result = $this->user_model->add($arr,'esf');

		return $result;
        }

        /**
         * 加入备选库
         * @param type $arr
         * @return array
         */
        function addalternatives($uid,$telno,$city=GB_CITY,$sendkind=3,$tbl='sell')
        {
        $arr['uid'] = $uid;
        $arr['telno'] = $telno;
        $arr['cityname'] = $city;
        $arr['sendkind'] = $sendkind;
        $arr['tbl'] = $tbl;
        $arr['addtime'] = time();
        //检查目前不在备选库
        $alternatives_id = $this->get_data(array('form_name' => 'alternatives_user','limit'=>1,'where'=>array('telno'=>$telno),'select'=>array('id')),'esf');
        if(!empty($alternatives_id[0]['id']))
          {
            return 0;
          }
		//设置表
		$this->user_model->set_table('alternatives_user');
		//过滤表结构
		$result = $this->user_model->add($arr,'esf');

		return $result;
        }


		/**
         * 验证推送用户是否在白名单或者推送库里
         * @param type $uid
         * @return array
         */
        function yzpush($telno){

           if(empty($telno))
           {
            return 0;
           }
           //检查白名单
           $whitelist_id = $this->get_data(array('form_name' => 'whitelist','limit'=>1,'where'=>array('telno'=>$telno),'select'=>array('id')),'esfbak');
           if(!empty($whitelist_id[0]['id']))
            {
             return $whitelist_id[0]['id'];
            }
            //检查推送库
            $user_id =  $this->get_data(array('form_name' => 'push_user','limit'=>1,'where'=>array('telno'=>$telno),'select'=>array('id')),'esf');
            if(!empty($user_id[0]['id']))
            {
                return $user_id[0]['id'];
            }

            //检查推送库历史库最近一个月记录
            $log_id =  $this->get_data(array('form_name' => 'push_user_log','limit'=>1,'where'=>array('telno'=>$telno,'sendtime >'=>time()-24*60*60*30),'select'=>array('id')),'esfbak');
            if(!empty($log_id[0]['id']))
            {
                return $log_id[0]['id'];
            }else{
                return 0;
            }

        }
		

		//added by bianshiwu 20141222 临时函数
		function setPushLogTemp($data){
			$sql = "INSERT INTO `push_log_tmp` ( `sendtime` ,`telno` ,`desc`) VALUES ('{$data['sendtime']}','{$data['telno']}','{$data['desc']}')";
			$this->db_esf->query($sql);
		}
		
		/**
         * 获取推送库的信息
         * @param type $uid,$remainNum 剩余推送次数
         * @return array
         */
        function getpusharray($remainNum){

			 if(intval($remainNum) <= 0) return array();

             //查出推送库总数
             $push_array_num =  $this->get_data(array('form_name' => 'push_user','where'=>array('cityname'=>'nj'),'select'=>array(' count(id) as num')),'esfbak');
             $push_num = ceil($push_array_num[0]['num']/$remainNum);
			 $push_num = 20;

			 //查出推送库
             $push_array =  $this->get_data(array('form_name' => 'push_user','where'=>array('cityname'=>'nj'), 'order_by'=>'id asc','limit'=>$push_num),'esfbak');
 
            //'where_in'=>array('telno',array(13813048550,15150897128,13062566161,18652058969,18260048358)),
             // print_r($push_array);die;

             if(is_array($push_array) && !empty($push_array)){
            
			   foreach($push_array as $key=>$value){
				 $pushid = 0;
                // if($key <4) continue;
			   	 //将信息加入推送历史表，删除推送表
		         $sql = "INSERT INTO `push_user_log` (`pushuserid` ,`uid` ,`level` ,`sendtime` ,`content` ,`telno` ,`sendid` ,`sendkind` ,`cityname` ,`tbl`) VALUES ('".$value['id']."','".$value['uid']."','".$value['level']."', '".time()."',  '".$value['content']."', '".$value['telno']."', '".$value['sendid']."', '".$value['sendkind']."', '".$value['cityname']."', '".$value['tbl']."')";
		         $query = $this->db_esf->query($sql);
				 $pushid = $this->db_esf->insert_id();//自增id

				 $sql2 = "DELETE from `push_user` where telno='".$value['telno']."'";
			     $query = $this->db_esf->query($sql2);

                 //对信息进行处理(第一次如果查询异常，再查询一次)
                 $arr = $this->get_solr_data($value);
				 if(isset($arr['blockid'])){
				     $arr =array();
				     $arr = $this->get_solr_data($value);
				 }

					//$arr['uid']=array('835248'=>'1','822557'=>'2','857996'=>'2','857992'=>'2','850507'=>'2','827694'=>'2','827350'=>'1');
					//$arr['uid']=array('857992'=>'1','850507'=>'2','860097'=>'2','860103'=>'2','860101'=>'2','860099'=>'2','827350'=>'1','859958'=>1,'857568'=>1);
					                                      	
					if(count($arr['uid']) > 1){ 
						$uidstr = '';
						foreach($arr['uid'] as $key4=>$value4)
						{
							$uidstr .= $uidstr == '' ? $key4 : ','.$key4;
						}
						

						//将经纪人加入营销表，判断是否今日已推送5条
						$sql = "select count(*) as num,brokerid from marketing_log where addtime>'".strtotime(date('Y-m-d'))."' and addtime<'".(strtotime(date('Y-m-d'))+24*60*60)."' and brokerid in ($uidstr) group by brokerid";
						$query = $this->db_esf->query($sql);
                        $uarr_num = $query->result_array();

						$temp_uarr_num = array();
						if(is_array($uarr_num) && !empty($uarr_num)){
						   foreach($uarr_num as $value1)
						   {
								//今日经纪人推送条数
								$temp_uarr_num[$value1['brokerid']]=$value1['num'];
						   }
						}
						
					    $sql = "select b.uid,b.truename,a.agid as agentid,a.agentshortname from broker b left join agency a on b.agentcode = a.agentcode where b.valid_flag = 1 and b.uid in ($uidstr)";
						$query = $this->db_esfhousebak->query($sql);
                        $uarr = $query->result_array();
						
						
						//过滤推送超过5次的经纪人
						$str='';
						$uarr_filter = array();
					    if(is_array($uarr) && !empty($uarr)){

						   foreach($uarr as $value2)
						   {
						      if(!isset($temp_uarr_num[$value2['uid']]) || $temp_uarr_num[$value2['uid']]<5)
							  {
                           	    $uarr_filter[] = $value2['uid'];
                                $str .= "('".$pushid."','".$value['id']."','".$value2['uid']."', '".$value2['truename']."',  '".$value2['agentid']."',  '".$value2['agentshortname']."', '".time()."', '".$value['telno']."', '".$value['sendid']."', '".$value['sendkind']."'),";								
							  }
						   }
						 }

						if($str){
						  $str = rtrim($str,',');
						  $sql = "INSERT INTO `marketing_log` (`pushid` ,`uid` ,`brokerid` ,`brokername` ,`agentid` ,`agentname`,`addtime` ,`telno` ,`sendid` ,`sendkind`) VALUES $str";
						  $query = $this->db_esf->query($sql);
						}
						
						 //转编码
						 $uarrnew = array();
					     if(is_array($uarr) && !empty($uarr)){
                           
						   foreach($uarr as $key=>$value5){
							   //过滤符合推送的经纪人
							   if(in_array($value5['uid'],$uarr_filter)){
									$uarrnew[$key]=$value5;
									$uarrnew[$key]['truename']= mb_convert_encoding($value5['truename'],'utf8','gbk');
									$uarrnew[$key]['agentshortname']= mb_convert_encoding($value5['agentshortname'],'utf8','gbk');
							   }
						    }
						 }
                         
                        $re['content'] = $contentnew;
						$re['uarr'] = $uarrnew;
						$return[] = $re;
						//print_r($return);die;
                    }
    
   			   }
 
               return $return;
			 }

		}
		
	     /**
         * 再次通过solr获得数据
         * @param type $array
         * @return array
         */		
		function get_solr_data($value){
	       
				 global $solr_conf_arr,$house;
		         $city = 'nj';
				 if($value['tbl']=='sell'){
					$this->load->library('solr_class',array('api_url'=>$solr_conf_arr[$city][$value['tbl']]),'solr_sell');
					$this->solr_class =$this->solr_sell;
				 }else{
					$this->load->library('solr_class',array('api_url'=>$solr_conf_arr[$city][$value['tbl']]),'solr_rent');
					$this->solr_class =$this->solr_rent;				 
				 }
                  
				   $content = unserialize($value['content']);
				   $infotype_flip = array_flip($house['infotype']);
				   if($value['sendkind']==1){
					   $address = explode('/',$content['address']);
					   $streetname1 = substr(strstr($address[0],'-'),1);
					   $streetname2 = substr(strstr($address[1],'-'),1);
					   $streetname3 = substr(strstr($address[2],'-'),1);
					   $streetid1 = $this->block_model->getstreetdetailbyname($streetname1,array('id'));
					   $streetid2 = $this->block_model->getstreetdetailbyname($streetname2,array('id'));
					   $streetid3 = $this->block_model->getstreetdetailbyname($streetname3,array('id'));
					   $infotype = $infotype_flip[$content['infotype']];
					   //$buildarea = explode('-',$content['buildarea']);
					   //$buildarea1 = $buildarea[0];
					   //$buildarea2 = $buildarea[1];
					   $price = explode('-',$content['price']);
					   $price1 = $price[0];
					   $price2 = $price[1];
					   $buildyear = explode('-',$content['buildyear']);
					   $buildyear1 = $buildyear[0];
					   $buildyear2 = $buildyear[1];
					   if(!empty($content['renttype'])){
					       $renttype = $content['renttype'];
					   }
                   }elseif($value['sendkind']==2 or $value['sendkind']==3  or $value['sendkind']==4){
				       $infotype = $infotype_flip[$content['infotype']];
				       $blockname = $content['blockshowname'];
                       
					   if($value['tbl']=='rent'){
						   if($content['price']<=800){
							   $price1 = 0;
							   $price2 = 1500;
						   }elseif($content['price']>800 && $content['price']<=1200){
							   $price1 = 500;
							   $price2 = 2000;
						   }elseif($content['price']>1200 && $content['price']<=2000){
							   $price1 = 800;
							   $price2 = 2500;
						   }elseif($content['price']>2000 && $content['price']<=3000){
							   $price1 = 1500;
							   $price2 = 3500;
						   }elseif($content['price']>3000 && $content['price']<=5000){
							   $price1 = 2000;
							   $price2 = 6000;
						   }elseif($content['price']>5000 && $content['price']<=10000){
							   $price1 = 4000;
							   $price2 = 11000;
						   }elseif($content['price']>=10000){
							   $price1 = 10000;
							   $price2 = 999999;
						   }
					   }else{
						   if($content['price']<=40){
							   $price1 = 0;
							   $price2 = 60;
						   }elseif($content['price']>40 && $content['price']<=60){
							   $price1 = 30;
							   $price2 = 80;
						   }elseif($content['price']>60 && $content['price']<=90){
							   $price1 = 50;
							   $price2 = 120;
						   }elseif($content['price']>90 && $content['price']<=120){
							   $price1 = 80;
							   $price2 = 150;
						   }elseif($content['price']>120 && $content['price']<=150){
							   $price1 = 100;
							   $price2 = 180;
						   }elseif($content['price']>150 && $content['price']<=200){
							   $price1 = 120;
							   $price2 = 220;
						   }elseif($content['price']>200 && $content['price']<=300){
							   $price1 = 150;
							   $price2 = 350;
						   }elseif($content['price']>300 && $content['price']<=500){
							   $price1 = 250;
							   $price2 = 600;
						   }elseif($content['price']>=500){
							   $price1 = 500;
							   $price2 = 999999;
						   }				   
					   }

				   }elseif($value['sendkind']==5){
			  	       $blockname = $content['blockname'];
				   }
				   
				    if($blockname != '')
					{
						$this->solr_class->setQueryField(array("blockshowname"=>$blockname));
					}
					else
					{
						$this->solr_class->setQueryField("");
					}

				    $streetarr = $ffarr = array();
					$ffarr[] = array("oper"=>"NOT", "field"=>"uid", "inneroper"=>":", "value"=>0);
					$ffarr[] = array("oper"=>"AND", "field"=>"esta", "inneroper"=>":", "value"=>1);
					$ffarr[] = array("oper"=>"AND", "field"=>"infofrom", "inneroper"=>":", "value"=>5);

					if(isset($streetid1) && $streetid1 > 0)
					{
						$streetarr[] = $streetid1['id'];
					}
					if(isset($streetid2) && $streetid2 > 0)
					{
						$streetarr[] = $streetid2['id'];
					}
					if(isset($streetid3) && $streetid3 > 0)
					{
						$streetarr[] = $streetid3['id'];
					}

					if($streetarr)
					{
						$ffarr[] = array("oper"=>"AND", "field"=>"streetid", "inneroper"=>"OR", "value"=>$streetarr);
					}
					if($infotype > 0)
					{
						$ffarr[] = array("oper"=>"AND", "field"=>"infotype", "inneroper"=>":", "value"=>$infotype);
					}
					if($buildarea1 > 0 || $buildarea2 > 0)
					{
						if($buildarea1 < $buildarea2)
						{
							$ffarr[] = array("oper"=>"AND", "field"=>"buildarea", "inneroper"=>"TO", "value"=>array($buildarea1,$buildarea2));
						}
						else
						{
							$ffarr[] = array("oper"=>"AND", "field"=>"buildarea", "inneroper"=>":", "value"=>$buildarea1);
						}
					}
					if($buildyear1 > 0 && $buildyear2 > 0)
					{
						if($buildyear1 < $buildyear2)
						{
							$ffarr[] = array("oper"=>"AND", "field"=>"buildyear", "inneroper"=>"TO", "value"=>array($buildyear1,$buildyear2));
						}
						else
						{
							$ffarr[] = array("oper"=>"AND", "field"=>"buildyear", "inneroper"=>":", "value"=>$buildyear1);
						}
					}
					if($price1 > 0 || $price2 > 0)
					{
						if($price1 < $price2)
						{
							$ffarr[] = array("oper"=>"AND", "field"=>"price", "inneroper"=>"TO", "value"=>array($price1,$price2));
						}
						else
						{
							$ffarr[] = array("oper"=>"AND", "field"=>"price", "inneroper"=>":", "value"=>$price1);
						}
					}
					if($renttype != '' && $value['tbl'] == 'rent')
					{
						$ffarr[] = array("oper"=>"AND", "field"=>"renttype", "inneroper"=>":", "value"=>$renttype);
					}
 
			if($ffarr)
			{
			  $this->solr_class->setFilterField($ffarr);
			}

			$this->solr_class->setCountNum(1000);
			$this->solr_class->setCountField(array("uid"));
			$arr = $this->solr_class->query('countgroup');
		    return $arr;
		}
		
		/**
         * 获取向经纪人推送的信息
         * @param type $brokerid
         * @return array
         */		
		function Getpushnumbybrokerid($city,$brokerid,$ctime,$is_buy,$page=1,$pagesize=20){
			
		    if($is_buy==1){
		    //$sql = "select b.content,a.addtime,a.is_buy,a.is_sendtelno,a.brokerid,b.sendid,b.sendkind,b.id as pushid,b.telno,b.tbl,b.level,b.sellnum,a.cusIntention from push_user_log b left join marketing_log a on b.telno = a.telno where a.addtime>'".$ctime."' and a.brokerid='".$brokerid."' and a.is_buy='".$is_buy."' order by b.id desc limit ".($page-1)*$pagesize.",".$pagesize."" ;

			$sql = "select b.content,a.addtime,a.is_buy,a.is_sendtelno,a.brokerid,b.sendid,b.sendkind,b.id as pushid,b.telno,b.tbl,b.level,b.sellnum,a.cusIntention from push_user_log b left join marketing_log a on b.id = a.pushid where a.addtime>'".$ctime."' and a.brokerid='".$brokerid."' and a.is_buy='".$is_buy."' and b.cityname='".$city."' order by b.id desc limit ".($page-1)*$pagesize.",".$pagesize."" ;
			}else{
		    //$sql = "select b.content,a.addtime,a.is_buy,a.is_sendtelno,a.brokerid,b.sendid,b.sendkind,b.id as pushid,b.telno,b.tbl,b.level,b.sellnum,a.cusIntention from push_user_log b left join marketing_log a on b.telno = a.telno where a.addtime>'".$ctime."' and a.brokerid='".$brokerid."' order by b.id desc " ;

			$sql = "select b.content,a.addtime,a.is_buy,a.is_sendtelno,a.brokerid,b.sendid,b.sendkind,b.id as pushid,b.telno,b.tbl,b.level,b.sellnum,a.cusIntention from push_user_log b left join marketing_log a on b.id = a.pushid where a.addtime>'".$ctime."' and a.brokerid='".$brokerid."' and b.cityname='".$city."' order by b.id desc " ;
			}
			
			
			$query = $this->db_esfbak->query($sql);
            $arr = $query->result_array();
            if($arr){
				 foreach($arr as $key=>$value)
				 {
				   $arr1[$key] = $value;
                   $con=unserialize($value['content']);
				   if($con){
				   foreach($con as $key1=> $value1){
                         if($key1=='buildyear'){
					       $arr2[$key1]= mb_convert_encoding($value1.'年','utf8','gbk');
                         }elseif($key1=='buildarea'){
                           $arr2[$key1]= mb_convert_encoding($value1.'平米','utf8','gbk');
                         }elseif($key1=='brokername'){
                         }else{
                           $arr2[$key1]= mb_convert_encoding($value1,'utf8','gbk');
                         }
				   }}
				   $arr1[$key]['content']=$arr2;

				 }
			 }
			 	
			return $arr1;
		}

        /**
         * 获取向经纪人推送的信息的数量
         * @param type $brokerid
         * @return array
         */		
		function Getpushnumbybroker($brokerid,$ctime,$is_buy){
		    if($is_buy==1){
		    $sql = "select count(a.id) as num from push_user_log b left join marketing_log a on b.telno = a.telno where a.addtime>'".$ctime."' and a.brokerid='".$brokerid."' and a.is_buy='".$is_buy."'";
			}else{
		    $sql = "select count(a.id) as num from push_user_log b left join marketing_log a on b.telno = a.telno where a.addtime>'".$ctime."' and a.brokerid='".$brokerid."'" ;
			}
            $query = $this->db_esfbak->query($sql);
            $arr = $query->result_array();
			return $arr[0];
		}
		
		 /**
         * 获取推送信息的出售次数和推送的经纪人
         * @param type $brokerid
         * @return array
         */		
		function Getsellnumbypush($telno,$sendid,$sendkind){
		    $key = $this->memkey.'_Getsellnumbypush'.$telno.$sendid.$sendkind;

			if($this->input->get('update') == 1)
			{
				$this->memcached_class->delete($key);
			}

			$pushdetail = $this->memcached_class->get($key);

			if( empty($pushdetail) )
			{
            $pushdetail=  $this->get_data(array('form_name' => 'push_user_log','limit'=>1,'where'=>array('telno'=>$telno,'sendid'=>$sendid,'sendkind'=>$sendkind,'sendtime >'=>time()-24*60*60*30),'select'=>array('sellnum','broker','sendid','sendkind')),'esfbak');
			$this->memcached_class->add($key, $pushdetail,3600);
			}
			return $pushdetail[0];
			}
			
		/**
         * 获取推送信息详细信息
         * @param type $pushid
         * @return array
         */		
		function Getpushdetal($pushid){
		    $key = $this->memkey.'Getpushdetal'.$pushid;

			if($this->input->get('update') == 1){
				$this->memcached_class->delete($key);
		 	}

			$pushdetail = $this->memcached_class->get($key);

			if( empty($pushdetail) ){
				$pushdetail=  $this->get_data(array('form_name' => 'push_user_log','limit'=>1,'where'=>array('id'=>$pushid),'select'=>array('sellnum','broker','sendid','sendkind','telno')),'esf');

				$this->memcached_class->add($key, $pushdetail,86400);
			}
			return $pushdetail[0];
		}
			
		 /**
         * 更新推送信息的出售次数
         * @param type $brokerid,$type 1,更新是否电话，2更新是否购买
         * @return array
         */				
		function Updatebrokerpush($brokerid,$type,$pushid){
			
			 //检查是否可购买次数已满，或者此经纪人已经购买过
			  $push_log = $this->Getpushdetal($pushid);
              if($type==1){
				  $arr = array('brokerid' => $brokerid,'pushid'=>$pushid); 
				  $up=array('is_sendtelno'=>1,'sendtelnotime'=>time());
				  $this->set_table('marketing_log');
				  $result = $this->save($arr,$up,'esf');
				  return 1;
			 }else{
				  if($push_log['sellnum'] >= 5)
				  {
				   return 'N_FULL';
				  }elseif(strpos($push_log['broker'],$brokerid)){
				   return 'N_BUY';     
				  }

				  $arr = array('brokerid' => $brokerid,'pushid'=>$pushid); 
				  $up=array('is_buy'=>1,'buytime'=>time());
				  $this->set_table('marketing_log');
				  $result = $this->save($arr,$up,'esf');
				  //更新推送历史表
				  if($result>0)
				  {
				  //删除缓存
				   $this->memcached_class->delete($this->memkey.'Getpushdetal'.$pushid);
				   $up=array('sellnum'=>($push_log['sellnum']+1),'broker'=>$push_log['broker'].'&'.$brokerid);
				   $arr=array('id'=>$pushid);
				   $this->set_table('push_user_log');
				   $result = $this->save($arr,$up,'esf');
				  }
				  return array('telno'=>$push_log['telno']);
			 }

		}

		 /**
         * 删除备选库的内容
         * @param type $telno,电话
         * @return array
         */				
		   function delalternatives($telno)
		    {
          //删除备选库
          $this->push_model->set_table('alternatives_user');
          $result = $this->push_model->del_mul($telno,'telno','esf');
            }

          /**
         * 通过手机获取推送历史库库的信息
         * @param string $telno
         * @return array
         */
        function getpushlogbytelno($telno){
            /*
            $key = $this->memkey.'getpushlogbytelno'.$telno;

			if($this->input->get('update') == 1)
			{
				$this->memcached_class->delete($key);
			}

			$pushdetail = $this->memcached_class->get($key);
            */
		    $pushdetail = false;

			if( empty($pushdetail) ){
             $pushdetail =  $this->get_data(array('form_name' => 'push_user_log','where'=>array('telno'=>$telno),'select'=>array('sendtime'),'order_by'=>'sendtime desc','limit'=>1),'esf');

             //$this->memcached_class->add($key, $pushdetail,3600);
            }

            return isset($pushdetail[0]['sendtime'])?$pushdetail[0]['sendtime']:'';

        }


		/***
		 * 先更新markering_log 意向
		 * 再更新pushuser_log  意向
		 *
		 */
		function commitintention($brokerid,$pushuserid,$intention)
		{
			
			//更新maketing_log 意向
			$sql = "update  `marketing_log` set cusIntention =$intention where brokerid=$brokerid and pushid =$pushuserid";
			//echo $sql;die;
			$result =  $this->db_esf->query($sql);

			//根据pushid 查找telno值
			$sql_marketing_log  = "select pushid from marketing_log where pushid=$pushuserid limit 1 ";
			$marketing_log = $this->db_esf->query($sql_marketing_log);
			
			$marketing_log = $marketing_log->result_array();
			$pushid		   =$marketing_log['0']['pushid'];
				
			$sql_mak = "select count(id) as num,cusIntention from marketing_log where pushid=$pushid   group by cusIntention ";
			//echo $sql_mak;die;
			$query_mak = $this->db_esf->query($sql_mak);

            $arr_mak   = $query_mak->result_array();
			
			foreach ($arr_mak as $key => $data)
			{
				if($data['cusIntention']!=0)
				{
					$datas[$data['cusIntention']] =$data['num'];
				}
				
			}

			for($i=0;$i<4;$i++)
			{
				if(isset($datas[$i]))
				{}
				else
				{
					$datas[$i] =0;
				}
			}

			ksort($datas);
			$cusIntention  =$this->compare_num($datas);
			
			$sql = "update  `push_user_log` set cusIntention =$cusIntention where id=$pushuserid";
			
			$result =  $this->db_esf->query($sql);

			return 1;
			
		}


		function compare_num($datas)
		{
			$rs =$datas;
			//print_r($rs);
			if($rs[1]==0 && $rs[2]==0 && $rs[3]==0 )
			{
				return 0;
			}
			else
			{
				//unset($rs[0]);
				sort($rs);
				
				$big =$rs[3];
				
				if($datas[3]==$big)
				{
					return 3;
				}
				elseif($datas[2]==$big)
				{
					return 2;
				}
				elseif($datas[1]==$big)
				{
					return 1;
				}
				
			}
		
		}

		
    }
	
	

