<?php
/**
 *租售宝经纪人积分类 BrokerCredit
 *Fisher 2012-10-31
**/

class BrokerCredit
{
	var $uid;	//经纪人UID
	var $db;	//数据库
	var $credit_arr = array(
			'plus_open' 	  => array('title'=>'端口开通',			'sign'=>'+', 'credit'=>200),
			'plus_identity'	  => array('title'=>'身份认证',			'sign'=>'+', 'credit'=>300),
			'plus_card' 	  => array('title'=>'名片认证',			'sign'=>'+', 'credit'=>200),
			'plus_login' 	  => array('title'=>'登录',				'sign'=>'+', 'credit'=>15),
			'plus_answer' 	  => array('title'=>'回复问答',			'sign'=>'+', 'credit'=>10),
			'plus_bestanswer' => array('title'=>'最佳答案',			'sign'=>'+', 'credit'=>20),
			'plus_login_mobile'=> array('title'=>'客户端登录',		'sign'=>'+', 'credit'=>50),
			'plus_isstar'	  => array('title'=>'发布多图房源',		'sign'=>'+', 'credit'=>100),
			'plus_isstar_mobile'=> array('title'=>'客户端发多图',	'sign'=>'+', 'credit'=>200),
			'plus_blockimg'	  => array('title'=>'小区图库收录',		'sign'=>'+', 'credit'=>200),
			'plus_windowback' => array('title'=>'橱窗积分返还',		'sign'=>'+', 'credit'=>0),
			'plus_operate'	  => array('title'=>'系统变更',			'sign'=>'+', 'credit'=>0),
			'plus_block'	  => array('title'=>'返还申请小区专家',	'sign'=>'+', 'credit'=>500),
			'plus_birthday'   => array('title'=>'生日积分领取',		'sign'=>'+', 'credit'=>2000),
			'plus_refresh_mobile'=> array('title'=>'客户端刷新',	'sign'=>'+', 'credit'=>200),
			'plus_block_supply' => array('title'=>'小区资料完善(返还)',	'sign'=>'+', 'credit'=>2000),
			'minus_block_supply' => array('title'=>'小区资料完善(冻结)',	'sign'=>'-', 'credit'=>2000),
			'minus_block'	  => array('title'=>'成功申请小区专家',	'sign'=>'-', 'credit'=>500),
			'minus_frozen'	  => array('title'=>'冻结房源',			'sign'=>'-', 'credit'=>100),
			'minus_window'	  => array('title'=>'橱窗展示投入',		'sign'=>'-', 'credit'=>0, 'viewcredit'=>-2),
			'minus_operate'	  => array('title'=>'系统变更积分',		'sign'=>'-', 'credit'=>0)
	);

	var $no_settlement = array('plus_open', 'plus_identity', 'plus_card','plus_answer','plus_bestanswer');	//不计入月度流水的操作
	var $allow_lesszero_arr = array('minus_frozen');	//允许操作积分使其小于0的操作

	var $time = 0; //操作时间
	var $brokercredit = 0; //经纪人当前积分
	var $groupid = 0;	//经纪人权限组

	/**
	* BrokerCredit 构造方法
	*
	* @param int $uid
	*/
	function BrokerCredit($uid)
	{
		global $db;
		$this->uid = $uid;
		$this->db = $db;
		$this->time = time();
		$this->groupid = $this->getBrokerGroupid();
	}

	/**
	* dealCredit 操作经纪人积分，所有积分操作调用此方法
	*
	* @param str $kind
	* @param arr $params  op_credit,operator,reason/rowid,tbl
	* @return bool
	*/
	function dealCredit($kind, $params = array())
	{

		//付费经纪人的有效的积分操作
		if( $this->groupid == 1 && isset($this->credit_arr[$kind]) )
		{
			//初始化操作分数
			$credit = $this->credit_arr[$kind]['credit'];
			//取经纪人套餐积分上限数据
			$package = $this->getBrokerPackageInfo();

			switch($kind)
			{
				//经纪人登录加分(每天一次)
				case 'plus_login' :		
				case 'plus_login_mobile':
										$brokerlogintime = $this->getBrokerLoginTimeByKind($kind);	//获取经纪人最后登录时间
										$credit = date('Ymd') != $brokerlogintime ? $this->credit_arr[$kind]['credit'] : 0;
										break;
				//手机客户端刷新房源(每天一次)
				case 'plus_refresh_mobile' :
										$logtime = $this->getLastCreditLogTimeByKind($kind);
										$credit  = date('Ymd') != $logtime ? $this->credit_arr[$kind]['credit'] : 0;
										break;
                		//经纪人生日积分
				case 'plus_birthday' :	$birthday = $this->getBrokerBirthday();	//获取经纪人最后一次获取生日积分时间
										$credit = date('Ymd') != $birthday ? $this->credit_arr[$kind]['credit'] : 0;
										break;

				//操作手动修改经纪人积分
				case 'plus_operate' :
				case 'minus_operate':

				//操作橱窗展示积分
				case 'plus_windowback' :
				case 'minus_window' :	$credit = intval($params['op_credit']);
										break;

				//操作发布多图积分
				case 'plus_isstar' :	
				case 'plus_isstar_mobile' :
										$monthisstarcredit = $this->getMonthIsstarCredit();
										//本月的多图房源积分超限
										if($monthisstarcredit >= $package['isstar_credit_upper_limit'])
										{
											$credit = 0;
										}
										else
										{
											//加分超限时只增加超限时的分数
											$tempcredit = $package['isstar_credit_upper_limit'] - $monthisstarcredit;
											$credit = $tempcredit > $credit ? $credit : $tempcredit;
										}
										break;

				//此类操作终生只能加分一次
				case 'plus_open' :		$package['credit_upper_limit'] = 200;
				case 'plus_identity' :
				case 'plus_card' :		$check = $this->getCreditLogByKind($kind);
										$credit = $check > 0 ? 0 : $this->credit_arr[$kind]['credit'];
										break;

				//一般积分操作
				default :				$credit = $this->credit_arr[$kind]['credit'];
										break;
			}

			//有效的积分变化
			if( $credit > 0 )
			{
				//初始化经纪人当前积分
				$this->brokercredit = $this->getBrokerCredit();
				//计算经纪人新积分
				$new_brokercredit = 0;
				$sign = $this->credit_arr[$kind]['sign'] == '+' ? 1 : -1;
				$new_brokercredit = $sign * $credit + $this->brokercredit;
				//加分的情况下新积分大于套餐积分上限
				if($sign == 1 && $new_brokercredit > $package['credit_upper_limit'])
				{
					//当前积分大于套餐积分上限
					if($this->brokercredit > $package['credit_upper_limit'])
					{
						$credit = 0;
					}
					else
					{
						//加分超限时只增加超限时的分数
						$credit = $package['credit_upper_limit'] - $this->brokercredit;
						$this->brokercredit = $package['credit_upper_limit'];
					}
				}
				//减分操作情况下经纪人积分可被减为负分，只是前台显示0分
				else
				{
					$this->brokercredit = $new_brokercredit;
				}


				//加分情况无视，减分情况只有特定操作可使积分小于0
				if($sign == -1 && $this->brokercredit < 0 && !in_array($kind, $this->allow_lesszero_arr))
				{
					return false;
				}

				//有效的积分变化
				if($credit > 0)
				{
					$this->doCredit($kind, $credit, $params);
					return true;
				}
			}
		}
		return false;
	}

	/**
	* doCredit 执行经纪人积分操作
	*
	* @param str $kind
	* @param int $credit
	* @param arr $params  operator,reason/rowid,tbl
	*/
	function doCredit($kind, $credit, $params = array())
	{
		$this->addCreditLog($kind, $credit);	//增加经纪人积分流水账表记录
		$this->updateBrokerCredit($this->brokercredit); //更新经纪人积分

		//TRUE表示月度结算中不记录的字段
		$no_settlement = in_array($kind, $this->no_settlement) ? true : false;
		$kind = $kind =='plus_isstar_mobile' ? 'plus_isstar' : $kind;
		$this->updateCreditSettlement($kind, $credit, $no_settlement);	//更新经纪人积分月度结算表记录

		//增加手动修改经纪人积分的操作记录
		if( in_array($kind, array('plus_operate', 'minus_operate')) )
		{
			$this->addCreditOperateLog($kind, $credit, $params['operator'], $params['reason']);
		}
		//增加经纪人发布多图房源加积分的操作记录
		if($kind == 'plus_isstar')
		{
			$this->addIsstarCreditLog($params['rowid'], $params['tbl']);
		}
	}

	/**
	* getCreditLogByKind 根据类型查找积分记录
	*
	* @param str $kind
	* @return integer
	*/
	function getCreditLogByKind($kind)
	{
		$kind = trim($kind);
        $num = $this->db->GetOne("select count(*) from log_credit where lc_uid='".$this->uid."' and lc_kind='".$kind."' ");
		return intval($num);
	}


	/**
	* getCreditLogTimeByKind 根据类型查找积分记录
	*
	* @param str $kind
	* @return integer
	*/
	function getLastCreditLogTimeByKind($kind)
	{
		$kind = trim($kind);
		$log_time = 0;
		$sql = " SELECT lc_time FROM log_credit WHERE lc_uid = '".$this->uid."' AND lc_kind ='".$kind."' ORDER BY lc_time DESC LIMIT 1 ";
        $lc_time = $this->db->GetOne($sql);

		$login_date = date('Ymd', $lc_time);

		return $login_date;
	}


	/**
	* dealCreditWindowback 处理橱窗积分返还
	*
	* @param int $rowid
	* @param str $tbl
	*/
	function dealCreditWindowback($rowid, $tbl)
	{
		$q = "SELECT keys_integral,	display FROM w_broker_house WHERE rowid='".$rowid."' and uid='".$this->uid."' and tbl='".$tbl."' and esta=1 and credit_type = 1 ";
		$w_arr=$this->db->GetRow($q);
		$backcredit = $w_arr['keys_integral'] + $w_arr['display'] * $this->credit_arr['minus_window']['viewcredit'];
		$backcredit = $backcredit <= 0 ? 0 : $backcredit;

		if($backcredit > 0)
		{
			$this->dealCredit('plus_windowback', array('op_credit'=>$backcredit));
		}

	}

	/**
	* addIsstarCreditLog 记录发布多图房源加积分情况
	*
	* @param int $rowid
	* @param int $tbl
	*/
	function addIsstarCreditLog($rowid, $tbl)
	{
		$wc = array();
		$wc['kind'] = 'p_20';
		$wc['uid'] = $this->uid;
		$wc['indate'] = date('Y-m-d',$this->time);
		$wc['title'] = '多图房源';
		$wc['rowid'] = $rowid;
		$wc['tbl'] = $tbl;
		$q = insert_sql("broker_plus",$wc);
		$rs = $this->db->Execute($q);
	}

	/**
	* getBrokerGroupid 获取经纪人Groupid
	*
	* @return integer
	*/
	function getBrokerGroupid()
	{
		$groupid = $this->db->GetOne("select groupid from broker where uid='".$this->uid."'");
		return intval($groupid);
	}

	/**
	* checkIsstarCreditLog 根据房源编号获取该房源的多图房源加积分情况
	*
	* @param int $rowid
	* @param int $tbl
	* @return integer
	*/
	function checkIsstarCreditLog($rowid, $tbl)
	{
		$rowid = intval($rowid);
		$tbl = trim($tbl);

        $num = $this->db->GetOne("select count(*) from broker_plus where uid='".$this->uid."' and rowid='".$rowid."' and tbl='".$tbl."'");
		return intval($num);
	}

	/**
	* getMonthIsstarCredit 获取经纪人当月发布多图获得的积分数
	*
	* @return integer
	*/
	function getMonthIsstarCredit()
	{
		$time = strtotime(date('Y-m', $this->time).'-1 00:00:00');
		//$sum = $this->db->GetOne("SELECT SUM(lc_value) FROM log_credit WHERE lc_uid = '".$this->uid."' AND lc_kind = 'plus_isstar' AND lc_time >= '".$time."' ");
		$sum = $this->db->GetOne("SELECT ls_plus_isstar FROM log_credit_settlement WHERE ls_uid = '".$this->uid."' AND ls_time = '".$time."'");

		return intval($sum);
	}

	/**
	* getBrokerPackageInfo 获取经纪人套餐上限数据
	*
	* @return array
	*/
	function getBrokerPackageInfo()
	{
		$sql = "SELECT bp.isstar_credit_upper_limit, bp.credit_upper_limit FROM broker_package bp LEFT JOIN broker b ON bp.package_id = b.package_id WHERE b.uid = '".$this->uid."'";
		return $this->db->GetRow($sql);
	}

	/**
	* addCreditOperateLog 增加手动修改经纪人积分流水账表记录
	*
	* @param str $kind
	* @param int $credit
	* @param str $operator
	* @param str $reason
	*/
	function addCreditOperateLog($kind, $credit, $operator, $reason)
	{
		$this->db->Execute("INSERT INTO log_credit_operate (lo_uid, lo_value, lo_kind, lo_operator, lo_reason, lo_time) VALUES ('".$this->uid."','".$credit."','".$kind."','".$operator."','".$reason."','".$this->time."')");
	}

	/**
	* updateBrokerCredit 更新经纪人积分
	*
	* @param int $credit
	*/
	function updateBrokerCredit($credit)
	{
		$this->db->Execute("UPDATE broker SET credit = '$credit' WHERE uid = '".$this->uid."'");
	}

	/**
	* getBrokerLoginTime 获取经纪人最后登录时间
	*
	* @return str Ymd
	*/
	function getBrokerLoginTime()
	{
		$brokerlogintime = $this->db->GetOne("SELECT logintime FROM broker WHERE uid = '".$this->uid."'");
		return date('Ymd', $brokerlogintime);
	}
	

	/**
	* getBrokerLoginTimeByKind 根据登录类别获取最后登录时间
	*
	* @return str Ymd
	*/
	function getBrokerLoginTimeByKind($login_kind)
	{	
		if($login_kind =='plus_login'){
			$kind_cond  = " AND kind = 'brokercp' ";
		}elseif($kind =='plus_login_mobile'){
			$kind_cond  = " AND kind IN('android','iphone') ";
		}
		
		$sql = "SELECT logintime FROM log_login WHERE uid = '".$this->uid."' ".$kind_cond." ORDER BY logintime DESC LIMIT 1";
		$brokerlogintime = $this->db->GetOne($sql);

		return date('Ymd', $brokerlogintime);
	}


	/**
	* getBrokerBirthday 获取经纪人最后登录时间
	*
	* @return str Ymd
	*/
	function getBrokerBirthday()
	{
		$brokerbirthday = $this->db->GetOne("SELECT lc_time FROM log_credit WHERE lc_uid = '".$this->uid."' and lc_kind='plus_birthday' order by lc_id desc");
		return date('Ymd', $brokerbirthday);
	}

	/**
	* getBrokerCredit 获取经纪人积分
	*
	* @param bool $doview	//为TRUE时，返回最小为0
	* @return integer
	*/
	function getBrokerCredit($doview = false)
	{
		$brokercredit = $this->db->GetOne("SELECT credit FROM broker WHERE uid = '".$this->uid."'");
		$brokercredit = intval($brokercredit);

		$brokercredit = $doview === true && $brokercredit < 0 ? 0 : $brokercredit;

		return $brokercredit;
	}

	/**
	* addCreditLog 增加经纪人积分流水账表记录
	*
	* @param str $kind
	* @param int $credit
	*/
	function addCreditLog($kind, $credit)
	{
		$this->db->Execute("INSERT INTO log_credit (lc_uid, lc_kind, lc_value, lc_time) VALUES ('".$this->uid."','".$kind."','".$credit."','".$this->time."')");
	}

	/**
	* getCreditLogTotal 获取经纪人积分流水账记录总条数
	*
	* @param int $type  0:全部显示 1:筛除多图积分 2:只看多图积分
	* @param int $day
	* @return integer
	*/
	function getCreditLogTotal($type, $day = 30)
	{
		$day = intval($day) - 1;
		$startday = $day > 0 ? strtotime("-".$day." day") : strtotime(date('Y-m-d').' 00:00:00');

		$typesql = $type == 1 ? " AND lc_kind = 'plus_isstar' " : ($type == 2 ? " AND lc_kind != 'plus_isstar' " : "");

		$total = $this->db->GetOne("SELECT COUNT(*) FROM log_credit WHERE lc_uid = '".$this->uid."' ".$typesql." AND lc_time >= '".$startday."'");

		return intval($total);
	}

	/**
	* getCreditLog 获取经纪人积分流水账记录
	*
	* @param int $type  0:全部显示 1:筛除多图积分 2:只看多图积分
	* @param int $perpage
	* @param int $start
	* @param int $day
	* @return array
	*/
	function getCreditLog($type, $perpage = 20, $start = 0, $day = 30)
	{
		$perpage = intval($perpage);
		$start = intval($start);

		$day = intval($day) - 1;
		$startday = $day > 0 ? strtotime("-".$day." day") : strtotime(date('Y-m-d').' 00:00:00');

		$typesql = $type == 1 ? " AND lc_kind = 'plus_isstar' " : ($type == 2 ? " AND lc_kind != 'plus_isstar' " : "");

		$list = $this->db->GetAll("SELECT lc_kind,lc_value,lc_time FROM log_credit WHERE lc_uid = '".$this->uid."' ".$typesql." AND lc_time >= '".$startday."' ORDER BY lc_id DESC LIMIT ".$start.",".$perpage." ");

		$result = array();
		$i = 0;
		foreach($list as $row)
		{
			$result[$i]['time'] = $row['lc_time'];
			$result[$i]['kind'] = $this->credit_arr[$row['lc_kind']]['title'];
			$result[$i]['credit'] = $this->credit_arr[$row['lc_kind']]['sign'].$row['lc_value'];
			$i++;
		}
		return $result;
	}

	/**
	* updateCreditSettlement 更新经纪人积分月度结算表记录
	*
	* @param str $kind
	* @param bool $no_settlement
	* @return array
	*/
	function updateCreditSettlement($kind, $credit, $no_settlement)
	{
		$credit = intval($credit);
		$time = strtotime(date('Y-m', $this->time).'-1 00:00:00');

		$row = $this->db->GetRow("SELECT ls_id FROM log_credit_settlement WHERE ls_uid = '".$this->uid."' AND ls_time = '".$time."'");

		if($row)
		{
			if($no_settlement)
			{
				$sql = "UPDATE log_credit_settlement SET ls_credit = '".$this->brokercredit."' WHERE ls_id = '".$row['ls_id']."' ";
			}
			else
			{
				$sql = "UPDATE log_credit_settlement SET ls_credit = '".$this->brokercredit."', ls_".$kind." = ls_".$kind." + '".$credit."' WHERE ls_id = '".$row['ls_id']."' ";
			}
		}
		else
		{
			if($no_settlement)
			{
				$sql = "INSERT INTO log_credit_settlement (ls_uid, ls_time, ls_credit) VALUES ('".$this->uid."', '".$time."', '".$this->brokercredit."') ";
			}
			else
			{
				$sql = "INSERT INTO log_credit_settlement (ls_uid, ls_time, ls_credit, ls_".$kind.") VALUES ('".$this->uid."', '".$time."', '".$this->brokercredit."', '".$credit."') ";
			}
		}

		$this->db->Execute($sql);

		return $nowcredit;
	}

	/**
	* getCreditSettlementLog 获取经纪人积分月度结算表记录
	*
	* @param int $month
	* @return array
	*/
	function getCreditSettlementLog($month = 5)
	{
		$month = intval($month);
		$month = $month > 0 ? $month : 5;
		$starttime = strtotime("-".$month." month");

		$list = $this->db->GetAll("SELECT * FROM log_credit_settlement WHERE ls_uid = '".$this->uid."' AND ls_time >= '".$starttime."' ORDER BY ls_id DESC LIMIT 6 ");

		return $list;
	}
}
?>