<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * zsb
 *
 * 房源基础类
 *
 * @package         zsb
 * @author          EllisLab Dev Team
 * @copyright      Copyright (c) 2006 - 2014, HOUSE365, Inc.
 * @link            http://nj.sell.house.com
 * @since           Version 1.0
 */

// ------------------------------------------------------------------------

/**
 * House_attr_model CLASS
 *
 * 房源基础类,提供房源基本操作，包含添删改查。
 *
 * @package         zsb
 * @subpackage      Models
 * @category        Models
 * @author          sun
 * @link            
 */
class House_base_model extends MY_Model {
    
    /**
     * 需要操作的表名
     * @var string 
     */
    protected $tbl = '';
    
    /**
     * 缓存key
     * @var string
     */
    private $_mem_key = '';
    
    /**
     * 房源几种状态的数组
     * @var array 
     */
    protected $house_esta = array(
        'active' => 1,/*激活*/ 'invalid' => 2/*失效*/, 
        'delete' => 4 , /*删除*/ 'frozen' => 5 /*冻结*/,
        'sysfrozen' => 51 /*系统拦截*/,);
    
    /**
     * 房源几种属性数组
     * @var array 
     */
    protected $house_attr = array(
        'isstar' => 3,/*多图*/ 'istag' => 1 /*急推*/
    );

    /**
     * 需要查询的数据表字段
     * @var string 
     */
    protected $select_fields = '';
    
    /**
     * 表数据字段
     * @var string 
     */
    protected $fileds = array();


	/**
     * 类初始化
     */
    public function __construct() 
    {
        parent::__construct(1,1,1);
		$this->_mem_key = GB_CITY.'house_base_model';
    }


    /**
     * 设置查询数据的表名
     * @param string $tbl
     */
    public function set_tbl($tbl) 
    {
        $this->tbl = $tbl;
    }
    
    /**
     * 获取查询数据的表名
     * @return string $tbl 表名
     */
    public function get_tbl() 
    {
         return $this->tbl;
    }
    
    /**
     * 获取房源状态数组
     * @return string $house_esta 房源状态数组
     */
    public function get_house_esta() 
    {
        return $this->house_esta;
    }
    
    
    /**
     * 房源属性数组
     * @return string $house_attr 房源属性数组
     */
    public function get_house_attr() 
    {
        return $this->house_attr;
    }

    
    /**
     * 设置表字段
     */
    public function set_fields()
    {
        $fields = $this->db->field_data($this->get_tbl());
        if ($fields)
        {
            foreach($fields as $v)
            {
                $this->fileds[] = $v->name; 
            }
        }
    }
    
    /**
     * 获取表字段
     * @access	public
     */
    public function get_fields()
    {
        return $this->fileds;
    }
    
    /**
     * 设置需要查询的字段
     * @param array $select_fields
     */
    public function set_select_fields($select_fields)
    {
        $select_fields_str = '';
        if(isset( $select_fields ) && !empty($select_fields))
        {   
            $select_fields_str = implode( ',', $select_fields) ;
        }
        $this->select_fields = $select_fields;
    }
    
    /**
     * 获取需要查询的字段
     * @return type
     */
    public function get_select_fields()
    {
        return $this->select_fields;
    }

    /**
     * 获取满足查询条件的房源条数
     * @param string $where 查询条件
     * @return int 房源数量
     */
    public function find_count_by($where, $selectdb = 0)
    {   
        $num_rows = 0;
        $tbl = $this->get_tbl();
        
        if ($selectdb == 0) 
        {
            $this->dbback->where($where);
            $num_rows = $this->dbback->count_all_results($tbl); 
        } 
        else 
        {
            $this->db->where($where);
            $num_rows = $this->db->count_all_results($tbl); 
        }
        
        return $num_rows;
    }
    
    /**
     * 获取房源列表页
     * @param string $where 查询条件
     * @param int $start 查询开始行
     * @param int $limit 数据偏移量
     * @param int $order_key 排序字段
     * @param string $order_by 升序、降序，默认降序排序
     * @return array 返回多条房源记录组成的二维数组
     */
    public function find_all_by($where, $start = 0, $limit = 20, 
            $order_key = 'updatetime' , $order_by = 'DESC') 
    {   
        $data_info = array();
        //查询字段
        if ($this->select_fields)
        {
            $this->dbback->select($this->select_fields);
        }
        //查询条件
        $this->dbback->where($where);
        //排序条件
        $this->dbback->order_by($order_key, $order_by);
        
        if ( $start >= 0 && $limit > 0 )
        {
            $this->dbback->limit($limit, $start);
        }
        
        $data_info =  $this->dbback->get($this->tbl)->result_array();
        //echo $this->dbback->last_query();
        
        return $data_info;
    }
    
    /**
     * 根据查询条件返回一条房源的记录
     * @param string $where 查询条件
     * @return array 返回一条一维数组的房源记录
     */
    public function find_one_by($where = '')
    {
        //查询字段
        if ($this->select_fields)
        {
            $this->dbback->select($this->select_fields);
        }
        //查询条件
        $this->dbback->where($where);
        return $this->dbback->get($this->get_tbl())->row_array();
    }
    
    /**
     * 根据经纪人编号和房源编号获取基本记录
     * @param int $uid 经纪人编号
     * @param int $id 房源编号
     * @return array 房源记录组成的一维数组
     */
    public function find_by_uid_id($uid, $id) 
    {
        //查询字段
        if ($this->select_fields)
        {
            $this->dbback->select($this->select_fields);
        }
        //查询条件
        $this->dbback->where('id', $id);
        $this->dbback->where('uid', $uid);
        return $this->dbback->get($this->get_tbl())->row_array();
    }
    
    /**
     * 通过房源编号获取房源记录
     * @param int $id 房源编号
     * @return array 房源记录组成的一维数组
     */
    public function find_by_id($id) 
    {
        //查询字段
        if ($this->select_fields)
        {
            $this->dbback->select($this->select_fields);
        }
        //查询条件
        $this->dbback->where('id', $id);
        return $this->dbback->get($this->get_tbl())->row_array();
    }

    /**
     * 插入房源数据
     * @param array $insert_data  插入数据源数组
     * @return int 成功 返回插入成功后的房源id 失败 false
     */
    protected function insert_data($insert_data) 
    {
        if (isset($insert_data[0]) && is_array($insert_data[0]))
        {
            //批量插入
            if ($this->db->insert_batch($this->get_tbl(), $insert_data))
            {
                return $this->db->insert_id();
            }
        } 
        else 
        {
            //单条插入
            if ($this->db->insert($this->get_tbl(), $insert_data))
            {
                return $this->db->insert_id();
            }
        }
        return false;
    }
    
    
    /**
     * 删除房源数据
     * @param array or int $ids 房源编号 可接受整数或者房源数组编号
     * @param int $uid 经纪人编号
     * @return boolean true 成功 false 失败
     */
    protected function delete_data($ids, $uid = '')        
    {
        //多条删除
        if (is_array($ids))
        {
            $arrIds = $ids;
        }
        else
        {
            $arrIds[0] = $ids;
        }

        if ($arrIds)
        {
            if ($uid)
            {
                $this->db->where('uid', $uid);
            }

            $this->db->where_in('id', $arrIds);
            $this->db->delete($this->get_tbl());
        }

        if ($this->db->affected_rows() >0)
        {
            return true;
        }
        else 
        {
            return false;
        }
    }

    /**
     * 更新房源数据
     * @param array $update_data 更新的数据源数组
     * @param array $ids 房源编号数组
     * @param int $uid 经纪人编号
     * @return int 成功后返回受影响的行数
     */
    protected function update_data($update_data, $ids, $uid = '')
    {   
        if (is_array($ids))
        {
            $arrIds = $ids;
        }
        else
        {
            $arrIds[0] = $ids;
        }

        $this->db->where_in('id', $arrIds);

        if ($uid)
        {
            $this->db->where('uid', $uid);
        }
        
        if (isset($update_data[0]) && is_array($update_data[0]))
        {
            $this->db->update_batch($this->get_tbl(), $update_data);
        }
        else 
        {
            $this->db->update($this->get_tbl(), $update_data);
        }

        return $this->db->affected_rows();
    }
    

    /**
     * 获取经纪人激活房源
     * @param int $uid 经纪人编号
     * @return int 返回经纪人激活房源条数
     */
    public function find_active_house_count($uid)
    {
        $this->dbback->where('uid', $uid);
        $this->dbback->where('esta', $this->house_esta['active']);
        return $this->dbback->count_all_results($this->get_tbl());
    }
    

    /**
     * 获取激活多图房源
     * @param type $uid 经纪人编号
     * @return int  返回经纪人激活多图房源条数
     */
    public function find_active_star_house_count($uid)
    {
        $this->dbback->where('uid', $uid);
        $this->dbback->where('esta', $this->house_esta['active']);
        $this->dbback->where('isstar', $this->house_attr['isstar']);
        return $this->dbback->count_all_results($this->get_tbl());
    }
    

    /**
     * 获取发布过房源的小区名称
     * @param int $uid 经纪人编号
	 * @param string $house_esta 发布房源状态
     * @return array 小区名称组成二维数组
     */
    public function find_publish_block( $uid ,$house_esta = 'active')
    {	
		$publish_block = array();
		$mem_key = $this->_mem_key.'_find_publish_block_'.$uid.'_'.$house_esta.'_'.$this->tbl.'_'.$this->select_fields;
		$cache = $this->mc->get($mem_key);

		if(isset($cache['is_ok']) && $cache['is_ok'] == 1 )
		{
			$publish_block = $cache['data'];
		}
		else
		{
			//查询字段
			if ($this->select_fields)
			{
				$this->dbback->select($this->select_fields);
			}

			$this->dbback->where('uid', $uid);
			if($house_esta == 'active')
			{
				$this->dbback->where('esta', $this->house_esta['active']);
			}
			else if(isset($this->house_esta[$house_esta]) && $this->house_esta[$house_esta] > 0 )
			{
				$this->dbback->where('esta', $this->house_esta[$house_esta]);
			}
			
			$this->dbback->where('blockshowname != ', '');
			$this->dbback->where('blockid != ', 0);
			$this->dbback->group_by('blockid');
			$publish_block =  $this->dbback->get($this->tbl)->result_array();
			
			$this->mc->add($mem_key, array('is_ok'=>1,'data'=>$publish_block),120);
		}

		return $publish_block;
    }
    

    /**
     * 获取有效房源的数量 默认是 激活+冻结
     * @param int $uid 经纪人编号
     * @return int 
     */
    public function valid_house_num($uid)
    {
        $where = "uid = $uid AND esta in ({$this->house_esta['active']},{$this->house_esta['frozen']}) AND infofrom = '5'";
        //$where = "uid = $uid AND esta={$this->house_esta['active']} AND infofrom = '5'"; //2020-08-31 chenlei 去掉冻结房源的数量
        return $this->find_count_by($where, 1);
    }
    

    /**
     * 获取库房源的数量 默认是 激活+冻结+失效
     * @param int $uid 经纪人编号
     * @return int 
     */
    public function stock_house_num($uid)
    {
        $where = "uid = $uid AND esta in ({$this->house_esta['active']},{$this->house_esta['frozen']},{$this->house_esta['invalid']})  AND infofrom = '5'";

        return $this->find_count_by($where,0);
    }
    

    /**
     * 记录用户操作房源状态的行为轨迹
     * @param string $companycode 公司编号
     * @param int $uid 经纪人编号
     * @param string $tbl 表名
     * @param int $rowid 房源编号
     * @param int $msg 房源状态位 0:删除房源 1:新增普通有效房源 
     *   2:新增普通失效房源 3:房源再发布 4:失效房源 5:新增多图有效房源 
     *   6:新增多图失效房源 7:租售宝刷新 8:手机租售宝刷新 9:多图改为非多图
     */
    public function action_log($companycode, $uid, $tbl, $rowid, $msg)
    {
		//新
        $oper_table = 'log_broker_oper';
		//旧
        $tmp_table = 'log_broker_tmp';
        
        $arr = explode( ',' , $rowid);
        $ss = array();
        $ss["agentcode"]    = $companycode;
        $ss["uid"]  = $uid;
        $ss["tbl"]  = $tbl;
        $ss["msg"]  = $msg;       
        $ss["y"]    = date('Y');
        $ss["m"]    = date('m');
        $ss["d"]    = date('d');
        $ss["time"] = date('Hi');
		$ss["date"]	= date('Ymd');
        $ss["ip"]   = get_ip();
        
        foreach( $arr as $k=>$v ) 
        {

			//存入多张表
			$kind = rand(1,2);

			if($kind == 1){
				$oper_table = 'log_broker_oper';
			}elseif($kind == 2){
				$oper_table = 'log_broker_oper2';
			}

            $ss["rowid"] = $v;
            $this->db->insert($oper_table, $ss);
        }
        
        if( $msg == 1 || $msg == 2 )
        {
            $time = date("Y-m-d");
            $num = count($arr);
            $this->dbback->select('id');
            $this->dbback->where('uid', $uid);
            $this->dbback->where('updatetime', $time);
            
            $result = array();
            $result = $this->dbback->get($tmp_table)->row_array();
            
            if($result)
            {
                $this->db->where('id', $result['id']);
                $update_data = array('num' => 'num + 1');
                $this->db->update($tmp_table, $update_data);
            }
            else
            {
                $insert_data = array(
                    'num' => $num, 'agentcode' => $companycode,
                    'uid' => $uid, 'updatetime' => $time
                );
                $this->db->insert($tmp_table, $insert_data);
            }
        }
    }
}

/* End of file house_base_model.php */
/* Location: ./zsb/model/house_base_model.php */