<?php 
defined('G_IN_SYSTEM')or exit('No permission resources.');
System::load_app_class('base','member','no');
System::load_app_fun('my','go');
System::load_app_fun('user','go');
class index extends SystemAction {
	
	public function __construct(){
		$this->db=System::load_sys_class("model");
		
	}
	
	public function lingqu(){		
		$id=$_REQUEST['id'];
		$re=$this->db->getone("select * from @#_hongbao where id=$id and status=0");
		if($re){
		    $this->db->query("update @#_hongbao set status=1 where id=$id");
	    	$this->db->query("update @#_member set money=money+".$re['jine']." where uid=".$re['uid']);
			$this->db->query("insert into @#_member_account(`uid`,`type`,`pay`,`content`,`money`,`time`) values(".$re['uid'].",1,'账户','领取红包',".$re['jine'].",".time().")");
		}
		header('Content-Type:application/json; charset=utf-8');
        exit(json_encode($re));
	}
	
	
	public function fafang(){
		$cishu=$this->db->getone("select value from @#_config where name='hongbao_cishu'");
		$cishu=$cishu['value'];
		#首先检出购买过num次且未发放红包的用户
		$re=$this->db->GetList("select uid from @#_member_go_record where hongbao=0 and UNIX_TIMESTAMP()-time>1200  GROUP BY uid HAVING count(id)>=".$cishu." ORDER BY count(id) desc");
		$user=array();
		foreach ($re as $k => $v) {
			//找出最近10次购买记录中奖号码和
			$huode=$this->db->getone("select sum(huode) as huode from @#_member_go_record where uid=".$v['uid']." order by id desc limit 0,10");
			//排除已中奖名单  $huode['huode']<10000000
			if($huode['huode']<10000000){
				array_push($user,$v['uid']);
			}
		}
		foreach ($user as $k => $v) {
			//获取平均购买金额
			$jine=$this->db->getone("select FLOOR(avg(moneycount)) as jine from (select * from @#_member_go_record where uid=$v and hongbao=0  order by id desc limit 0,2) as a");
			$jine=$jine['jine'];
			$jine=floor($jine*0.2);
			if($jine==0){
			    $jine=1;
			}else{
				$jine=rand(1, $jine);
			}
			$num=$this->db->getone("select value from @#_config where name='hongbao_num'");
			$num=$num['value'];
			if($num>0){
			    $this->db->query("update @#_config set value=value-1 where name='hongbao_num'");
				//发放红包记录
				$this->db->query("insert into @#_hongbao(uid,jine,ctime) values($v,$jine,".time().")");
				//更新红包发放状态
				$this->db->query("update @#_member_go_record set hongbao=1 where uid=$v");
			}
		}
	}


}
?>