<?php

namespace BYDAuto\Commands;

use BYDAuto\Jobs\TestdrivePushJob;
use BYDAuto\Models\Testdrive;
use BYDAuto\Models\Vehicle;
use Illuminate\Console\Command;

class CheryTransferCommand extends Command
{
    // php artisan BYDAuto:transfer vehicle_alias_update
    // php artisan BYDAuto:transfer dispatch_by_mobile
    // php artisan BYDAuto:transfer dispatch_all_draft
    protected $signature = 'bydauto:transfer {action}';

    protected $description = '奇瑞SCRM数据传输';

    public function handle()
    {
        $action = $this->argument('action');
        $this->{'action_' . $action}();
    }

    public function action_dispatch_all_draft()
    {
        $items = Testdrive::query()
            ->where('status', Testdrive::STATUS_DRAFT)
            ->get();
        $this->showTable($items);

        $confirm = $this->confirm('是否确认推送？', true);
        if (!$confirm) {
            return Command::SUCCESS;
        }
        foreach ($items as $model) {
            TestdrivePushJob::dispatch($model);
        }
        return Command::SUCCESS;
    }

    public function action_vehicle_alias_update()
    {
        $items = Vehicle::query()->get();
        $items->each(function ($item) {
            $cleanName = preg_replace('/\s+/', '', $item->name);
            $alias = [$item->name];
            if ($item->name !== $cleanName) {
                $alias[] = $cleanName;
            }
            $item->update(['alias' => $alias]);
        });
    }

    public function action_dispatch_by_mobile()
    {
        $mobiles = $this->ask('请输入手机号码，多个用逗号分隔');
        $mobiles = explode(',', $mobiles);

        $items = Testdrive::query()
            ->whereIn('mobile', $mobiles)
            ->get();
        $this->showTable($items);

        $confirm = $this->confirm('是否确认推送？', true);
        if (!$confirm) {
            return Command::SUCCESS;
        }
        foreach ($items as $model) {
            TestdrivePushJob::dispatch($model);
        }
        return Command::SUCCESS;
    }

    protected function showTable($items)
    {
        $columns = ['id', 'status', 'name', 'mobile'];
        $this->table($columns, $items->map(fn($item) => $item->only($columns)));
    }
}
