<?php

namespace app\command;

use app\model\Goods;
use Intervention\Image\Gd\Driver;
use Intervention\Image\ImageManager;
use Intervention\Image\ImageManagerStatic;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Tinywan\Storage\Exception\StorageException;


class GoodsThumbCommand extends Command
{
    protected static $defaultName = 'GoodsThumbCommand';
    protected static $defaultDescription = 'GoodsThumbCommand';

    /**
     * @return void
     */
    protected function configure()
    {
        $this->addArgument('name', InputArgument::OPTIONAL, '商品主图片批量缩略');
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $goods = Goods::select('goods_id','goods_cover')->limit(10)->get()->toArray();

        foreach ($goods as $good){
            if (!file_exists(public_path($good['goods_cover']))){
                echo "【".$good['goods_id']."】源文件不存在,跳过 \n";
                continue;
            }
            $fileNameArray = explode(DIRECTORY_SEPARATOR,$good['goods_cover']);
            $two = $fileNameArray[count($fileNameArray)-2];
            if ($two == 'thumb'){
                echo "【".$good['goods_id']."】已存在,跳过 \n";
                continue;
            }
            array_splice($fileNameArray,-1,0,'thumb');

            $thumbPath = public_path(ltrim(implode(DIRECTORY_SEPARATOR,$fileNameArray),DIRECTORY_SEPARATOR));
            if (file_exists($thumbPath)){
                echo "【".$good['goods_id']."】缩略图已存在,跳过 \n";
                continue;
            }
            $path = array_slice($fileNameArray,0,-1);
            $pathStr = public_path(ltrim(implode(DIRECTORY_SEPARATOR,$path),DIRECTORY_SEPARATOR));

            if (!is_dir($pathStr) && !mkdir($pathStr, 0755, true)){
                throw new StorageException('文件夹创建失败,请核查是否有对应权限。');
            }

            $image = ImageManagerStatic::make(public_path($good['goods_cover']));

            $imgWidth = $image->width();
            $imgHeight = $image->height();
            $rate = round($imgWidth / 200, 2);
            $height = intval($imgHeight / $rate);
            $image = $image->resize(200, $height);
            $encoded = $image->encode('jpg');
            $encoded->save($thumbPath);

            Goods::where('goods_id',$good['goods_id'])->update(['goods_cover'=>implode(DIRECTORY_SEPARATOR,$fileNameArray)]);

            echo "【".$good['goods_id']."】已完成 \n";
        }



        return self::SUCCESS;
    }

}