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

/**
 * House_Statistic_Model Class
 *
 * 个人房源的相关数据，点击量、房源操作日志数据等
 *
 * @package         center
 * @subpackage      model
 * @category        model
 * @author          liuhu
 */
class House_Statistic_Model extends MY_Model {

    /**
    * 用户ID
    *
    * @access private
    * @var integer
    */
    private  $_uid = 0;

    /**
    * 用户操作内容所在的城市
    *
    * @access private
    * @var string
    */
    private $_city = 'nj';

    /**
    * 用户客户端IP
    *
    * @access private
    * @var string
    */
    private $_ip = '';

    /**
    *  用户操作日志表
    *
    * @access private
    * @var string
    */
    private  $_log_tbl = "log_house_operate";

    /**
    *  用户操作日志表
    *
    * @access private
    * @var string
    */
    private  $_log_click_tbl = "log_house_click";

    /**
    *  房源编号
    *
    * @access private
    * @var int
    */
    private  $_rowid = 0;


    /**
    *  是否有缓存，0有缓存，1没有缓存
    *
    * @access private
    * @var int
    */
    private  $_nocache = 0;

    /**
    *  操作类型键值表
    *
    * @access private
    * @var array
    */
    private  $_operate_type = array( 1 => '新增' , 2 => '操作刷新' , 3 => '删除' , 4 => '修改', 5 => '再发布',7=>'套餐智能刷新',8=>'套餐操作刷新', 10 => '操作刷新', '11' => '预约刷新' );
//    private  $_operate_type = array( 1 => '新增' , 2 => '刷新' , 3 => '删除' , 4 => '修改', 5 => '再发布' );

    /**
    *  操作类型键值表
    *
    * @access private
    * @var array
    */
    private  $_house_type = array( 'sell' => '出售' , 'rent' => '出租' , 'buy' => '求购' , 'rentwanted' => '求租');

    /**
    *  点击量表查询的字段
    *
    * @access private
    * @var array
    */
    private  $_select_fields    = array();

    /**
    * Constructor
    */
    public function __construct()
    {
        parent::__construct();
        $this->memkey = 'home_statistic'.GB_CITY;
    }


    /**
    * set_uid
    *
    * 初始化uid参数
    *
    * @access	public
    * @param	int     $uid 用户编号
    * @return	void
    */
    public function set_uid( $uid )
    {
        $this->_uid = $uid;
    }


    /**
    * get_uid
    *
    * 初始化uid参数
    *
    * @access	public
    * @return	int     $uid 用户编号
    */
    public function get_uid( )
    {
        return $this->_uid ;
    }


    /**
    * set_city
    *
    * 初始化城市参数
    *
    * @access	public
    * @param	string  $city 城市参数
    * @return	void
    */
    public function set_city($city)
    {
        $this->_city    = $city;
    }


    /**
    * get_city
    *
    * 获得城市
    *
    * @access	public
    * @return	string  $city 城市
    */
    public function get_city()
    {
        return $this->_city ;
    }


    /**
    * set_ip
    *
    * 初始化IP参数
    *
    * @access	public
    * @param	string  $ip ip
    * @return	void
    */
    public function set_ip($ip)
    {
       $this->_ip    = $ip;
    }

    /**
    * set_nocache
    *
    * 初始化IP参数
    *
    * @access	public
    * @param	string  $ip ip
    * @return	void
    */
    public function set_nocache($nocache)
    {
       $this->_nocache    = $nocache;
    }


    /**
    * get_operate_type
    *
    * 获取操作类型
    *
    * @access	public
    * @param	void
    * @return	array   操作类型数据
    */
    public function get_operate_type()
    {
        return $this->_operate_type;
    }

    /**
     * 获取最近一次购买的智能刷新套餐promote_id
     * @param $houseid
     * @param $tbl
     * @return mixed
     */
    public function getLastAutoRefreshPackageOrder($houseid, $tbl){
        $sql = "select id from personal_house_promote where house_id =".$houseid. " and house_type=".$tbl." and status=1 and package_type = 3 order by confirm_time desc limit 1";
        $query = $this->db_esfhouse->query($sql);
        $rows  = $query->result_array();
        $promote_id = isset( $rows[0]['id'] ) ? $rows[0]['id'] : 0;
        return $promote_id;
    }
    /**
     * 获取智能自动刷新套餐首次自动刷新时间,1或者3都代表自动刷新
     * @param $type
     * @param $houseid
     * @param $tbl
     * @return mixed
     */
    public function getAutoRefreshPackageStartTime($houseid,$tbl,$promote_id){
        $sql = "select ctime from personal_house_increment where promote_id =".$promote_id." and rowid= ".$houseid." and package_type in('1','3') and tbl=". $tbl. " order by ctime ASC limit 1";
        $query = $this->db_esfhouse->query($sql);
        $res   = $query->result_array();
        $datetime    =$res[0]['ctime'];
        $datetime = date('Y-m-d H:i:s',$datetime);
        return $datetime;
    }

    /**
     * 获取智能自动刷新套餐用户已使用次数：包括用户手动刷新和自动刷新
     * @param $houseid
     * @param $tbl
     * @return mixed
     */
    public function getAutoRefreshPackageUsedNums($houseid,$tbl,$promote_id){
        $sql   = "select count(*) as count from personal_house_increment where promote_id= $promote_id and rowid = $houseid and tbl = '$tbl'";
        $query = $this->db_esfhouse->query($sql);
        $rows  = $query->result_array();
        $count = $rows[0]['count'];
        return $count;

    }

    /**
     * 获取智能刷新套餐里面总的刷新次数
     * @param $houseid
     * @param $tbl
     * @return mixed
     */
    public function getAutoRefreshPackageTotalNums($promote_id){
        $sql   = "select package_refresh_num from personal_house_promote where id = $promote_id and package_type = 3";
        $query = $this->db_esfhouse->query($sql);
        $rows  = $query->result_array();
        $nums = $rows[0]['package_refresh_num'];
        return $nums;
    }

    /**
     * 获取智能刷新套餐预计最后一次刷新时间
     * @param $type
     * @param $houseid
     * @param $tbl
     * @return false|float|int|string
     */
    public function getGuessLastRefreshTime($houseid,$tbl, $promote_id){
        //获取剩余刷新次数
        $totalnums = $this->getAutoRefreshPackageTotalNums($promote_id);
        $usednum = $this->getAutoRefreshPackageUsedNums($houseid, $tbl, $promote_id);
        $restnums = $totalnums-$usednum;

        //获取上次刷新时间
        $sql   = "select ctime from personal_house_increment where promote_id = $promote_id and rowid = $houseid and tbl = '$tbl' order by ctime desc limit 1";
        $query = $this->db_esfhouse->query($sql);
        $res   = $query->result_array();
        $lastdatetimestr    =$res[0]['ctime'];
        //返回预计最后一次刷新时间
        if($restnums >0){
            $resttimestr = 14400 * $restnums;
            $guessFinalRefreshTime = $lastdatetimestr + $resttimestr;
            $guessFinalRefreshTime = date('Y-m-d H:i:s', $guessFinalRefreshTime);
        }else{
            $guessFinalRefreshTime = 0; //剩余次数用完，那么预计个毛？
        }

        return $guessFinalRefreshTime;
    }

    /**
     * 获取自动刷新套餐使用详情日志
     * @param $houseid
     * @param $tbl
     * @return mixed
     */
    public function getAutoRefreshDetail($houseid, $tbl,$promote_id){
        //获取上次刷新时间
        $sql   = "select ctime,package_type from personal_house_increment where promote_id = $promote_id and rowid = $houseid and tbl = '$tbl' order by ctime desc";
        $query = $this->db_esfhouse->query($sql);
        $rows  = $query->result_array();
        $total = count($rows);
        if(!empty($rows)){
            $orders = $total;
            foreach($rows as &$row){
                $row['datetime'] = date('Y-m-d H:i:s',$row['ctime']);
                unset($row['ctime']);
                $row['order'] = $orders;
                if($row['package_type'] == 1 || $row['package_type'] == 3){
                    $row['typetext'] = iconv('gbk','utf-8',"自动");
                }elseif($row['package_type'] == 2){
                    $row['typetext'] = iconv('gbk','utf-8',"手动");
                }
                $orders -=1;
            }
        }else{
            $total = 0;
        }
        return array('total'=>$total,'data'=>$rows);
    }
    /**
    * get_house_type
    *
    * 获取房源类型数组
    *
    * @access	public
    * @param	void
    * @return	array   房源类型
    */
    public function get_house_type()
    {
        return $this->_house_type;
    }


    /**
    * 设置查询字段
    *
    * @access	public
    * @param	array $fields  查询字段数组
    * @return  void
    */
    public function set_select_fields($fields)
    {
       $this->_select_fields   = $fields;
    }


    /**
    * 设置房源编号
    *
    * @access	public
    * @param	int $rowid  房源编号
    * @return  void
    */
    public function set_rowid($rowid)
    {
       $this->_rowid = $rowid;
    }


	/**
    * _tbl_exists
    *
    * 判断数据库表是否存在
    *
    * @access	private
    * @param	int		 $tbl_name   表名称
    * @return	boolean  true/false
    */
	private function _tbl_exists($tbl_name)
	{
		$sql = "SHOW TABLES LIKE '".$tbl_name."'";
		$result = $this->db_esf->query($sql);
		$tbl_info = $result->result_array();

		if( is_array($tbl_info) && !empty($tbl_info) )
		{
			return true;
		}
		else
		{
			return false;
		}
	}


	/**
    * _get_tblname_by_date
    *
    * 根据日期生成表字段
    *
    * @access	private
	* @param	string	$date   日期(eg:20140313)
    * @param	string	$tbl_name  基础表名称
    * @return	string	$tblname 表名称
    */
	private function _get_tblname_by_date($date , $base_tblname = '')
	{
		$base_tblname = $base_tblname == '' ?
						$this->_log_click_tbl : strip_tags($base_tblname);

		$tblname = $base_tblname . $date;

		return $tblname;
	}


	/**
    * _creat_tbl_by_copy
    *
    * 根据$tblname 生成新表 $tblname_new
    *
    * @access	private
	* @param	string	$tblname_new  新表名称
    * @param	string	$tblname	  被复制的表的名称
    * @return	boolean true/false
    */
	private function _creat_tbl_by_copy ( $tblname_new , $tblname )
	{
		if( trim($tblname_new) == trim($tblname) )
		{
			return false;
		}

		//5.0之前用(CREATE TABLE 新表 SELECT * FROM 旧表 WHERE 1=2)
		// MYSQL5.0以上才支持
		$sql = " CREATE TABLE $tblname_new LIKE $tblname ";
		$result = $this->db_esf->query($sql);

		if($result)
		{
			return true;
		}
		else
		{
			return false;
		}
	}


    /**
    * sub_operate_log
    *
    * 提交个人用户中心用户操作房源的日志
    *
    * @access	public
    * @param	string      $tbl 操作房源类型:二手房(sell)/租房(rent)
    * @param	int         $rowid 操作房源的编号
    * @param	int         $operate_type 操作类型
    * @param	string 	    $device 操作设备类型( 1：pc , 2：andriod , 3：iphone)
    * @return	array       操作结果数组
    */
    public function sub_operate_log( $tbl , $rowid , $operate_type , $device = 1)
    {
        //ip地址
        $this->_ip = empty($this->_ip) ? get_ip() : $this->_ip;

       //提交的日志数据
       $data   = array(
            'city'      => $this->_city,
            'uid'       => $this->_uid,
            'tbl'       => $tbl,
            'rowid'     => intval( $rowid ),
            'type'      => $operate_type,
            'datetime'  => date('Y-m-d H:i:s'),
            'ip'        => $this->_ip,
            'device'    => $device,
		    'add_time'  => time()
        );

       //插入数据
       $this->set_table($this->_log_tbl);
       $insert_id  = $this->add($data);

       //返回数据
       $result = array();
       if( $insert_id > 0)
       {
            $result['is_ok']	= 1;
            $result['msg']	= $this->_operate_type[$operate_type].'操作成功';
       }
       else
       {
            $result['is_ok']	= 0;
            $result['msg']	= $this->_operate_type[$operate_type].'操作失败';
       }

       return  $result ;
    }


    public function buy_log($data)
    {
        //插入数据
        $this->set_table('buy_process_log');
        $insert_id  = $this->add($data,'esfhouse');
        return  $insert_id ;
    }

    /**
     * 根据uid获取租房和售房的房源id
     * @param $uid
     * @return array
     */
    public function getHousesByUid($uid){
        $sql = "select id from sell where uid=".$uid." union all select id from rent where uid = ".$uid;
        $query  =  $this->db_esfhouse->query($sql);
        $houseids_arr = $query->result_array();
        $houseids_str = '';
        if(!empty($houseids_arr)){
            foreach($houseids_arr as $each){
                $houseids[] = $each['id'];
            }
            $houseids_str = implode(',',$houseids);
        }

        return $houseids_str;
    }
    /**
    * get_operate_count
    *
    * 获取个人用户中心房源操作日志数量
    *
    * @access	public
    * @param	int     $type 操作类型
    * @param	mixed   $data 操作日期
    * @return	$int    $num
    */
    public function get_operate_count( $type = 0 , $datetime = '' )
    {

		$key = $this->memkey.'get_operate_count'.$type.$datetime.$this->_city.$this->_uid;
		if($this->input->get('update') == 1)
		{
			$this->memcached_class->delete($key);
		}

		$total_num = $this->memcached_class->get($key);
        if($this->_nocache==1)
        {
          $total_num='';
        }

		if(empty($total_num) )
		{

			$arr_data = array();
			//智能刷新套餐取的是personal_house_increment表
            if($type == 7 || $type == 8){  //7是自动，8是手动
                $start_datetime = !empty($datetime) ? strtotime($datetime) : mktime(0,0,0,date('m'),date('d')-1,date('Y'));
                $end_datetime = $start_datetime+86400;
                $houseids = $this->getHousesByUid($this->_uid);
                if(!$houseids){
                    return array();
                }
                if($type==7){
                    $package_type = '(1,3)';  //自动
                }else{
                    $package_type = '(2)';   //手动
                }

                $sql = "select count(*) as count from personal_house_increment where rowid in( ".$houseids.") and package_type in".$package_type
                ."and ctime between $start_datetime and $end_datetime";
                $query  =  $this->db_esfhouse->query($sql);
                $res = $query->result_array();
                $total_num = $res[0]['count'];
            }else{
                //base_filter
                $where_cond = "city = '".$this->_city."' AND uid = '".$this->_uid."' ";

                //type_filter
                if( !empty( $type ) && is_numeric($type) )
                {
                    if ( $type == 2 ) {//手动刷新
                        $where_cond .= " AND type in (2,10) ";
                    } else {
                        $where_cond .= " AND type = '" . $type . "' ";
                    }
                }

                //时间参数
                $datetime = !empty( $datetime ) ? $datetime : date( 'Y-m-d' , time() - 86400 );
                //开始时间
                $datetime_start  = date('Y-m-d H:i:s', strtotime($datetime) ) ;
                //结束时间
                $datetime_end  = date('Y-m-d H:i:s', strtotime($datetime) + 86400 ) ;
                $where_cond .= " AND datetime BETWEEN '".$datetime_start."' AND  '".$datetime_end."'";
                $this->db_esfbak->where( $where_cond );
                $this->db_esfbak->from($this->_log_tbl);
                $total_num  =  $this->db_esfbak->count_all_results();
            }

            //计入缓存
			$this->memcached_class->add($key, $total_num,3600);
        }

        return intval( $total_num ) ;
    }


    /**
    * get_operate_list
    *
    * 获取个人用户中心房源操作日志
    *
    * @access	public
    * @param	int     $type 操作类型
    * @param	string  $data 操作日期
    * @param	int     $offset 偏移数
    * @param	int     $limti 每次取的条数
    * @param	string  $order 升序降序
    * @return	array   操作日志
    */
    public function get_operate_list ( $type = 0 , $rowid = 0 , $datetime = '' , $offset = 0 , $limit = 10 , $order = 'DESC' )
    {

        $key = $this->memkey.'get_operate_list'.$type.$rowid.$datetime.$offset.$limit.$order.$this->_city.$this->_uid;
		if($this->input->get('update') == 1)
		{
			$this->memcached_class->delete($key);
		}
		$this->memcached_class->delete($key);
		$arr_data = $this->memcached_class->get($key);

        if($this->_nocache==1)
        {
          $arr_data=array();
        }


		if(empty($arr_data) )
		{
            $arr_data = array();

            //智能刷新套餐取的是personal_house_increment表
            if($type == 7 || $type == 8){  //7是自动，8是手动
                $start_datetime = !empty($datetime) ? strtotime($datetime) : mktime(0,0,0,date('m'),date('d')-1,date('Y'));
                $end_datetime = $start_datetime+86400;
                $houseids = $this->getHousesByUid($this->_uid);
                if($type==7){
                    $package_type = '(1,3)';  //自动
                }else{
                    $package_type = '(2)';   //手动
                }

                $sql = "select * from personal_house_increment where rowid in (".$houseids." ) and package_type in".$package_type
                    ."and ctime between $start_datetime and $end_datetime order by ctime desc limit $offset,$limit";
                $query  =  $this->db_esfhouse->query($sql);
                $arr_data = $query->result_array();
                if(!empty($arr_data)){
                    foreach($arr_data as &$each){
                        $each['datetime'] = date('Y-m-d H:i:s',$each['ctime']);
                        $each['type'] = ($each['package_type'] == 2) ? 8 : 7;
                        $each['tbl'] = ($each['tbl'] == 1) ? 'sell' : 'rent';
                    }
                }
            }else{
                //base_filter
                $where_cond = "city = '".$this->_city."' AND uid = '".$this->_uid."' ";

                //type_filter
                if( !empty( $type ) && is_numeric($type) )
                {
                    if ( $type == 2 ) {//手动刷新
                        $where_cond .= " AND type in (2,10) ";
                    } else {
                        $where_cond .= " AND type = '" . $type . "' ";
                    }
                }

                //rowid_filter
                if( !empty( $rowid ) && is_numeric($rowid) )
                {
                    $where_cond .= " AND rowid = '".$rowid."' ";
                }

                //时间参数
//                $datetime = !empty( $datetime ) ? $datetime : date( 'Y-m-d' , time() - 86400 );
//                //开始时间
//                $datetime_start  = date('Y-m-d H:i:s', strtotime($datetime) ) ;
//                //结束时间
//                $datetime_end  = date('Y-m-d H:i:s', strtotime($datetime) + 86400 ) ;
                $datetime = !empty( $datetime ) ? $datetime : date( 'Y-m-d');
                $datetime_start = $datetime.' 00:00:00';
                $datetime_end = $datetime.' 23:59:59';

                $where_cond .= " AND datetime BETWEEN '".$datetime_start."' AND  '".$datetime_end."'";
                //echo $where_cond;die;
                $this->db_esfbak->where( $where_cond );
                $this->db_esfbak->order_by( 'datetime' , $order );
                $arr_data = $this->db_esfbak->get( $this->_log_tbl , $limit , $offset )->result_array();

            }

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

        return $arr_data ;
    }

    /**
     * sub_house_refresh
     * //TODO 没有校验用户套餐次数有没有用完。怎么能直接就给刷了呢！
     * 提交个人用户房源点刷新信息
     *
     * @access	public
     * @param	string  $tbl 操作房源类型:二手房(sell)/租房(rent)
     * @param	int     $rowid 操作房源的编号
     * @param	string  $district 房源所在的区属
     * @param	int     $blockid 小区编号
     * @param	int     $streetid 板块编号
     * @param	int     $room 房源个数
     * @param	float   $price 房源价格
     * @param	int     $buildarea 房源面积
     * @param	string 	$device 操作设备类型( 1：pc , 2：andriod , 3：iphone)
     * @return	array   提交结果数组
    */
    public function sub_house_refresh($tbl , $rowid , $price , $order_id,$type='')
    {

        $ctime = $time =time();

        if($type == 4){
            $sql =" update $tbl set updatetime=$ctime,lucupdatetime=$ctime,lucupdatetime=$ctime where id=$rowid and esta=1";
            $this->db_esfhouse->query($sql);
            
            $order_sql  ="select * from personal_house_orders where id=$order_id  limit 1";
            $data_order	  =$this->db_esfbak->query($order_sql);
            $orders =$data_order->result_array();
            if($orders){
                $order = $orders[0];
                //插入操作日志表
                $dat = date('Y-m-d H:i:s');
                $city = GB_CITY;
                $uid = $order['user_id'];
                $ip = get_ip();
                $rowid = $order['house_id'];
                $order_log1 ="insert into log_house_operate (city,uid,tbl,rowid,type,datetime,ip,device,add_time,order_id) VALUES ('$city',$uid,'$tbl',$rowid,2,'$dat','$ip',1,$time,$order_id)";
                $this->db_esfhouse->query($order_log1);
            }



        }

        $sql_promote_new		="select id,price,order_id from personal_house_promote where id=$order_id and  end_time >= $time limit 1";

        $data_promote_new	  =$this->db_esfhouse->query($sql_promote_new);

        $data_promote_arr_new =$data_promote_new->result_array();
        if(empty($data_promote_arr_new))
        {
            die("套餐过期");
        }
        if($tbl=='sell')
        {
            $tbl_new =1;
        }
        else
        {
            $tbl_new =2;
        }
        if(empty($price))
        {
            $sql_promote  ="select id,price,order_id from personal_house_promote where id=$order_id  limit 1";

            $data_promote	  =$this->db_esfhouse->query($sql_promote);

            $data_promote_arr =$data_promote->result_array();
            $price			   =$data_promote_arr[0]['price'];

        }
        $ctime =time();
        $sql_personal_house_inc ="insert into personal_house_increment (price,promote_id,package_type,tbl,rowid,ctime) VALUES ('$price','$order_id','2','$tbl_new','$rowid','$ctime')";

        $personal_house_promote_query =$this->db_esfhouse->query($sql_personal_house_inc);

        $sql =" update $tbl set updatetime=$ctime,lucupdatetime=$ctime,lucupdatetime=$ctime where id=$rowid and esta=1";
        $this->db_esfhouse->query($sql);

        $time =time();
        //2018.5.31 取消时间拦截。原因：防止4小时刷新一次定时任务不准，导致出现时间已到而次数未刷新情况。
//        $sql_promote  ="select id,package_refresh_num from personal_house_promote where house_type=$tbl_new and house_id=".$rowid." and package_type=3 and status=1 and start_time<=".$time." and end_time >=".$time." order by id desc limit 1";
        $sql_promote  ="select id,package_refresh_num from personal_house_promote where house_type=$tbl_new and house_id=".$rowid." and package_type=3 and status=1 order by id desc limit 1";

        $data_promote	  =$this->db_esfhouse->query($sql_promote);

        $data_promote_arr =$data_promote->result_array();

        if(!empty($data_promote_arr))
        {

            $promote_id  =$data_promote_arr[0]['id'];

            $promote_num =$data_promote_arr[0]['package_refresh_num'];
            $sql_inc  ="select count(*) as num from personal_house_increment where promote_id=$promote_id and rowid=".$rowid." and tbl =$tbl_new ";

            $data_inc		=$this->db_esfhouse->query($sql_inc);
            $data_inc_arr   = $data_inc->result_array();

            if(!empty($data_inc_arr))
            {
                $inc_num	=$data_inc_arr['0']['num'];
                $num		=$promote_num-$inc_num;
            }
        }
        else
        {
            $num =0;
        }
        $data =array();
        $data['num'] =$num;


        $result = array ('result' => 1 , 'msg' => 'success','data'=>$data);

        return $result;
    }


	/**
	* sub_house_click
	*
	* 提交个人用户房源点击量信息
	*
	* @access	public
	* @param	string  $tbl 操作房源类型:二手房(sell)/租房(rent)
	* @param	int     $rowid 操作房源的编号
	* @param	string  $district 房源所在的区属
	* @param	int     $blockid 小区编号
	* @param	int     $streetid 板块编号
	* @param	int     $room 房源个数
	* @param	float   $price 房源价格
	* @param	int     $buildarea 房源面积
    * @param	string 	$device 操作设备类型( 1：pc , 2：andriod , 3：iphone)
	* @return	array   提交结果数组
	*/
	public function sub_house_click( $tbl , $rowid ,  $district , $blockid , $streetid , $room , $price ,$buildarea , $device)
	{
		//点击时间
		$time = time();
		$click_time  = date('Y-m-d H:i:s',$time);
		$hour    = date( 'G' , $time );
		$day	= date('Ymd', $time );

		//ip地址
		$this->_ip = empty($this->_ip) ? get_ip() : $this->_ip;

		//提交的日志数据

        $data   = array(
            'city'      => $this->_city,
            'uid'       => $this->_uid,
            'tbl'       => $tbl,
            'rowid'     => intval( $rowid ),
            'district'  => strip_tags($district),
            'blockid'   => intval($blockid),
            'streetid'  => intval($streetid),
            'room'      => intval($room),
            'price'     => floatval($price),
            'buildarea' => intval($buildarea),
            'click_time'=> $click_time ,
            'hour'      => $hour ,
            'ip'        => $this->_ip,
            'device'    => $device
        );

        //插入数据
        $tbl_name = $this->_get_tblname_by_date( $day , $this->_log_click_tbl);

//        //判断表是不是存在，不存在则新建表（mc缓存）
//        $is_exist = $this->_tbl_exists($tbl_name);
//
//        //如果不存在则创建表
//        if( ! $is_exist )
//        {
//            $creat_result = $this->_creat_tbl_by_copy( $tbl_name , $this->_log_click_tbl);
//        }

        if( true)
        {
            $data   = array(
                'city'      => $this->_city,
                'uid'       => $this->_uid,
                'tbl'       => $tbl,
                'rowid'     => intval( $rowid ),
                'district'  => iconv('gbk', 'utf8', strip_tags($district)),
                'blockid'   => intval($blockid),
                'streetid'  => intval($streetid),
                'room'      => intval($room),
                'price'     => floatval($price),
                'buildarea' => intval($buildarea),
                'click_time'=> $click_time ,
                'hour'      => $hour ,
                'ip'        => $this->_ip,
                'device'    => $device
            );

            $postUrl = "http://newrent.house365.com/queue/log-house-click";
            $curlPost = array(
                'mqToken' => '993386062b3b3702664cb1a3c654a98d',
                'queueParams' => array(
                    'tableName' => $tbl_name,
                    'insertData' => $data
                )
            );

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $postUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($curlPost));
            curl_exec($ch);
            curl_close($ch);
        }

        //返回数据
        $result = array();

        if( true)
        {
            $result['is_ok'] = 1;
            $result['msg'] = '点击操作记录成功';
        }
        else
        {
            $result['is_ok'] = 0;
            $result['msg'] = '点击操作记录失败';
        }


		//插入个人付费推广房源表
        if($tbl=='sell')
        {
            $house_type = 1;
            $tbl_new =1;
        }
        else
        {
            $house_type = 2;
            $tbl_new =2;
        }
        $time =time();
        //查找付费房源推广表
        $sql_personal_house_promote ="select * from personal_house_promote where house_type =$house_type and house_id =".$rowid." and status =1 and start_time<=$time and end_time>=$time limit 1";

		$personal_house_promote_query =$this->db_esfbak->query($sql_personal_house_promote);
        $result_promote = $personal_house_promote_query->result_array();

        if(is_array($result_promote) && !empty($result_promote)) {
            $ispromote = 1;
            $str_package_type = "";
            $str_package_keyword = "";
            $str_package_day = "";
            $str_promote_time = "";
            foreach ($result_promote as $key => $rs) {
                $str_package_type .= $rs['package_type'] . ',';           //套餐类型
                $str_package_keyword .= $rs['package_keyword'] . ',';     //套餐关键字
                $str_package_day .= intval(($rs['end_time']-$rs['start_time'])/86400) . ',';     //套餐天数
                $str_promote_time .= date('Y-m-d', $rs['start_time']) . '/' . date('Y-m-d', $rs['end_time']) . ',';
            }

            $str_package_type = rtrim($str_package_type, ',');
            $str_package_keyword = rtrim($str_package_keyword, ',');
            $str_package_day = rtrim($str_package_day, ',');
            $str_promote_time = rtrim($str_promote_time, ',');
        }
        else
        {
            $ispromote = 0;
            $str_package_type       ='/';
            $str_package_keyword    ='/';
            $str_package_day        ='/';
            $str_promote_time       ='/';

        }

        $sql_personal_house = "select infotype,telno from " . $tbl . " where id =" . $rowid . ' and esta=1';

        $personal_house_query = $this->db_esfbak->query($sql_personal_house);
        $result_house = $personal_house_query->result_array();
        if (is_array($result_house) && !empty($result_house)) {
            $telno            = $result_house[0]['telno'];
            $infotype         = $result_house[0]['infotype'];

        }

        //是否是实勘房源
        $sql_survey_house = "select id from survey". " where type ="."'$tbl'"."  and house_id =" . $rowid;

        $survey_house_query = $this->db_esfbak->query($sql_survey_house);
        $survey_house = $survey_house_query->result_array();
        if (is_array($survey_house) && !empty($survey_house)) {
            $survey =1;
        }else{
            $survey =0;
        }

        $time  =date('Y-m-d');
        $sql_log_promote_house ="select id from log_promote_house where tbl=".$tbl_new.' and rowid='.$rowid.' and ctime='."'".$time."'";

        $log_promote_house_query =$this->db_esfbak->query($sql_log_promote_house);
        $result_log_promote = $log_promote_house_query->result_array();

        if(empty($result_log_promote))
        {
            if($ispromote==0)
            {
                $promote_search_time ='';
            }
            else
            {
                $promote_search_time =time();
            }
            $sql_new ="insert into log_promote_house (ispromote,tbl,rowid,infotype,survey,package_type,package_day,package_search,telno,promote_time,ctime,promote_search_time) VALUES ('$ispromote','$tbl_new','$rowid','$infotype','$survey','$str_package_type','$str_package_day','$str_package_keyword','$telno','$str_promote_time','$time','$promote_search_time')";
        }
        else
        {
            $sql_new ="update log_promote_house set num =num+1 where tbl='$tbl_new' and rowid='$rowid' and ctime ='$time'";
        }

        //echo $sql_new;die;
        $this->db_esf->query($sql_new);


        return  $result ;




	}


    /**
    * _get_house_click_num
    *
    * 获取个人用户中心房源点击数量
    *
    * @access	public
    * @param	mixed   $data 操作日期
    * @param	string  $tbl 房源类型 默认是所有，sell\rent代表sell房源和rent房源
    * @return	array   操作日志
    */
    private function _get_house_click_num( $datetime = '' , $tbl = '',$city='' )
    {
		$this->_city = $city!="" ? $city : $this->_city;
        $key = $this->memkey.'_get_house_click_num_'.$datetime.'_'.$tbl.'_'.$this->_city.'_'.$this->_uid.'_'.$this->_rowid;

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

        $click_num = array();

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

        if( $cache_data['is_ok'] == 1 )
        {
            $click_num = $cache_data['data'];
        }
        else
        {
            //base_filter
            $where_cond = "city = '".$this->_city."' AND uid = '".$this->_uid."' ";

            //type_filter
            if( in_array( $tbl , array( 'sell' , 'rent' ) ) )
            {
                $where_cond .= " AND tbl = '".$tbl."' ";
            }

            //查询某个房源的点击量
            if( $this->_rowid > 0 )
            {
                $where_cond .= " AND rowid = '".$this->_rowid."' ";
            }

            //时间参数
            $datetime = !empty( $datetime ) ? $datetime : date( 'Y-m-d' , time() - 86400 );
            //开始时间
            $datetime_start  = date('Y-m-d H:i:s', strtotime($datetime) ) ;
            //结束时间
            $datetime_end  = date('Y-m-d H:i:s', strtotime($datetime) + 86400 ) ;

            $where_cond .= " AND click_time BETWEEN '".$datetime_start."' AND  '".$datetime_end."'";

            $day = date('Ymd',strtotime( $datetime_start ) );

            $tbl_name = $this->_get_tblname_by_date( $day, $this->_log_click_tbl );

            //判断表是不是存在
            $is_exist = $this->_tbl_exists($tbl_name);

            if( $is_exist )
            {

                //查询条件
                $this->db_esfbak->where( $where_cond );

                //查询表
                $this->db_esfbak->from($tbl_name);

                //获取数据
                $click_num = $this->db_esfbak->count_all_results();
            }
            else
            {
                 $click_num = 0;
            }

            $this->memcached_class->add($key, array('is_ok'=>1,'data'=>$click_num),1800);
        }

        return $click_num ;
    }


    /**
    * get_house_click
    *
    * 获取个人用户中心房源点击量
    *
    * @access	public
    * @param	mixed   $data 操作日期
    * @param	string  $tbl 房源类型 默认是所有，sell\rent代表sell房源和rent房源
    * @param	int     $offset 偏移数
    * @param	int     $limit 每次取的条数
    * @param	string  $order 升序降序
    * @return	array   操作日志
    */
    private function _get_house_click_list( $datetime , $tbl = '', $offset = 0  , $limit = 0 , $order = 'DESC' )
    {
        $key = $this->memkey.'_get_house_click_list_'.$datetime.'_'.$tbl.'_'.$offset.'_'.$limit.'_'.$order.'_'.$this->_city.$this->_uid;

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

        $arr_data = array();

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

		if( $cache_data['is_ok'] == 1 )
		{
            $arr_data = $cache_data['data'];
        }
        else
        {
            //base_filter
            $where_cond = "city = '".$this->_city."' AND uid = '".$this->_uid."' ";

            //type_filter
            if( in_array( $tbl , array( 'sell' , 'rent' ) ))
            {
                $where_cond .= " AND tbl = '".$tbl."' ";
            }

            //查询某个房源的点击量
            if( $this->_rowid > 0 )
            {
                $where_cond .= " AND rowid = '".$this->_rowid."' ";
            }

            //时间参数
            $datetime = !empty( $datetime ) ? $datetime : date( 'Y-m-d' , time() - 86400 );
            //开始时间
            $datetime_start  = date('Y-m-d H:i:s', strtotime($datetime) ) ;
            //结束时间
            $datetime_end  = date('Y-m-d H:i:s', strtotime($datetime) + 86400 ) ;

            $where_cond .= " AND click_time BETWEEN '".$datetime_start."' AND  '".$datetime_end."'";

            $day = date('Ymd',strtotime( $datetime_start ) );

            $tbl_name = $this->_get_tblname_by_date( $day, $this->_log_click_tbl );

            //判断表是不是存在
            $is_exist = $this->_tbl_exists($tbl_name);

            if( $is_exist === true )
            {
                //查询字段
                if( !empty($this->_select_fields)  &&  is_array( $this->_select_fields ) )
                {
                    $fields_str = implode(',',$this->_select_fields );
                    $this->db_esfbak->select( $fields_str );
                }

                //查询条件
                $this->db_esfbak->where( $where_cond );

                //排序
                $this->db_esfbak->order_by( 'click_time' , $order );

                //limit offset
                if( $limit > 0 || $offset > 0 )
                {
                    $this->db_esfbak->limit( $limit , $offset );
                }

                //查询表
                $this->db_esfbak->from($tbl_name);

                //获取数据
                $arr_data = $this->db_esfbak->get()->result_array();
            }
            else
            {
                 $arr_data = array();
            }

            $this->memcached_class->add( $key , array( 'is_ok' => 1,'data' => $arr_data) , 1800 );
        }

        return $arr_data ;
    }


    /**
    * get_house_click_by_hour
    *
    * 获取个人用户中心房源点击量
    *
    * @access	public
    * @param	mixed   $data 操作日期
    * @param	string  $tbl 房源类型 默认是所有，sell\rent代表sell房源和rent房源
    * @param	int     $offset 偏移数
    * @param	int     $limit 每次取的条数
    * @param	string  $order 升序降序
    * @return	array   操作日志
    */
    public function get_house_click_by_hour( $date , $tbl = '' , $offset = 0  , $limit = 0 , $order = 'DESC')
    {
        //设置查询字段
        $this->set_select_fields(  array( 'uid' , 'tbl' , 'rowid' , 'hour' ) );

        //查询房源点击量数据
        $date_click = $this->_get_house_click_list( $date, $tbl, $offset, $limit, $order);

        return $date_click;
    }


    /**
    * get_house_clicknum_by_id
    *
    * 获取个人用户中心某条房源点击总量
    *
    * @access	public
    * @param	int     $rowid 房源编号
    * @param	string  $tbl 房源类型 默认是所有，sell\rent代表sell房源和rent房源
    * @param	mixed   $data 操作日期
    * @return	int     $click_num  操作日志
    */
    public function get_house_clicknum_by_id( $rowid , $tbl = '' , $date = '',$city='' )
    {
        //点击量情况数组
        $click_num = 0;

        //房源编号
        $rowid = intval($rowid);

        if( $rowid > 0)
        {
            //设置要查询的房源编号
            $this->set_rowid($rowid);

            //查询房源点击量数据
            $click_num = $this->_get_house_click_num( $date , $tbl ,$city );
        }

        return intval($click_num);
    }


    /**
    * get_house_click_by_id
    *
    * 获取个人用户中心某条房源点击详情
    *
    * @access	public
    * @param	int     $rowid 房源编号
    * @param	string  $tbl 房源类型 默认是所有，sell\rent代表sell房源和rent房源
    * @param	mixed   $data 操作日期
    * @param	int     $offset 偏移数
    * @return	array   操作日志
    */
    public function get_house_click_by_id( $rowid ,  $tbl = '' , $date = '')
    {
        //点击量情况数组
        $date_click = array();

        //房源编号
        $rowid = intval($rowid);

        if( $rowid > 0)
        {
            //设置查询字段
            $this->set_select_fields( array( 'uid' , 'tbl' , 'rowid' , 'hour' ) );

            //设置要查询的房源编号
            $this->set_rowid($rowid);

            //查询房源点击量数据
            $date_click = $this->_get_house_click_list( $date , $tbl );
        }

        return $date_click;
    }


	 /**
    * get_telno_state
    *
    * 获取用户短信状态
	* 
	* 1表示一分钟只能已经发送过短信
	* 2表示一天之内已经发过超过10次短信
    * 3表示可以发短信
    */
    public function get_telno_state( $telno)
    {
		$time =time();
		$time_one =$time-60;
		
		$time_start =strtotime(date('Y-m-d 00:00:00') );
		$time_end =strtotime(date('Y-m-d 23:59:59') );
		$ip =$_SERVER['REMOTE_ADDR'];
		$where_cond = "telno = '".$telno."' AND ip = '".$ip."' AND ctime >='".$time_one."' ";
        //查询条件
		$this->db_esfbak->where( $where_cond );
		//查询表
		$this->db_esfbak->from('api_sms');
		//获取数据
		$arr_data = $this->db_esfbak->get()->result_array();
		if($arr_data)
		{
			return 1;
		}

		$where_cond1 = "telno = '".$telno."' AND ip = '".$ip."' AND ctime >='".$time_start."' AND ctime <='".$time_end."' ";
        //查询条件
		$this->db_esfbak->where( $where_cond1 );
		//查询表
		$this->db_esfbak->from('api_sms');
		//获取数据
		$arr_data = $this->db_esfbak->get()->result_array();
		if(count($arr_data)>10)
		{
			return 2;
		}

		return 3;
    }


	/**
    * get_telno_state_app
    *
    * 获取用户app短信状态
	* 
	* 1表示一分钟只能已经发送过短信
	* 2表示一天之内已经发过超过10次短信
    * 3表示可以发短信
    */
    public function get_telno_state_app( $telno)
    {
		$time =time();
		$time_one =$time-60;
		
		$time_start =strtotime(date('Y-m-d 00:00:00') );
		$time_end =strtotime(date('Y-m-d 23:59:59') );
		$ip =$_SERVER['REMOTE_ADDR'];
		$where_cond = "telno = '".$telno."' AND ip = '".$ip."' AND ctime >='".$time_one."' ";
        //查询条件
		$this->db_esfbak->where( $where_cond );
		//查询表
		$this->db_esfbak->from('api_sms_app');
		//获取数据
		$arr_data = $this->db_esfbak->get()->result_array();
		if($arr_data)
		{
			return 1;
		}

		$where_cond1 = "telno = '".$telno."' AND ip = '".$ip."' AND ctime >='".$time_start."' AND ctime <='".$time_end."' ";
        //查询条件
		$this->db_esfbak->where( $where_cond1 );
		//查询表
		$this->db_esfbak->from('api_sms_app');
		//获取数据
		$arr_data = $this->db_esfbak->get()->result_array();
		if(count($arr_data)>10)
		{
			return 2;
		}

		return 3;
    }


	/**
    * check_validcode_state
    *
    * 验证验证码状态
	* 
	* 1表示验证通过
	* 0表示验证未通过
    */
	public function check_validcode_state($telno,$validcode)
	{
		$time =time();
		$time_one =$time-60*3;
		$ip =$_SERVER['REMOTE_ADDR'];
		$status =0;
		$where_cond = "telno = '".$telno."' AND ctime >='".$time_one."' AND status ='".$status."' AND validcode ='".$validcode."' ";
		
        //查询条件
		$this->db_esf->where( $where_cond );
		//查询表
		$this->db_esf->from('api_sms');
		//获取数据
		$arr_data = $this->db_esf->get()->result_array();
		
		if(empty($arr_data))
		{
			return 0;
		}
		else
		{
			return 1;
		}
		
	}
	

	/**
    * check_validcode_state_app
    *
    * 验证app验证码状态
	* 
	* 1表示验证通过
	* 0表示验证未通过
    */
	public function check_validcode_state_app($telno,$validcode)
	{
		$time =time();
		$time_one =$time-60*3;
		$ip =$_SERVER['REMOTE_ADDR'];
		$status =0;
		$where_cond = "telno = '".$telno."' AND ctime >='".$time_one."' AND status ='".$status."' AND validcode ='".$validcode."' ";
		
        //查询条件
		$this->db_esf->where( $where_cond );
		//查询表
		$this->db_esf->from('api_sms_app');
		//获取数据
		$arr_data = $this->db_esf->get()->result_array();
		
		if(empty($arr_data))
		{
			return 0;
		}
		else
		{
			return 1;
		}
		
	}


   /**
    * update_validcode_state
    *
    * 更新验证码状态
	* 
	* 1更新通过
	* 0更新失败
    */

	public function update_validcode_state($telno,$validcode)
	{
		$ip =$_SERVER['REMOTE_ADDR'];
		$arr=array('telno'=>$telno,'ip'=>$ip,'status'=>0,'validcode'=>$validcode);
		$up= array('status'=>1);

		$this->set_table('api_sms');
		$result = $this->save($arr,$up,'esf');

		if($result)
		{
			return 1;
		}
		else
		{
			return 0;
		}
		
		
	
	}

	/**
    * update_validcode_state_app
    *
    * 更新验证码状态
	* 
	* 1更新通过
	* 0更新失败
    */
	public function update_validcode_state_app($telno,$validcode)
	{
		$ip =$_SERVER['REMOTE_ADDR'];
		$arr=array('telno'=>$telno,'ip'=>$ip,'status'=>0,'validcode'=>$validcode);
		$up= array('status'=>1);

		$this->set_table('api_sms_app');
		$result = $this->save($arr,$up,'esf');

		if($result)
		{
			return 1;
		}
		else
		{
			return 0;
		}
		
		
	
	}
}

/* End of file house_statistic_model.php */
/* Location: ./center/model/house_statistic_model.php */
