<?php

namespace App\Jobs;

use App\Jobs\GrowingIO\FeedMockReportJob;
use App\Models\Log\FeedLogModel;
use App\Models\PartnerModel;
use App\Models\User\UserModel;
use Illuminate\Bus\Queueable;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Redis;

/**
 * feed流mock数据
 * Class FeedMockPushJob
 * @package App\Jobs
 */
class FeedMockPushJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    private $uid;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $user = UserModel::findOrFail($this->uid);
        /** @var UserModel $user */

        // 滑动的性别
        if (in_array($user->feed_sex, [1, 2])) {
            $sxo = $user->feed_sex;
        } else {
            $sxo = 2;
        }

        $partner_id = Redis::lpop("feed:mock:sex:{$sxo}");
        if ($partner_id) {
            $partner = PartnerModel::whereId($partner_id)->orderBy('last_three_day_feed', 'ASC')->first([
                'id',
                'last_three_day_feed'
            ]);
        } else {
            if (Redis::exists("feed:mock:lock:{$sxo}")) {
                $partner = null;
            } else {
                $partners = PartnerModel::where([['is_sell', 1], ['sex', $sxo]])->orderBy(
                    'last_three_day_feed',
                    'ASC'
                )->take(500)->get(['id', 'last_three_day_feed']);
                $partner = $partners->pop();
                foreach ($partners as $value) {
                    /** @var PartnerModel $value */
                    Redis::rpush("feed:mock:sex:{$sxo}", [$value->id]);
                }
            }
        }
        if ($partner) {
            FeedLogModel::create([
                'uid' => $this->uid,
                'partner_id' => $partner->id,
                'ismock' => 1
            ]);
            FeedMockReportJob::dispatch($this->uid, $partner->id, $partner->last_three_day_feed);
        } else {
            Redis::setex("feed:mock:lock:{$sxo}", 3600 * 5, true);
        }
    }
}
