<?php

namespace App\Jobs;

use App\Models\Partner\PartnerBeautyUser;
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\DB;

class PartnerCallbackJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /**
     * 任务最大尝试次数。
     *
     * @var int
     */
    public $tries = 1;


    /**
     * 任务运行的超时时间。
     *
     * @var int
     */
    public $timeout = 120;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($id)
    {
        $this->partner = PartnerBeautyUser::find($id);
    }


    protected $partner;

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $beauty_partner = $this->partner;

        if (
            $beauty_partner
            && $beauty_partner->original_photo
            && $beauty_partner->new_photo
            && $beauty_partner->replaced_at > 0
            && $beauty_partner->callback_at == 0
        ) {
            DB::transaction(function () use ($beauty_partner) {

                $partner = PartnerModel::find($beauty_partner->partner_id);
                if ($partner->{$beauty_partner->field} == $beauty_partner->new_photo) {
                    $partner->{$beauty_partner->field} = $beauty_partner->original_photo;
                    $partner->save();

                    $user = UserModel::find($beauty_partner->uid);
                    $user->{$beauty_partner->field} = $beauty_partner->original_photo;
                    $user->save();

                    $beauty_partner->callback_at = time();
                    $beauty_partner->save();
                }
            });
        }
    }
}
