<?php
$conf_basedir	= "../../";	//相对主目录的位置
$conf_where		= "admin";	//选择调用相应模块
$directory		= basename(dirname(__FILE__));	//定义当前所在的目录，引入模块公用函数
include_once($conf_basedir."base.inc.php");
//include_once WEB_MODULE . '/growth/base.inc.php';
checkAuth('10');	//判断登录和权限

$allow_act = array("surface", "sort0", "sort1", "sort2");
$act = in_array($act, $allow_act) ? $act : "surface";
$fitment = intval($fitment);

if(is_array($idarr) && !empty($idarr))
{
	$piccheck = new BrokerHousePicCheck();
	foreach($idarr as $id)
	{
		$oper = intval($operarr[$id]);

		if($oper == 2)	//冻结
		{
			$piccheck->freeze($id);
		}
		else if($oper == 1)	//删除
		{
			$piccheck->del($id);
		}
		else //通过
		{
			$piccheck->thaw($id,$act);
		}
	}
	
	//设置管理员审核房源数据操作数量记录
	$num = count($idarr);
	setCheckOpernum($act, array($act=>$num));
}

sleep(1);
echo "<script>window.location.href='./pic_manage.php?act=".$act."&fitment=".$fitment."'</script>";
exit;

//图片审核
class BrokerHousePicCheck
{
	private $systime = '';

	public function BrokerHousePicCheck()
	{
		$this->systime = time();
	}

	private function delPicFromCheckTable($id)
	{
		global $db;

		$sql = "delete from admin_pic_check where id = '".$id."'";
		$db->Execute($sql);
	}

	private function delPicFromUploadTable($tbl, $id)
	{
		global $db;

		$sql = "delete from ".$tbl." where id = '".$id."'";
		$db->Execute($sql);
	}

	private function freezePicFromUploadTable($tbl, $id)
	{
		global $db;

		$sql = "update $tbl set flg=3 where id = '".$id."'";
		$db->Execute($sql);
	}

	private function delSurfaceFromHouseTable($tbl, $id)
	{
		global $db;

		$sql = "update ".$tbl." set pic1 = '' where id = '".$id."'";
		$db->Execute($sql);
	}

	private function getInfoFromCheckTable($id)
	{
		global $dbback;

		$sql = "select * from admin_pic_check where id = '".$id."'";
		return $dbback->GetRow($sql);
	}

	private function getInfoFromHouseTable($tbl, $id)
	{
		global $dbback,$mc,$conf_cityflag;
		
		$memkey = $conf_cityflag."_getInfoFromHouseTable_".$tbl."_".$id;
		$cache = $mc->get($memkey);
		if($cache['isok'] == 1)
		{
			$return = $cache['data'];
		}
		else
		{
			$sql = "select * from ".$tbl." where id = '".$id."'";
			$return = $dbback->GetRow($sql);

			$mc->add($memkey, array('isok'=>1,'data'=>$return), false, 10);
		}
		return $return;
	}

	private function getBrokerInfo($uid)
	{
		global $dbback,$mc;

		$return = array();

		$memkey = "getBrokerInfo".$uid;
		$cache = $mc->get($memkey);
		if($cache['isok'] == 1)
		{
			$return = $cache['data'];
		}
		else
		{
			$sql = "select b.username, a.agentshortname, b.master from broker b left join agency a on b.agentcode = a.agentcode where b.uid = '".$uid."'";
			$return = $dbback->GetRow($sql);
			$mc->add($memkey, array('isok'=>1,'data'=>$return), false, 3600);
		}
		return $return;
	}

	private function add2Qa($info)
	{
		global $db,$web_auth;

		$randnum = rand(1, 50);

		if($randnum == 1)
		{
			$ss['uid'] = $info['uid'];
			$ss['housetbl'] = $info['housetbl'];
			$ss['houseid'] = $info['houseid'];
			$ss['fitment'] = $info['fitment'];
			$ss['infotype'] = $info['infotype'];
			$ss['pictbl'] = $info['pictbl'];
			$ss['picid'] = $info['picid'];
			$ss['picurl'] = $info['picurl'];
			$ss['sort'] = $info['sort'];
			$ss['surface'] = $info['surface'];
			$ss['dateline'] = $this->systime;
			$ss['admin'] = $_SESSION[$web_auth]["username"];
			
			$q = insert_sql("admin_pic_qa", $ss);
			$db->Execute($q);
		}
	}

	//审核成功图片加入小区待入图片
    private function addentry($info)
	{
		global $db,$dbback,$web_auth,$conf_cityflag;
		
		//获取房源信息
		$houseinfo[$info['houseid']] = getHouseInfoByTblId($info['housetbl'], $info['houseid']);

        //检查是否被锁定
        $q = "select count(*) as num from block_lock where blockid='" . $houseinfo[$info['houseid']]['blockid'] . "'";
        $array_lock = $dbback->GetRow($q);
        //var_dump($array_lock);exit;
        if($array_lock['num']<1)
        {
			$ss['blockid'] = $houseinfo[$info['houseid']]['blockid'];
			//判断是不是正式小区
			$q = "select esta from block where id='" . $ss['blockid'] . "'";
			$array_zs= $dbback->GetRow($q);
			$ss['blockname'] =$houseinfo[$info['houseid']]['blockshowname'];
			$ss['sort'] = $info['sort'];
			$ss['room'] = $houseinfo[$info['houseid']]['room'];
			$ss['hall'] = $houseinfo[$info['houseid']]['hall'];
			$ss['toilet'] = $houseinfo[$info['houseid']]['toilet'];
			$ss['pic_url'] = $info['picurl'];
			$arr = getimagesize(str_replace('thumb/','',$ss['pic_url']));
			$ss['dateline'] = $this->systime;
            $ss['houseid'] = $info['houseid'];
			$q = insert_sql("admin_pic_entry", $ss);

			if($ss['blockid']!=0 && !empty($ss['blockid']) && $arr[0]>=300 && $arr[1]>=300 && $array_zs['esta']==2)
			{
				$db->Execute($q);
			}
		}
	}
	
	//通过
	public function thaw($id,$act){
		$id = intval($id);
		$info = $this->getInfoFromCheckTable($id);//获取审图库中图片信息
		$this->delPicFromCheckTable($id);//从审图库删除图片
		if($info['uid'] <= 0)
		{
			return false;
		} 
        if($act=='sort0')
        {
        $this->addentry($info);//记录到小区备用库
        }
		$this->add2Qa($info);//记录到QA库
       
		$this->addLog2Picpasslog($info['file_md5'], $info['sort']);//记录到通过库做白名单用
	}

	//删除
	public function del($id){
		global $db,$dbback,$conf_cityflag,$config_GrowthCredit;
		
		$id = intval($id);
		$info = $this->getInfoFromCheckTable($id);//获取审图库中图片信息
		$this->delPicFromCheckTable($id);//从审图库删除图片
		if($info['uid'] <= 0)
		{
			return false;
		}
                
                
		//封面图删除操作
		if($info['surface'] == 1)
		{
			$this->delSurfaceFromHouseTable($info['housetbl'], $info['houseid']);
		}

		$this->photo_log($info['uid'], $info['housetbl'], $info['houseid'], $info['sort'], $info['fitment'], $info['surface'], $info['picurl'], 1, $info['file_md5']);//日志记录
		$this->delPicFromUploadTable($info['pictbl'], $info['picid']);//从图片库删除图片
               $reduceScoreMessage = '';
                if ($config_GrowthCredit == 1 && $conf_cityflag!='nj') {
                       $brokerGroup = new BrokerGroup();
                       $brokerInfo = $brokerGroup->getBrokerGroupInfo($info['uid']);        
                       $arrBroker = array(
                            'id' => $brokerInfo['uid'],
                            'groupid' => $brokerInfo['groupid'],
                       );
                       $gcwp = new GrowthCreditWayPackage();
	               $score = $gcwp->getScoreByWayAliasAndPackageId('delHousePic',$arrBroker['groupid']);
                       $gbc = new GrowthBrokerCredit($arrBroker);
                       $gbc->reduce('delHousePic', '', $score);
                       $reduceScoreMessage = "，已经扣除".$score."积分";
                                        
                }
                
		//发送冻结消息
		$row = $dbback->GetRow("select infofrom,agentcode,uid from ".$info['housetbl']." where id = '".$info['houseid']."'");
		$tablename=array ('sell'=>'出售', 'rent'=>'出租');
		$pictype = array('户型图','外景图','室内图');
		$bigpic = str_replace("/thumb","",$info['picurl']);

		
		if($info['surface'] == 1)
		{
			$subject = $tablename[$info['housetbl']]."房源编号".$info['houseid']."的封面图（".$pictype[$info['sort']]."）因违规已被删除，请您重新为房源设置合格的封面图。";
		}
		else
		{
			$subject = $tablename[$info['housetbl']]."房源编号".$info['houseid']."的一张".$pictype[$info['sort']]."违规被删除";
		}

		$msg = $tablename[$info['housetbl']]."房源编号".$info['houseid']."的一张".$pictype[$info['sort']]."违规被删除".$reduceScoreMessage.";<br /><a href='".$bigpic."' target='_blank'><img src='".$info['picurl']."' width='130' /></a>";

		$this->send_systemmsg($row,$subject,$msg);

		if($info['housetbl'] == 'sell')
		{
			$sql = "select count(*) from ".$info['pictbl']." where tbl='".$info['housetbl']."' and rowid='".$info['houseid']."' and sort=2";
			$num = $db->GetOne($sql);
			
			/*------------------------------------------*/	
			if($info['housetbl'] == 'sell' && $num < '3'){
				if($config_real == 1){//针对real房产品添加
					$db->Execute("update ".$info['housetbl']." set isreal=0,isstar=0,istag=0,grade=0 where id=".$info['houseid']." ");
					$db->Execute("update house_real set real_esta='9' where rowid=".$info['houseid']." and real_esta in(0,1) order by createtime desc limit 1");
				}
				else
				{
					$db->Execute("update ".$info['housetbl']." set isstar=0,istag=0,grade=0 where id=".$info['houseid']." ");
				}
			}else if($info['housetbl']=='rent'&&$num<'3'){
				$db->Execute("update ".$info['housetbl']."  set isstar=0,istag=0,grade=0 where id=".$info['houseid']." ");
			}
			/*------------------------------------------*/
		}
	}
	
	//冻结
	public function freeze($id){
		global $db;

		$id = intval($id);
		$info = $this->getInfoFromCheckTable($id);//获取审图库中图片信息
		$this->delPicFromCheckTable($id);//从审图库删除图片
		if($info['uid'] <= 0)
		{
			return false;
		}

		$this->freezePicFromUploadTable($info['pictbl'], $info['picid']);//修改图片库为冻结状态
		$this->photo_log($info['uid'], $info['housetbl'], $info['houseid'], $info['sort'], $info['fitment'], $info['surface'], $info['picurl'], 2, $info['file_md5']);//日志记录
		
		//获取房源信息，冻结房源
		$houseinfo = $this->getInfoFromHouseTable($info['housetbl'], $info['houseid']);
		if($houseinfo['esta'] == 1)
		{
			$this->add_freeze($info['housetbl'], $info['houseid']);
		}
	}

	//以下私有方法与housecp后台冻结规则同步方法(待测试)
	private function add_freeze($tbl,$rowid){
		global $db,$dbback,$web_auth,$config_BrokerCredit,$config_BrokerPunish,$config_real,$conf_cityflag,$config_GrowthCredit;
		$tablename=array ('sell'=>'出售', 'rent'=>'出租');

		$row = $dbback->GetRow("select infofrom,agentcode,uid from ".$tbl." where id = $rowid");

		if($row){
			$master = $dbback->GetOne("select master from broker where uid ='$row[uid]'");
			$agentcode = $dbback->GetOne("select agentcode from broker where uid ='$row[uid]'");

			$tt=array();
			$tt[tbl] = $tbl;
			$tt[rowid] = $rowid;
			$tt[agentcode] = $agentcode!=''?$agentcode:$row[agentcode];
			$tt[uid]    = $row[uid];
			$tt[master] = $master;
			$tt[reason] = "房源图片违规";
			$tt[remark] = "此信息由系统自动发出";
			$tt[freezetime] = time();
			$tt[esta] = 4;
			$tt[operator] = $_SESSION[$web_auth]["username"];

			//写入数据库
			$q=insert_sql('house_freeze',$tt);
			//echo $q;
			//exit();
			if($db->Execute($q))
			{

				//改变房源状态
				$r=$db->Execute("update $tbl set esta='5' where id=$rowid ");
		
				if($config_real == 1 && $tbl=='sell'){//针对real房产品添加
					$db->Execute("update house_real set real_esta='9' where rowid=$rowid and real_esta in(0,1) order by createtime desc  limit 1");
					$db->Execute("update $tbl set isreal='0' where id=$rowid ");
				}
                                $reduceScoreMessage = '';
                                if ($config_GrowthCredit == 1 && $conf_cityflag!='nj') {
                                        $brokerGroup = new BrokerGroup();
                                        $brokerInfo = $brokerGroup->getBrokerGroupInfo($row[uid]);        
                                        $arrBroker = array(
                                                 'id' => $brokerInfo['uid'],
                                                 'groupid' => $brokerInfo['groupid'],
                                              );
                                        $gcwp = new GrowthCreditWayPackage();
	                                $score = $gcwp->getScoreByWayAliasAndPackageId('frozenHouse',$arrBroker['groupid']);	                                	
                                        $gbc = new GrowthBrokerCredit($arrBroker);
                                        $gbc->reduce('frozenHouse', '',$score);
                                        $reduceScoreMessage = "，已经扣除".$score."积分";
                                   }
                           
				
				if($config_BrokerCredit == 1)
				{
					if($conf_cityflag == 'nj')
					{
						//经纪人房源冻结扣积分
						include_once(CORE_LIB . "/class_brokercredit_nj.php");                                                
					}                                        
					else
					{
						//经纪人房源冻结扣积分
						include_once(CORE_LIB . "/class_brokercredit.php");
                                               
					}
                                        $I = new BrokerCredit($row['uid']);
			                $I->dealCredit('minus_frozen');
			
				}

				//更新惩罚状态
				$this->update_user_freeze($row['agentcode'],$row['uid']);


				if($config_BrokerPunish == 1)
				{
					//经纪人诚信记录
					include_once(CORE_LIB . "/brokerpunish.class.php");
					$B = new BrokerPunish($row['uid']);
					$B->addViolationRecords($tbl,$rowid,2,$_SESSION[$web_auth]["username"],"审核图片冻结");
				}

				//发送冻结消息
				$subject = $tablename[$tbl]."房源".$rowid;
				$msg = $tablename[$tbl]."房源编号".$rowid."的房源目前已被冻结,冻结原因：".$tt[reason].$reduceScoreMessage;
				$this->send_systemmsg($row,$subject,$msg);
			}
		}
	}

	private function send_systemmsg($row,$subject,$msg)
	{
		global $db;

		$ss=array();
		$ss[kind] = "system";
		$ss[subject] ="【系统信息】".$subject;
		$ss[message] = $msg;
		$ss[operator] = "system";
		$ss[creattime] = time();
		$ss[issystem] = 1;

		$q=insert_sql("agent_announce",$ss);
		$db->Execute($q);
		$newid=$db->Insert_ID();//自增的用法

		$ss=array();
		$ss[announceid]=$newid;
		if($row[infofrom] == '2') 	{ $ss[agentcode] = $row[agentcode]; }
		if($row[infofrom] == '5') 	{ $ss[agentcode] = 'B000'; }
		$ss['uid']=$row[uid];
		$ss["new"] = 1;

		//写入数据库
		$q=insert_sql("agent_announceitem" ,$ss);
		//echo $q;
		//exit();
		$db->Execute($q);

	}

	//更新agency或者broker处罚状态
	private function update_user_freeze($agentcode,$uid){
		global $db,$config_xqzj;
		if($agentcode != "B000") return;
		$tbl ="broker";
		$month = mktime(0,0,0,date("m"),1, date("Y"));
		$nextmonth = mktime(0,0,0,date("m")+1,1, date("Y"));

		$total = $db->GetOne("select count(*) from house_freeze where agentcode='B000' and uid=$uid and freezetime>$month and freezetime<$nextmonth and esta != 3");
		if($total>=30){
			$db->Execute("update $tbl set festa=1 where uid=$uid and festa=0");
		}
		else if($total>=3 && $config_xqzj == 1){
			$sql = "select id from block_apply where uid=$uid and esta=1";
			if($db->GetOne($sql)){
				$sql = "select apptime from block_apply where uid=".$uid." and esta=1";
				$apptime=$db->GetOne($sql);
				$sql="update block_apply set esta=".$esta." where uid=".$uid." and esta=1";
				$db->Execute($sql);
				$sql="update block_apply_data set uptime=".time()." where uid=".intval($uid)." and apptime='$apptime'";
				$db->Execute($sql);
			}
		}
	}

	//记录日志
	private function photo_log($uid, $tbl, $id, $sort, $fitment, $surface, $info, $oper, $file_md5){
		global $db,$web_auth;
		
		$uid = intval($uid);
		$binfo = $this->getBrokerInfo($uid);
		$arr['username'] = $binfo['username'];
		$arr['agentname'] = $binfo['agentshortname'];
		$arr['master'] = $binfo['master'];
		$arr['housetbl'] = $tbl;
		$arr['houseid'] = $id;
		$arr['sort'] = $sort;
		$arr['fitment'] = $fitment;
                $arr['surface'] = $surface;
		$arr['info'] = $info;
		$arr['oper'] = $oper;
		$arr['admin'] = $_SESSION[$web_auth]["username"];
		$arr['dateline'] = time();
		$arr['file_md5'] = $file_md5;
		$q = insert_sql("admin_house_check_log",$arr);
		$db->Execute($q);
	}

	//记录日志
	private function addLog2Picpasslog($file_md5, $pic_sort){
		global $db,$conf_cityflag;
		
		if($file_md5 != "")
		{
			$arr['file_md5'] = $file_md5;
			$arr['pic_sort'] = $pic_sort;
			$arr['dateline'] = $this->systime;
			$q = insert_sql("admin_pic_pass_log",$arr);
			$db->Execute($q);
		}
	}
}
?>