<?php

namespace App\Modules\User\Models;

use Illuminate\Database\Eloquent\Model;

class SmartPushUserSign extends Model
{
    protected $table = 'smart_push_user_sign';
    protected $fillable = ['uid','price','day','sign_time'];

    /**
     * 用户是否已签到
     * @param $uid
     * @param $day
     * @return mixed
     */
    public static function isSign($uid,$day){
        return self::where('uid',$uid)->where('day',$day)->first();
    }
    
    /**
     * 删除N天前的数据，保留热数据
     */
    static function deleteSmartPushUserSignByTime($end_time)
    {
        $max_id = self::where('day','<=',$end_time)->max('id');
        $min_id = self::where('day','<=',$end_time)->min('id');
        if($max_id)
        {
            while (true)
            {
                $t_max_id = min($min_id + 50000, $max_id);
                $affect_rows = self::where('id','>=',$min_id)->where('id','<=',$t_max_id)->delete();

                $min_id = $t_max_id;

                if(!$affect_rows) break;
                sleep(1);
            }
        }
    	return true;
    }

    /**
     * 签到
     * @param $uid
     * @param $day
     * @return mixed
     */
    public static function sign($uid,$day,$fee){
        $data = ['uid'=>$uid,'price'=>$fee,'day'=>$day,'sign_time'=>time()];
        return self::create($data);
    }

    /**
     * 用户签到记录
     */
    public static function getUserSignRecord($uid){
        return self::where('uid',$uid)->select('price','sign_time')->orderBy('sign_time','desc')->paginate();
    }
}
