<?php

namespace App\Console\Commands;

use App\Good;
use App\Trace;
use Carbon\Carbon;
use Vinkla\Hashids\Facades\Hashids;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;

class GenerateKey extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'generate:key {gid}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '生成key';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $gid = $this->argument('gid');
        $good = Good::where('id', $gid)->first();
        $good->is_key = 'D';
        $good->save();

        $keyNum = Trace::where('gid', $gid)->count();

        $jishu = $good->group ?? $good->number;
        $leijia = 0;

        //生成key
        if (($num = ($good->number - $keyNum)) > 0) {
            $zNum = floor($num / 1000);
            $yNum = $num % 1000;
            $i = 0;
            while ($i < $zNum) {
                $data = [];
                for ($j = 0; $j < 1000; $j++) {
                    $key = $good->skey . $this->num_random($good->bit);
                    $data[] = [
                        'gid' => $gid,
                        'key' => $key,
                        'group' => floor($leijia / $jishu),
                        'created_at' => Carbon::now(),
                        'updated_at' => Carbon::now(),
                    ];
                    $leijia++;
                }
                Trace::insert($data);
                $i++;
            }

            for ($m = 0; $m < $yNum; $m++) {
                Trace::create([
                    'gid' => $gid,
                    'key' => $good->skey . $this->num_random($good->bit),
                    'group' => floor($leijia / $jishu),
                ]);
                $leijia++;
            }

        }

        $keyNum = Trace::where('gid', $gid)->count();
        if ($keyNum < $good->number) {
            Artisan::call("generate:key", ['gid' => $good->id]);
        } else {

            $ids = Trace::whereNull('slug')->pluck('id');
            foreach ($ids as $id) {
                Trace::where('id', $id)->update(['slug' => Hashids::encode($id)]);
            }

            $good->is_key = 'T';
            $good->save();
        }
    }


    private function num_random($len = 16)
    {
        $num = '';
        for ($i = 0; $i < $len; $i++) {
            $num .= rand(0, 9);
        }
        return $num;
    }
}
