<?php

namespace App\Console\Commands;

use App\Models\DrugReportInfo;
use App\Services\SyncDrugReportService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class UpdateTaskCommand extends Command
{
    protected $signature = 'update-task';

    protected $description = '批量更新药检报告域名';
    public function __construct()
    {
        parent::__construct();
    }
    public function handle()
    {
        $oldDomain = 'https://drugreport.oss-cn-shenzhen.aliyuncs.com';
        $newDomain = 'https://file.snowkirin.com.cn';
        $batchSize = 5000; // 每批 5000 条
        $totalUpdated = 0;

        // 先获取符合条件的总记录数
        $totalCount = DB::table('drug_report_ass')
            ->where('report_url', 'like', "{$oldDomain}%")
            ->count();
        var_dump($totalCount);exit();
        if ($totalCount === 0) {
            $this->info('没有需要更新的记录');
            return 0;
        }

        $this->info("共发现 {$totalCount} 条需要更新的记录");
        $this->info("开始分批更新，每批 {$batchSize} 条...");

        // 创建进度条
        $bar = $this->output->createProgressBar($totalCount);
        $bar->start();

        try {
            // 使用分块更新，避免一次性锁表
            do {
                $affected = DB::table('drug_report_ass')
                    ->where('report_url', 'like', "{$oldDomain}%")
                    ->limit($batchSize)
                    ->update([
                        'report_url' => DB::raw(
                            "REPLACE(report_url, '{$oldDomain}', '{$newDomain}')"
                        )
                    ]);

                $totalUpdated += $affected;
                $bar->advance($affected);

                // 可选：每批之间短暂休眠，减轻数据库压力
                // usleep(100000); // 0.1 秒

            } while ($affected > 0);

            $bar->finish();
            $this->newLine();
            $this->info("✅ 更新完成，共处理 {$totalUpdated} 条记录");

        } catch (\Exception $e) {
            $bar->finish();
            $this->error("❌ 更新失败：{$e->getMessage()}");
            return 1;
        }

        return 0;
    }

}
