<?php

namespace App\Console\Commands;

use App\Handlers\LoadExcelHandler;
use App\Import;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;

class LoadExcels extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'excel:load {id}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '读取excel';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $info = Import::where('id', $this->argument('id'))->first();

        $data = (new LoadExcelHandler)->load(public_path('uploads') . '/' . $info->path);

        $category = collect(Import::$CATEGORY)->where('id', $info->category)->first();

        unset($data[0]);

        $data = collect($data)->map(function ($v) use ($category) {
            return array_combine(array_column($category['fields'], 'field'), array_only($v, array_column($category['fields'], 'column')));
        })->toArray();

        $info->is_load = 'T';
        $info->data = serialize($data);
        $info->save();

        if ($info->is_import === 'T') {
            Artisan::queue('database:import', ['id' => $info->id]);
        }

    }
}
