<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2020/2/4
 * Time: 12:47
 */

namespace app\common\command;

use app\common\model\Article;
use file\FileHelper;
use file\PathHelper;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use time\Timestamp;

class ArticleImgPersistence extends Command
{
    /**
     * 文章网络图片本地化
     * php think ArticleImgPersistence
     */
    protected function configure()
    {
        $this->setName('ArticleImgPersistence')
            ->setDescription('article image save to local');
    }

    protected function execute(Input $input, Output $output)
    {
        $articles = (new Article())->where(['content' => ['like', '%http%']])->order('id desc')->select();
        $savePath = DS . 'uploads' . DS . 'admin' . DS . 'attachment' . DS . Timestamp::dayStart(time()) . DS;
        $count = 0;
        foreach ($articles as $article) {
            $output->writeln('article id = ' . $article->id);
            $imgs = matchImg($article->content);
            foreach ($imgs as $img) {
                if (ifContain($img, 'http://') || ifContain($img, 'https://')) {
                    $saveName = PathHelper::getFilename($img);
                    $output->writeln($img . '   =========>>>>>>    ' . $savePath . $saveName);
                    FileHelper::fetchDownFile($img, ROOT_PATH . 'public' . $savePath, $saveName);
                    $data = [
                        'module' => '',//模块
                        'use' => 'articleImgPersistence',//来源
                        'filename' => $saveName,//文件名
                        'filepath' => $savePath . $saveName,//文件路径
                        'fileext' => PathHelper::getExt($img),//文件后缀
                        'filesize' => 0,//文件大小
                        'create_time' => time(),//时间
                        'uploadip' => '',//IP
                        'user_id' => 0,
                        'status' => \app\common\model\Attachment::STATUS_OPEN,
                        'admin_id' => 0,
                        'audit_time' => 0,
                    ];
                    Db::name('attachment')->insertGetId($data);
                    $article->save(['content' => str_replace($img, replaceUrlDS($savePath . $saveName), $article->content)]);
                    $count++;
                }
            }
        }
        $output->writeln('finish , save image ' . $count);
    }
}