<?php

namespace App\Jobs;

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

class PartnerCommitJob 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 = PartnerBeauty::find($id);
    }


    protected $partner;


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


        DB::transaction(function () use ($beauty_partner) {

            $partner = PartnerModel::find($beauty_partner->partner_id);

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


                $beauty_partner->submitted_at = time();
                $beauty_partner->save();

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

                PartnerBeautyUser::updateOrCreate(
                    ['partner_id' => $beauty_partner->partner_id, 'field' => $beauty_partner->field],
                    [
                        'uid' => $beauty_partner->uid,
                        'partner_id' => $beauty_partner->partner_id,
                        'field' => $beauty_partner->field,
                        'original_photo' => $beauty_partner->original_photo,
                        'new_photo' => $beauty_partner->new_photo,
                        'replaced_at' => time()
                    ]
                );
            } else {
                $beauty_partner->delete();
            }
        });
    }
}
