红包雨

/**

  • 活动红包
  • @ApiWeigh (998)
    */
class RedPacket extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /**
     * 活动红包
     * @ApiMethod   (post)
     * @ApiReturn    ({"code":1,"msg":"返回成功"})
     * @ApiReturnParams (name="num", type="string", required=true,description="抢到钱数")
     */
    public function red_packet()
    {
        $user = $this->auth->getUser();
        $week = date('w');
         $this->error('活动暂未开启',$week);
        if ($week != 6 && $week !=0){
            $this->error('活动暂未开启',$week);
        }

        $total_money = Db::name('config_tiandi')->where('id',4)->value('value');//总金额
        $balance = Db::name('red_log')->where('date',strtotime(date('Y-m-d',time())))->sum('money');//已抢金额
        $red_num = Db::name('config_tiandi')->where('id',5)->value('value');//红包个数
        $count = Db::name('red_log')->where('date',strtotime(date('Y-m-d',time())))->count();//抢到的数量
        $min=0.1;//最小值
        $i = $red_num - $count;//剩余红包
        if ($total_money==$balance){
            $this->error('红包已被抢完');
        }
        if ($i == 0){
            $this->error('很遗憾,红包已被抢完');
        }
        if ($i == 1){
            $rand_num = $total_money - $balance;//最后一个人获得剩下的所有
        }else{
            $count = $count+1;
            $safe_total = (($total_money - $balance)-($red_num-$count)*$min)/($red_num-$count);//随机安全上限
            $rand_num = mt_rand($min*100,$safe_total*100)/100;
        }
        $red_log = [
            'user_id'=>$user['id'],
            'money'  =>$rand_num,
            'create_time'   =>time(),
            'date'=>strtotime(date('Y-m-d',time()))
        ];
        $info = Db::name('red_log')->where('user_id',$user['id'])->where('date',strtotime(date('Y-m-d',time())))->find();
        if ($info){
            $this->error('您今天已经抢过啦');
        }
        Db::startTrans();
        try {
            Db::name('red_log')->insert($red_log);
            //增加余额
            Db::name('user')->where('id',$user['id'])->setInc('money',$rand_num);
            //记录日志
            $money_log = [
                'user_id'=>$user['id'],
                'number'=>$rand_num,
                'before'=>$user['money'],
                'after' =>$user['money'] + $rand_num,
                'type'  =>'red_01',
                'create_time'=>time()
            ];
            Db::name('money_log')->insert($money_log);
            Db::commit();
            return json(['code' => 1, 'msg' => '抢成功','data'=>$rand_num]);
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

    }

你可能感兴趣的:(红包雨)