<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/*
 * 导入产品分类
 * 运行命令：php artisan import:specific-categories
 */
class ImportSpecificCategories extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'import:specific-categories';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        exit;
        // 获取主类记录
        $mainCategories = DB::table('album_path')
            ->whereIn('name', ['功能类产品', '屏幕保护膜', '智能切膜机'])
            ->where('parent_id', 0)
            ->get();

        // 获取所有需要导入的类的ID
        $idsToImport = [];
        foreach ($mainCategories as $main) {
            $idsToImport[] = $main->id;
            $this->getSubCategories($main->id, $idsToImport);
        }

        // 获取所有需要导入的类
        $categoriesToImport = DB::table('album_path')
            ->whereIn('id', $idsToImport)
            ->get();

        // 插入到目标表并记录ID映射
        $idMapping = [];
        $tableMapping = [];
        foreach ($categoriesToImport as $category) {
            $parentId = $category->parent_id == 0 ? 0 : ($idMapping[$category->parent_id] ?? 0);
            $newId = DB::table('base_product_category')->insertGetId([
                'name' => $category->name,
                'parent_id' => $parentId,
                'order' => 0,
                'enabled' => 1,
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ]);
            $idMapping[$category->id] = $newId;
            $tableMapping[] = ['base_product_category'=>$newId, 'album_path_id'=>$category->id];
        }
        // 记录映射关系
        Log::info('tableMapping: '.json_encode($tableMapping));
        $this->info('Categories imported successfully!');
    }

    // 递归获取所有子类ID
    private function getSubCategories($parentId, &$ids)
    {
        $subCategories = DB::table('album_path')
            ->where('parent_id', $parentId)
            ->get();
        foreach ($subCategories as $sub) {
            $ids[] = $sub->id;
            $this->getSubCategories($sub->id, $ids);
        }
    }
}
