<?php
/**
 *租售宝经纪人积分类 BrokerCredit
 *Fisher 2012-1-29
 * xz  update 2012-7-13
**/

class BrokerCredit
{
	var $uid;			//经纪人UID
	var $db;			//数据库
	var $credit_arr;	//经纪人积分规则数组
	var $esta_Module;	//模块是否生效

	//不计入月度流水的操作
	var $no_settlement = array('plus_open', 'plus_identity', 'plus_card','plus_smallphoto','plus_locCertificate','plus_pubCertificate');
	var $allow_lesszero_arr = array('minus_frozen');//允许操作积分使其小于0的操作
	var $time = 0;			//操作时间
	var $brokercredit = 0;	//经纪人当前积分
	var $groupid = 0;		//经纪人权限组
	var $ispay = 0;			//经纪是否付费

	/**
	* BrokerCredit 构造方法
	*
	* @param int $uid
	*/
	function BrokerCredit($uid)
	{
		global $db,$credit_arr,$config_BrokerCredit;

		$this->uid = $uid;
		$this->db = $db;
		$credit_arr['plus_open']['redit'] = $this->getBrokerOpenCredit();
		$this->credit_arr =  $credit_arr;
		$this->esta_Module = $config_BrokerCredit;
		$this->time = time();
		$this->groupid = $this->getBrokerGroupid();
		$this->ispay =  $this->getBrokerPay();
	}

	/**
	* dealCredit 操作经纪人积分，所有积分操作调用此方法
	*
	* @param str $kind
	* @param arr $params  op_credit,operator,reason/rowid,tbl
	* @return bool
	*/
	function dealCredit($kind, $params = array())
	{
		//积分模块是否生效，不生效直接返回false
		if( !($this->esta_Module) || empty($this->esta_Module)  ){
			return false;
		}

		//付费经纪人的有效的积分操作
		if( ( $this->ispay==0 && isset($this->credit_arr[$kind]) ))
		{

			//初始化操作分数
			$credit = $this->credit_arr[$kind]['credit'];
			//取经纪人套餐积分上限数据
			$package = $this->getBrokerPackageInfo();
			switch($kind)
			{
				//经纪人登录加分
				case 'plus_login' :		$brokerlogintime = $this->getBrokerLoginTime();	//获取经纪人最后登录时间
										$credit = date('Ymd') != $brokerlogintime ? $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' :
										$dayisstarcredit = $this->getDayIsstarCredit();//当日已加多图积分数
										//当日的多图房源积分超限
										if($dayisstarcredit >= $package['isstar_credit_limit_day']){
											$credit_day = 0;
										}else{
											//加分超限时只增加超限时的分数
											$tempcredit = $package['isstar_credit_limit_day'] - $dayisstarcredit;
											$credit_day = $tempcredit > $credit ? $credit : $tempcredit;
										}

										$monthisstarcredit = $this->getMonthIsstarCredit();//当月已加多图积分数
										//本月的多图房源积分超限
										if($monthisstarcredit >= $package['isstar_credit_upper_limit']){
											$credit_month = 0;
										}else{
											//加分超限时只增加超限时的分数
											$tempcredit = $package['isstar_credit_upper_limit'] - $monthisstarcredit;
											$credit_month = $tempcredit > $credit ? $credit : $tempcredit;
										}
										//判断两个中的最小的一个
										$credit = $credit_month >= $credit_day ? $credit_day : $credit_month;
										break;

				//此类操作终生只能加分一次
				case 'plus_open' :		$check = $this->getCreditLogByKind($kind);
										$credit = $check > 0 ? 0 : $package[$kind];//经纪人开账号积分和权限组绑定
										break;
				case 'plus_identity' :
				case 'plus_smallphoto' :
				case 'plus_localCertificate' :
				case 'plus_publicCertificate' :
				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'];
					}
				}else{		//减分操作情况下经纪人积分可被减为负分，只是前台显示0分
					$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;
		$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);
	}

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


	/**
	* getBrokerPay 获取经纪人是否付费
	*
	* @return integer
	*/
	function getBrokerPay()
	{
		$ispay = $this->db->GetOne("select is_pay from broker where uid='".$this->uid."'");
		return intval($ispay);
	}

	/**
	* 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 ls_plus_isstar FROM log_credit_settlement WHERE ls_uid = '".$this->uid."' AND ls_time = '".$time."'");

		return intval($sum);
	}


	/**
	* getDayIsstarCredit 获取经纪人当日发布多图获得的积分数
	*
	* @return integer
	*/
	function getDayIsstarCredit()
	{
		$starttime = strtotime(date('Y-m-d', $this->time).'00:00:00');
		$endtime = $this->time;
		$sql = "SELECT COUNT(*) FROM log_credit WHERE lc_uid = ".$this->uid." AND "
				."lc_kind = 'plus_isstar' AND lc_time BETWEEN ".$starttime." AND ".$endtime." ";
		$sum = $this->db->GetOne($sql);
		$sum = $sum*($this->credit_arr['plus_isstar']['credit']);
		return intval($sum);
	}

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


	/**
	* getBrokerPackageInfo 获取经纪人开通账号赠送积分
	*
	* @return int
	*/
	function getBrokerOpenCredit()
	{
		$sql = "SELECT 	bg.plus_open FROM broker_group bg LEFT JOIN broker b ON bg.id = b.groupid WHERE b.uid = '".$this->uid."'";
		$credit =  $this->db->GetOne($sql);
		return intval($credit);
	}

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

	/**
	* getBrokerCredit 获取经纪人积分
	*
	* @param bool $doview	//为TRUE时，返回最小为0
	* @return integer
	*/
	function getBrokerCredit($doview = false)
	{
		//积分模块是否生效，不生效直接返回0
		if( !($this->esta_Module) || empty($this->esta_Module)  ){
			return 0;
		}
		$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' " : "");
		$sql = "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." ";

		$list = $this->db->GetAll($sql);

		$result = array();
		$i = 0;

		if(!empty($list)){
			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_time DESC LIMIT 6 ");

		return $list;
	}
}
?>