<?php
/**
 * 出售房源信息管理
 * @package Apps
 */ 

class HouseSell {

	/**
	 * @var Object $db 数据库查询对象
	 * @access private
	 */
	var $db = NULL;
	
	/**
	 * 出售房源基本信息表
	 *
	 * @var string
	 */
	var $tName = 'fke_housesell';
	
	var $base = 'fke_base';
	/**
	 * 出售房源图片信息列表
	 *
	 * @var string
	 */
	var $tNamePic = 'fke_housesell_pic';
	/**
	 * 点击统计表，按天统计
	 *
	 * @var string
	 */
	var $tNameStat = 'fke_housesell_stat';
	/**
	 * 出售房子成交列表
	 *
	 * @var string
	 */
	var $tNameBargain = 'fke_housesell_bargain';
	
	/**
	 * 执行时间
	 *
	 * @var string
	 */
	var $dotime = 'fke_dotime';
	
	/**
	 * 出售房源置顶
	 *
	 * @var string
	 */
	var $tNameSellTop = 'fke_housesell_top';
	
	function HouseSell($db) {
		$this->db = $db;
	}
	
	/**
	 * 取房源列表
	 * @param array limit 
	 * @param Enum $flag 0：全部 ， 1：已审核 ，2：未审核 3:未审核和已通过的 4：未通过的
	 * @access public
	 * @return array
	 */
	function getList($pageLimit,$fileld='*' , $flag = 0,$where_clouse = '',$order='') {
		$where =' where 1 = 1' ;
		if($where_clouse){
			$where .= $where_clouse;
		}
		if($flag == 1){
			$where .= " and is_checked = 1 ";
		}elseif($flag == 2){
			$where .= " and is_checked = 0 ";
		}elseif($flag == 3){
			$where .= " and (is_checked = 0 or is_checked = 1 )";
		}elseif($flag == 4){
			$where .= " and is_checked = 2";
		}elseif($flag == 5){
			$where .= " and is_index = 1";
		}elseif($flag == 6){
			$where .= " and status = 1";
		}elseif($flag == 7){
			$where .= " and status = 2";
		}elseif($flag == 8){
			$where .= " and status = 3";
		}elseif($flag == 9){
			$where .= " and (status = 4 or status = 7)";
		}
		elseif($flag == 10){
			$where .= " and is_top = 1";
		}
		$this->db->open('select '.$fileld.' from '.$this->tName.$where.' '.$order , $pageLimit['rowFrom'],$pageLimit['rowTo']);
		$result = array();
		while ($rs = $this->db->next()) {
			$result[] = $rs;
		}
		return $result;
	}
	
	/**
	 * 保存置顶房源
	 * @param array $days 天数
	 * @access public
	 * @return bool
	 */
	function housetopsave($fileddata) {
		$field_array  = array(
			'member_id'=>$fileddata['member_id'],
			'housesell_id'=>$fileddata['house_id'],
			'add_time'=>time(),
			'to_time'=>$fileddata['to_time'],
		);
		return $this->db->insert($this->tNameSellTop,$field_array);
		}

	/**
	 * 保存房源信息
	 * @param array $borough 基本表单数组
	 * @param array $boroughInfo 详细表单数组
	 * @access public
	 * @return bool
	 */
	function save($fileddata) {
		global $cfg,$query,$page;
		//特殊处理,只转递过来小区名字没有小区ID，那是由于用户直接输入小区名字没有选择下拉列表
		$borough = new Borough($query);
		if(!$fileddata['borough_id']){
			$fileddata['borough_id'] = $borough->getIdByName($fileddata['borough_name']);
			//没有找到该小区
			if(!$fileddata['borough_id']){
				$page->back('没有搜索到相关的小区，请确认你的小区名称');
			}
			$fileddata['cityarea_id'] =  $borough->getInfo($fileddata['borough_id'],'cityarea_id');
			$fileddata['cityarea2_id'] =  $borough->getInfo($fileddata['borough_id'],'cityarea2_id');
		}else{
			$fileddata['cityarea_id'] =  $borough->getInfo($fileddata['borough_id'],'cityarea_id');
			$fileddata['cityarea2_id'] =  $borough->getInfo($fileddata['borough_id'],'cityarea2_id');
		}
		
		//房源特色，前后加，号便于搜索匹配
		if($fileddata['house_feature']){
			$fileddata['house_feature'] = ','.implode(',',$fileddata['house_feature']).',';
		}
		
		$field_array  = array(
			'house_title'=>$fileddata['house_title'],
			'cityarea_id'=>$fileddata['cityarea_id'],
			'cityarea2_id'=>$fileddata['cityarea2_id'],
			'house_type'=>$fileddata['house_type'],
			'house_price'=>$fileddata['house_price'],
			'house_totalarea'=>$fileddata['house_totalarea'],
			'house_room'=>$fileddata['house_room'],
			'house_hall'=>$fileddata['house_hall'],
			'house_toilet'=>$fileddata['house_toilet'],
			'house_veranda'=>$fileddata['house_veranda'],
			'video'=>$fileddata['video'],
			'house_topfloor'=>$fileddata['house_topfloor'],
			'house_floor'=>$fileddata['house_floor'],
			'house_age'=>$fileddata['house_age'],
			'house_toward'=>$fileddata['house_toward'],
			'house_fitment'=>$fileddata['house_fitment'],
			'house_feature'=>$fileddata['house_feature'],
			'house_desc'=>$fileddata['house_desc'],
			'borough_id'=>$fileddata['borough_id'],
			'borough_name'=>$fileddata['borough_name'],
			'broker_id'=>$fileddata['broker_id'],
			'company_id'=>$fileddata['company_id'],
			'belong'=>$fileddata['belong'],
			'owner_name'=>$fileddata['owner_name'],
			'owner_phone'=>$fileddata['owner_phone'],
			'owner_notes'=>$fileddata['owner_notes'],
			'is_vexation'=>$fileddata['vexation'],
		);

         //如果勾选加急房源选项，从会员表中减少条数,编辑房源除外
		 if(empty($fileddata['id'])){
		   if($fileddata['vexation']==1){
			 $member = new Member($query);
			 $member->deleteVexation($fileddata['broker_id'],'1');
			    }
			 }

		//取图片第一张作为房源缩略图
		if($fileddata['house_picture_thumb'][0]){
			$field_array['house_thumb'] =$fileddata['house_picture_thumb'][0];	
		}
		
		if($fileddata['id']){
			//编辑
			$field_array['drawing_id'] = $fileddata['drawing_id'];
			if($fileddata['broker_id']==0){
				$field_array['is_checked'] = $fileddata['is_checked'];
				}
			$field_array['updated']=time();
			$house_id= intval($fileddata['id']);
			$houseInfo = $this->getInfo($house_id,'house_drawing,created');
			//编辑今天的房源计算时间
			$today = mktime(0,0,0,date('m'),date('d'),date('Y'));
			if($houseInfo['created']>$today){
				$field_array['update_order']=$cfg['time']+14400;
			}else{
				$field_array['update_order']=$cfg['time'];
			}
			
			/*
			if($houseInfo['house_drawing'] != $fileddata['house_drawing']){
				//把户型图插入到小区中去
				$insert_drawing = array(
					'pic_url'=>$fileddata['house_drawing'],
					'pic_thumb'=>$fileddata['house_drawing_thumb'],
					'pic_desc'=>$fileddata['house_drawing_desc'],
					'borough_id'=>$fileddata['borough_id'],
					'creater'=>$fileddata['creater'],
					'addtime'=>$cfg['time'],
				);
				$field_array['drawing_id'] = $borough->insertDrawing($insert_drawing);
				$field_array['house_drawing'] = $fileddata['house_drawing'];
			}
			*/
			$field_array['house_drawing'] = $fileddata['house_drawing'];
			
			$this->db->update($this->tName,$field_array,'id = '.$house_id);
			$this->db->execute('delete from '.$this->tNamePic.' where housesell_id ='.$house_id);
			//插入房源图片	
			if(is_array($fileddata['house_picture_url'])){
				foreach($fileddata['house_picture_url'] as $key => $pic_url){
					$imgField = array(
						'pic_url'=>$pic_url,
						'pic_thumb'=>$fileddata['house_picture_thumb'][$key],
						'pic_desc'=>$fileddata['house_picture_desc'][$key],
						'housesell_id'=>$house_id,
						'creater'=>$fileddata['creater'],
						'addtime'=>$cfg['time'],
					);
					$this->db->insert($this->tNamePic,$imgField);
				}
			}
			
		}else{
			//增加
			$statistics = new Statistics($query);
			$house_no = $statistics->getNum('housesell_no')+1;
			$field_array['house_no']=$cfg['cityCode'].sprintf("%07d",$house_no);
			//增加1
			$statistics->add('housesell_no');
			
			$field_array['consigner_id']=$fileddata['consigner_id'];
			$field_array['created']=$cfg['time'];
			$field_array['updated']=$cfg['time'];
			//新发房源有4个小时的优先显示
			$field_array['update_order']=$cfg['time']+14400;
			
			//游客发布进入未审核状态
		    if($fileddata['broker_id']==0){
			$field_array['is_checked'] =0;
			}
			
			$field_array['status']=$fileddata['status']?$fileddata['status']:1;
			
			//把户型图插入到小区中去
			/*
			if($fileddata['house_drawing']){
				$insert_drawing = array(
					'pic_url'=>$fileddata['house_drawing'],
					'pic_thumb'=>$fileddata['house_drawing_thumb'],
					'pic_desc'=>$fileddata['house_drawing_desc'],
					'borough_id'=>$fileddata['borough_id'],
					'creater'=>$fileddata['creater'],
					'addtime'=>$cfg['time'],
				);
				$field_array['drawing_id'] = $borough->insertDrawing($insert_drawing);
			}
			*/
			$field_array['house_drawing'] = $fileddata['house_drawing'];
			
			//把图片插入到小区中去	
			/*
			if(is_array($fileddata['borough_picture_url'])){
				foreach($fileddata['borough_picture_url'] as $key => $pic_url){
					$imgField = array(
						'pic_url'=>$pic_url,
						'pic_thumb'=>$fileddata['borough_picture_thumb'][$key],
						'pic_desc'=>$fileddata['borough_picture_desc'][$key],
						'borough_id'=>$fileddata['borough_id'],
						'creater'=>$fileddata['creater'],
						'addtime'=>$cfg['time'],
					);
					$borough->insertPic($imgField);
				}
			}
			*/
			//插入到房源审核中
			if(is_array($fileddata['borough_picture_url'])){
				$borough_update = new BoroughUpdate($query);
				$pic_list = $borough->getImgList($_POST['borough_id'],0);

				if($pic_list){
					$picList = array();
					foreach ($pic_list as $item){
						$picList[] = $item['pic_url'];
					}
					$old_value = implode('|',$picList);
				}
				foreach($fileddata['borough_picture_url'] as $key => $pic_url){
					$newValue = $fileddata['borough_picture_desc'][$key]."|".$pic_url."|".$fileddata['borough_picture_thumb'][$key];
					$boroughUpdateField = array(
				 		'borough_id'=>$fileddata['borough_id'],
				 		'id'=>'borough_pic',
				 		'old_value'=>$old_value,
				 		'value'=>$newValue,
				 		'broker_id'=>$fileddata['broker_id'],
				 	);
				 	$borough_update->save($boroughUpdateField);
				}
			}

			$this->db->insert($this->tName,$field_array);
			$house_id = $this->db->getInsertId();
			//统计
			$statistics->add('sellNum');
			//对应小区中增加一个房源
			$borough->increase($fileddata['borough_id'],'sell_num');
			
			//插入房源图片	
			if(is_array($fileddata['house_picture_url'])){
				foreach($fileddata['house_picture_url'] as $key => $pic_url){
					$imgField = array(
						'pic_url'=>$pic_url,
						'pic_thumb'=>$fileddata['house_picture_thumb'][$key],
						'pic_desc'=>$fileddata['house_picture_desc'][$key],
						'housesell_id'=>$house_id,
						'creater'=>$fileddata['creater'],
						'addtime'=>$cfg['time'],
					);
					$this->db->insert($this->tNamePic,$imgField);
				}
			}
		}
		
		return $house_id;
	}
	
	/**
	 * 房源刷新统计脚本执行
	 */
	function dorefresh() {
		$today = mktime(0,0,0,date('m'),date('d'),date('Y'));
		$data = $this->getDotime('time');
		if($today != $data) {
			 $this->db->execute('update '.$this->tName.' set refresh = 2');
			 $this->db->execute('update '.$this->dotime.' set time = '.$today);
			}
	}
	
	/**
	 * 取房源信息
	 * @param string $id 小区ID
	 * @param string $field 主表字段
	 * @access public
	 * @return array
	 */
	function getInfo($id, $field = '*') {
		return $this->db->getValue('select ' . $field . ' from '.$this->tName.'  where id=' . $id);
	}
	
	/**
	 * 取执行时间
	 */
	function getDotime($field = '*') {
		return $this->db->getValue('select ' . $field . ' from '.$this->dotime);
	}
	
	/**
	 * 房源置顶过期信息
	 * @param string $id 小区ID
	 * @param string $field 主表字段
	 * @access public
	 * @return array
	 */
	function getToTime() {
		$shijian = time();
		return $this->db->select('select housesell_id from '.$this->tNameSellTop.'  where to_time <='.$shijian);
	}
	
	/**
	 * 删除置顶房源记录
	 * @param mixed $ids 选择的ID
	 * @access public
	 * @return bool
	 */
	function deleteTop($ids) {
		if (is_array($ids)) {
			$ids = implode(',',$ids);
			$where = ' where housesell_id in (' . $ids . ')';
		} else {
			$where = ' where housesell_id=' . intval($ids);
		}
		$this->db->execute('delete from '.$this->tNameSellTop. $where);
		return true;
		
	}
	
	
	
	/**
	 * 删除房源信息
	 * @param mixed $ids 选择的ID
	 * @access public
	 * @return bool
	 */
	function delete($ids) {
		
		if (is_array($ids)) {
			$ids = implode(',',$ids);
			$where = 'id in (' . $ids . ')';
		} else {
			$where = 'id=' . intval($ids);
		}
		
		$nohouseid = $this->db->select('select id from '.$this->tName.' where '.$where );
		if(!empty($nohouseid)){
			$nohouseid = implode(',',$nohouseid);
			$deletewhere = ' where id in (' . $nohouseid . ')';
			$deletewhere1 = ' where housesell_id in (' . $nohouseid . ')';
			$deletewhere2 = ' where house_id in (' . $nohouseid . ')';
			
			$this->db->execute('delete from '.$this->tName. $deletewhere);
			$this->db->execute('delete from '.$this->tNamePic.$deletewhere1);
			$this->db->execute('delete from '.$this->tNameStat.$deletewhere2);
			$this->db->execute('delete from '.$this->tNameBargain.$deletewhere2);
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 操作状态 不物理删除
	 * @param mixed $ids ID
	 * @access public
	 * @return bool
	 */
	function changeStatus($ids,$status) {
		if (is_array($ids)) {
			$ids = implode(',',$ids);
			$where = ' id in (' . $ids . ')';
		} else {
			$where = ' id=' . intval($ids);
		}
		return $this->db->execute('update '.$this->tName.' set status = '.$status.' where ' . $where);
	}
	/**
	 * 更新某个字段
	 * @param mixed $ids ID
	 * @access public
	 * @return bool
	 */
	function update($ids,$field,$value) {
		if (is_array($ids)) {
			$ids = implode(',',$ids);
			$where = ' id in (' . $ids . ')';
		} else {
			$where = ' id=' . intval($ids);
		}
		return $this->db->execute('update '.$this->tName.' set '.$field.' = \''.$value.'\' where ' . $where);
	}
	
	/**
	 * 更新刷新次数
	 * @param mixed $ids ID
	 * @access public
	 * @return bool
	 */
	function updateRefresh($ids) {
		if (is_array($ids)) {
			$ids = implode(',',$ids);
			$where = ' id in (' . $ids . ')';
		} else {
			$where = ' id=' . intval($ids);
		}
		return $this->db->execute('update '.$this->tName.' set refresh = refresh -1 where ' . $where);
	}
	
	/**
	 * 审核房源
	 * @param mixed $ids 选择的ID
	 * @access public
	 * @return bool
	 */
	function check($ids,$flag) {
		$where = ' where 1=1 ';
		if (is_array($ids)) {
			$ids = implode(',',$ids);
			$where .= ' and id in (' . $ids . ')';
		} else {
			$where .= ' and id=' . intval($ids);
		}
		
		return $this->db->execute('update '.$this->tName.' set is_checked = '.$flag.$where);
	}
	
	/**
	 * 审核房源
	 * @param mixed $ids 选择的ID
	 * @access public
	 * @return bool
	 */
	function promote($ids,$flag) {
		$where = ' where 1=1 ';
		if (is_array($ids)) {
			$ids = implode(',',$ids);
			$where .= ' and id in (' . $ids . ')';
		} else {
			$where .= ' and id=' . intval($ids);
		}
		
		return $this->db->execute('update '.$this->tName.' set is_promote = '.$flag.$where);
	}
	
	/**
	 * 刷新房源
	 * @param mixed $ids ID
	 * @access public
	 * @return bool
	 */
	function refresh($ids) {
		if (is_array($ids)) {
			$ids = implode(',',$ids);
			$where = ' id in (' . $ids . ')';
		} else {
			$where = ' id =' . intval($ids);
		}
		//分开操作，保证今天发的房源排在刷新房源前面
		$to_day = mktime(0,0,0,date('m'),date('d'),date('Y'));
		$now_time = time();
		$this->db->execute("update ".$this->tName." set updated = ".$now_time.",update_order = ".($now_time+14400)."  where " . $where." and created>=".$to_day);
		$this->db->execute("update ".$this->tName." set updated = ".$now_time.",update_order = ".$now_time."  where " . $where." and created<".$to_day);
		return true;
	}
	
	/**
	 * 取总用户数
	 * @access public
	 * @return NULL
	 */
	function getCount($flag = 0,$where_clouse = '') {
		$where =" where 1 = 1";
		if($flag == 1){
			$where .= " and is_checked = 1";
		}
		if($flag == 2){
			$where .= " and is_checked = 0";
		}
		if($flag == 3){
			$where .= " and (is_checked = 0 or is_checked = 1 )";
		}
		if($flag == 5){
			$where .= " and is_index= 1";
		}if($flag == 6){
			$where .= " and status = 1";
		}if($flag == 7){
			$where .= " and status = 2";
		}if($flag == 8){
			$where .= " and status = 3";
		}if($flag == 9){
			$where .= " and (status = 4 or status = 7)";
		}
		if($flag == 10){
			$where .= " and is_top = 1";
		}
		if($where_clouse){
			$where.= $where_clouse;
		}
		
		return $this->db->getValue('select count(*) from '.$this->tName. $where );
	}

	/**
	 * 取得所有符合条件的房源
	 *
	 * @param unknown_type $columns
	 * @param unknown_type $condition
	 * @param unknown_type $order
	 * @return unknown
	 */
	function getAll($columns='*',$condition='',$order = ''){
		if($condition != ''){
			$condition = ' where ' .$condition;
		}
		return $this->db->select('select '.strtolower($columns).' from '.$this->tName.$condition.' '.$order);
	}

	/**
	 * 图片的列表
	 *
	 * @param string 出售房源ID $housesell_id
	 * @param string 字段
	 */
	function getImgList($housesell_id,$field = '*')
	{
		return $this->db->select('select '.$field.' from '.$this->tNamePic.' where housesell_id = '.$housesell_id);
	}
	/**
	 * 图片数量
	 *
	 * @param string 出售房源ID $housesell_id
	 * @return number
	 */
	function getImgNum($housesell_id)
	{
		return $this->db->getValue('select count(*) from '.$this->tNamePic.' where housesell_id = '.$housesell_id);
	}
	/**
	 * 图片属性
	 *
	 * @param string 出售房源ID $housesell_id
	 * @return number
	 */
	function getImgInfo($pic_id,$field = '*')
	{
		return $this->db->getValue("select ".$field." from ".$this->tNamePic." where id = ".$pic_id);
	}
	/**
	 * 删除房源的图片
	 *
	 * @param int $picid
	 * @return bool
	 */
	function delHousePic($picid )
	{
		return $this->db->execute('delete from '.$this->tNamePic.' where id = '.$picid );
	}
	/**
	 * 删除房源的户型图
	 *
	 * @param int $dataid
	 * @return bool
	 */
	function delHouseDraw($dataid )
	{
		return $this->db->execute('update '.$this->tName.' set house_drawing=\'\',drawing_id = 0 where id = '.$dataid );
	}
	/**
	 * 取得房源点击数
	 * 按天统计
	 * @param housell_id
	 * @param date
	 * @return num
	 * 
	 */
	function getClick($house_id , $date)
	{
		return $this->db->getValue('select click_num from '.$this->tNameStat.' where house_id = '.$house_id.' and stat_date =\''.$date.'\'' );
	}
	
	/**
	 * 取得置顶房源到期时间
	 * 按天统计
	 * @param housell_id
	 * @param date
	 * @return num
	 * 
	 */
	function getTopTotime($house_id)
	{
		return $this->db->getValue('select to_time from '.$this->tNameSellTop.' where housesell_id = '.$house_id);
	}
	/**
	 * 增加点击数 ， 需要增加总数和每天点击数
	 *
	 * @param int $house_id
	 */
	function addClick($house_id)
	{
		$today = date("Y-m-d",time());
		if($stat_id = $this->db->getValue('select id from '.$this->tNameStat.' where house_id = '.$house_id.' and stat_date =\''.$today.'\'' )){
			$this->db->execute('update '.$this->tNameStat.' set  click_num = click_num+1 where id = '.$stat_id );
		}else{
			$this->db->execute("insert into ".$this->tNameStat." (house_id,click_num,stat_date) value ('".$house_id."','1','".$today."')");
		}
		return $this->db->execute('update '.$this->tName.' set  click_num = click_num+1 where id = '.$house_id );
	}
	/**
	 * 按某个字段计算数量
	 *
	 * @param string $field
	 * @param string $where
	 * @return array
	 */
	function getCountGroupBy($field,$where='',$having_count=2)
	{
		if($where != ''){
			$where = ' where ' .$where;
		}
		
		return $this->db->select('select '.$field.',count(*) as house_num from '.$this->tName.$where." group by ".$field.' having house_num >='.$having_count);
	}
}
?>