<?php

namespace App\Jobs;

use App\Models\Partner\PartnerBeauty;
use GuzzleHttp\Client;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class PartnerBeautifyJob 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()
    {
        $imageUrl = "https://oss.pocketuniversity.cn" . $this->partner->original_photo;
        $content = $this->getMeiTuImage($imageUrl);
        if ($content) {
            $base64 = $content['media_info_list'][0]['media_data'];
            $content = base64_decode($base64);
            $new_avatar = sprintf("/imgs/%s/%s.png", date('Y-m-d'), \Ramsey\Uuid\Uuid::uuid4()->toString());

            \Storage::disk('oss')->put($new_avatar, $content);

            $this->is_beauty = 2;
            $this->partner->new_photo = $new_avatar;
            $this->partner->save();
        }
    }


    protected $appId = '931';
    protected $appKey = 'X5Q5H48jGwHb6Fphq5ErWMGl0Dk1AfXC';
    protected $secretId = 'jBc8Y_5f9O9RcMRqGLHRi7BLhwTrqWp_';

    protected $aiBeautyUrl = 'https://openapi.mtlab.meitu.com/v2/AIBeauty';
    protected $hdrUrl = 'https://openapi.mtlab.meitu.com/v1/hdr';
    protected $aiDenoiseUrl = 'https://openapi.mtlab.meitu.com/v1/AIDenoise';
    protected $makeUpUrl = 'https://openapi.mtlab.meitu.com/v3/makeup';

    protected $client;


    public function getMeiTuImage($url)
    {
        $data = [
            'query' => [
                'api_key' => $this->appKey,
                'api_secret' => $this->secretId,
            ],
            'json' => [
                'parameter' => [
                    'rsp_media_type' => 'base64',
                    'outputType' => 0,
                    'nModes' => 1,
                ],
                'media_info_list' => [
                    [
                        'media_data' => $url,
                        'media_profiles' => [
                            'media_data_type' => 'url'
                        ],
                    ]
                ],
            ]
        ];

        $this->client = new Client();
        $response = $this->client->post($this->aiBeautyUrl, $data);

        if ($response->getStatusCode() == 200) {
            $content = $response->getBody()->getContents();
            return json_decode($content, true);
        }
    }
}
