<?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_Wang_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 => '再发布' );

    /**
    *  操作类型键值表
    *
    * @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;
    }


    /**
    * 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 ;
    }


    /**
    * 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();

			//base_filter
			$where_cond = "city = '".$this->_city."' AND uid = '".$this->_uid."' ";

			//type_filter
			if( !empty( $type ) && is_numeric($type) )
			{
				$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();

            //base_filter
            $where_cond = "city = '".$this->_city."' AND uid = '".$this->_uid."' ";

            //type_filter
            if( !empty( $type ) && is_numeric($type) )
            {
                $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 ) ;

            $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_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( $is_exist || $creat_result )
		{
			$this->set_table($tbl_name);
			$insert_id  = $this->add($data);
		}

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

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

		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;
    }

	/**
    * 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;
		}
		
	}
	
   /**
    * 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;
		}
		
		
	
	}
}

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