<?php

namespace App\Console\Commands;

use App\Good;
use App\Trace;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class ExportTraces extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'export:traces {gid}  {--queue}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导出code';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->line('开始导出码');
        $id = $this->argument('gid');
        $good = Good::where('id', $id)->first();

        $name = $good->id . '.txt';
        if (Storage::disk('public')->exists($name)) {
            Storage::disk('public')->delete($name);
        }
        Trace::where('gid', $id)->select('id', 'key', 'gid', 'slug')->chunk(2000, function ($trace) use ($name, $good) {
            $trace = $trace->map(function ($v) use ($good) {
                $data[] = $v['key'];
                $data[] = config('app.url') . '/key/' . $v['slug'];
                return implode(',', $data);
            });
            $data = implode($trace->toArray(), "\r\n");
            Storage::disk('public')->append($name, $data);
        });

        $good->update([
            'is_download' => 'T'
        ]);
        $this->line('导出完成');
    }
}
