<?php


namespace App\Models;


use App\Http\Filters\QueryFilter;
use App\Tasks\IntegralBillTask;
use Common\Model\RedisModel;
use Carbon\Carbon;
use Hhxsv5\LaravelS\Swoole\Task\Task;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CheckIn extends Model
{
    protected $table = 'check_in';
    public $timestamps = false;

    public function scopePage($query, $page = 1, $pageSize = 10)
    {
        return $query->offset(($page - 1) * $pageSize)->limit($pageSize);
    }

    public function scopeFilter($query, QueryFilter $filters)
    {
        return $filters->apply($query);
    }

    //获取签到记录
    public function getCheckInList($page, $pageSize, $filter)
    {
        $checkIns = CheckIn::filter($filter)->page($page, $pageSize)
            ->orderBy('id', 'desc')->get()->toArray();
        $count = CheckIn::filter($filter)->count();

        return ['data' => $checkIns, 'count' => $count];
    }

    //添加签到记录
    public function addCheckIn($data)
    {
        $result = DB::transaction(function () use ($data) {
            $result = DB::table('check_in')->insert($data);
            if (!$result) {
                return false;
            }
            //使用异步任务去添加流水
            $data['integral_id'] = Integral::INTEGRAL_TYPE_CHECK_IN;
            $task = new IntegralBillTask($data);
            $result = Task::deliver($task);
            if (!$result) {
                return false;
            }
            //添加流水成功后,要把签到记录放到redis
            $date = Carbon::now()->toDateString();
            $hashKey = 'ic_welfare_integral_limit_' . Integral::INTEGRAL_TYPE_CHECK_IN;
            $userId = $data['user_id'];
            $redis = new RedisModel();
            $redis->hincrby($hashKey, $userId, 1);

            return true;
        });

        return $result;
    }

    //判断是否可以签到
    public function canCheckInFromRedis($userId)
    {
        $redis = new RedisModel();

        //先判断 ic_welfare_check_in_日期 在不在,不在的话就添加一个并且给过期时间
        $date = Carbon::now()->toDateString();
        $hashKey = 'ic_welfare_check_in_' . $date;
        $exist = $redis->exists($hashKey);
        if (!$exist) {
            //设置晚上12点过期
            $todayEndTime = Carbon::now()->endOfDay()->timestamp;
            $redis->expireAt($hashKey, $todayEndTime);

            //因为连最基础的键都没有,就代表肯定没有签到过
            return true;
        }

        //如果没有,就代表用户今天没有签到
        $checkInTime = $redis->hget($hashKey, $userId);
        if (!$checkInTime) {
            //因为他今天没有签到过,所以本次签到是可以执行的
            return true;
        }

        return false;
    }
}