<?php

namespace App\Console\Commands;

use App\Http\Enum\BusinessOrderShippingStatus;
use App\Models\BusinessOrder;
use App\Models\Shop;
use App\Services\Business\BusinessFactory;
use Carbon\Carbon;
use Illuminate\Console\Command;

class KttOrderSyncStatus extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ktt:order_sync_status {ids?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '快团团同步发货状态';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     * @throws \Exception
     */
    public function handle()
    {
        $ids = $this->argument('ids');
        if (!empty($ids)) {
            $ids = explode(",", $ids);
        }
        $startTime = Carbon::now()->subDays(15)->getPreciseTimestamp(3);
        BusinessOrder::query()->when($ids, function ($query) use ($ids) {
            $query->whereIn('id',$ids);
        })
            ->where('confirm_at', '>=', $startTime)
            ->where('shipping_status', BusinessOrderShippingStatus::UNSHIP)
            ->where('cancel_status', 0)
            ->chunk(200, function ($orders) {
                foreach ($orders as $order) {
                    $shop = Shop::query()->find($order['shop_id']);
                    if (!empty($shop)) {
                        BusinessFactory::init()->make($shop->plat_id)->setShop($shop)->queryStatusAndSync($order);
                        usleep(10);
                    }
                }
            });
    }
}
