<?php

namespace App\Jobs\Push;

use App\Modules\Push\Models\QappNewUserPushTask;
use App\Modules\SendOrder\Models\QappSendOrder;
use App\Modules\User\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Bus\Dispatchable;

/**
 * 新用户延时push消息推送队列
 */
class NewUserPushMsgDelay implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $uid;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(int $uid)
    {
        $this->uid = $uid;
    }

    private function findUserTasks()
    {
        $user = User::find($this->uid);
        if ($user) {
            $send_order_id = $user->send_order_id;
            $send_order = QappSendOrder::where('send_order_id', $send_order_id)->first();
            if ($send_order) {
                $account = $send_order->account;
                return QappNewUserPushTask::where('qapp_account', $account)
                    ->where('is_enabled', 1)
                    ->where('is_deleted', 0)
                    ->get();
            }
        }
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $tasks = $this->findUserTasks();
        if ($tasks) {
            foreach ($tasks as $task) {
                $job = new NewUserPushMsg($this->uid, $task);
                dispatch($job)->onConnection('rabbitmq')->onQueue('new_user_push_msg')->delay($task->time_delay);
                myLog('new_user_push_msg')->info("task_id:{$task->id}; uid: {$this->uid}");
            }
        }
    }
}
