<?php

declare(strict_types=1);

namespace App\Command;

use App\Helpers\AppHelper;
use App\Model\AppArticle;
use Hyperf\Collection\Collection;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\DbConnection\Db;
use Psr\Container\ContainerInterface;
use function Hyperf\Coroutine\co;

#[Command]
class CoverCommand extends HyperfCommand
{

    protected $reids;
    public function __construct(protected ContainerInterface $container)
    {
        parent::__construct('demo:cover');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('Hyperf Demo Command');
    }

    public function handle()
    {
        $this->line('Hello Hyperf!', 'info');

        Db::table('app_articles')->where('id', '>', 11284)->orderBy('id')->chunk(20, function (Collection $item) {
            $waitGroup = new \Hyperf\Coroutine\WaitGroup();
            foreach ($item as $v) {;
                if (!$v || $v->cover) {
                    if ($v->year) {
                        continue;
                    }
                }
                $waitGroup->add();
                co(function () use ($waitGroup, $v) {
                    $cover = json_decode($v->images, true);
                    $v->cover = current($cover)['src'];

                    $model = AppArticle::find($v->id);
                    if ($model) {
                        $model->cover = current($cover)['src'];
                        preg_match('/([0-9]+)/', $model->title, $y);

                        $model->year = $y[1] ?? 0;
                        echo "update {$v->id} year: {$model->year} effect: {$model->update()}" . PHP_EOL;
                    }

                    $waitGroup->done();
                });
            }

            $waitGroup->wait();
        });


//        var_dump(file_get_contents('https://www.vogue.com/fashion-shows/designer/AFKIR'));
    }
}
