<?php

namespace App\Console\Commands;

use App\Exceptions\ClientException;
use App\Import\CategoryImport;
use App\Models\Goods\Category;
use EasyWeChat\Kernel\Exceptions\ServiceNotFoundException;
use Guanguans\Notify\Factory;
use http\Exception\RuntimeException;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class ExportCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'export {cmd?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    public function handle()
    {
        $cmd = $this->argument('cmd');
        $args = $this->arguments();
        unset($args['command'], $args['cmd']);
        $params = array_values($args);

        if (empty($cmd)) {
            echo 'Nothing to do...';
        } else {
            if (method_exists($this, $cmd)) {
                call_user_func_array([$this, $cmd], $params);
            } else {
                echo 'cmd not exists';
            }
        }
        return;
    }

    public function category()
    {
        //从一个表格中获取数据,并放入到一个数组中
        $r = (new CategoryImport())->collection(Excel::toCollection(null, storage_path('app/public/category.xls'))[0]);
        DB::transaction(function () use ($r) {
            foreach ($r as $k => $v) {
                if ($k == 0) {
                    continue;
                }
                /** @var Category $category */
                $category = Category::where("name", $v[1])->first();
                $data = [
                    'name' => $v[0],
                    'parent_id' => optional($category)->id ?? 0,
                    'level' => optional($category)->level + 1,
                    'thumb' => "https://iph.href.lu/400x200",
                    'weight' => $v[2],
                    'index_weight' => $v[3],
                    "category_weight" => $v[5],
                    "search_weight" => $v[4],
                ];
                $c = new Category($data);
                $c->save();
            }
        });

    }

    public function robot()
    {
        throw new ServiceNotFoundException("找不到");
//        dump(1/0);
    }
}