<?php

namespace App\Jobs;

use App\Models\PartnerModel;
use App\Models\PraiseModel;
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 ThumbJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    private $uid;
    private $partner_id;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            sleep(5);
            // 点赞者
            $user = UserModel::findOrFail($this->uid);
            // 被点赞者
            $puser = UserModel::where('partner_id', $this->partner_id)->firstOrFail();

            // 被点赞者被点赞池
            $datas = Redis::zrange("fpdx:feed:thumb:{$puser->uid}", 0, -1);
            foreach ($datas as $data) {
                try {
                    // 点赞者卡片
                    $partner = PartnerModel::findOrFail($data);
                    $thumb = PraiseModel::where([
                        ['uid', $partner->uid],
                        ['partner_id', $puser->partner_id]
                    ])->firstOrFail();
                    $t = (time() - $thumb->created_at) / 3600 + 1;
                    $score = 100 * exp(floatval(-1 / ($partner->praises * $t + 1))) * 0.5;
                    Redis::zadd("fpdx:feed:thumb:{$puser->uid}", $score, $data);
                    Redis::expire("fpdx:feed:thumb:{$puser->uid}", 86400 * 30);
                } catch (\Exception $exception) {
                }
            }
            // 点赞者卡片
            $partner = PartnerModel::findOrFail($user->partner_id);
            $score = ceil(100 * exp(floatval(-1 / ($partner->praises + 1))) * 0.5);
            Redis::zadd("fpdx:feed:thumb:{$puser->uid}", $score, $user->partner_id);
            Redis::expire("fpdx:feed:thumb:{$puser->uid}", 86400 * 30);
        } catch (\Exception $exception) {
            app('sentry')->captureException($exception);
        }
    }
}
