<?php

namespace App\Jobs;

use App\Models\PartnerModel;
use App\Models\User\UserModel;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Redis;

class FeedRecommendJob 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()
    {
        $uid = $this->uid;
        try {
            if (Redis::exists("{fpdx:feed:recommend:{$uid}}")) {
                return;
            }
            $user = UserModel::findOrFail($uid);
            $hideList = Redis::zrange("charge_feed_{$user->uid}", 0, -1);
            empty($hideList) && $hideList = array();
            $last_login = time() - 86000 * 2;
            // 获取精选卡片用户
            $where = array(
                ['sex', $user->feed_sex],
                ['is_recommend', 1],
                ['is_sell', 1],
                ['is_push_feed', 1],
                ['score', '>', 0],
                ['login_at', '>', $last_login]
            );
            $partners = PartnerModel::where($where)->whereNotIn('id', $hideList)->get();
            $recommenduids = collect($partners)->pluck('uid')->toArray();

            $uids = $recommenduids;
            // 用户按距离排序
            if ($user->feed_sex == 1) {
                $key = "fpdx:user:locations:sell:boy";
            } else {
                $key = "fpdx:user:locations:sell:girl";
            }
            $redis_uids = Redis::geoRadius($key, $user->lng, $user->lat, 500, "km", array('ASC'));
            $whereuids = array_slice(array_intersect($redis_uids, $uids), 0, 100);
            // 获取uid-卡片id集合
            $p2uids = PartnerModel::whereIn('uid', $whereuids)->get(['id', 'uid']);
            $uid2ids = array();
            array_map(function ($value) use (&$uid2ids) {
                $uid2ids[$value['uid']] = $value['id'];
            }, collect($p2uids)->toArray());
            array_map(function ($value) use ($uid2ids, $uid) {
                Redis::rpush("{fpdx:feed:recommend:{$uid}}", $uid2ids[$value]);
            }, $whereuids);
            Redis::expire("{fpdx:feed:recommend:{$uid}}", mktime(0, 0, 0) + 86000 - time());
        } catch (\Exception $exception) {
            app('sentry')->captureException($exception);
            Redis::hset("session_msy_{$uid}", "init_recommend_queues", 0);
        }
    }
}
