<?php

namespace Kylin\Region\Commands;

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

class RegionImportCommand extends Command
{
    protected $signature = 'kylin:region:import
        {--force : 强制重新导入（清空旧数据）}
        {--level=3 : 导入层级:1省2省市3省市区4省市区乡镇}
        {--province-only : 仅导入省级数据}';

    protected $description = '导入全国省市区乡镇数据（基于 AreaCity 数据源）';

    /**
     * 数据文件目录
     */
    private string $dataDir;

    public function __construct()
    {
        parent::__construct();
        $this->dataDir = dirname(__DIR__, 2) . '/database/data';
    }

    public function handle(): int
    {
        $this->info('');
        $this->info('  ╔══════════════════════════════════════╗');
        $this->info('  ║     Kylin 地区数据导入               ║');
        $this->info('  ╚══════════════════════════════════════╝');
        $this->info('');

        $maxLevel = $this->option('province-only') ? 1 : (int) $this->option('level');
        $levelNames = [1 => '省', 2 => '市', 3 => '区县', 4 => '乡镇'];
        $this->info("导入层级：1~{$maxLevel}（" . implode('→', array_map(fn($l) => $levelNames[$l], range(1, $maxLevel))) . '）');

        // 清空旧数据
        if ($this->option('force') || $this->confirm('是否清空旧数据重新导入？', true)) {
            DB::table('kylin_regions')->truncate();
            $this->info('已清空旧数据');
        }

        $total = 0;

        // 按层级依次导入
        for ($level = 1; $level <= $maxLevel; $level++) {
            $count = $this->importLevel($level);
            $this->info("{$levelNames[$level]}级数据导入完成：{$count} 条");
            $total += $count;
        }

        $this->info('');
        $this->info("  地区数据导入完成，共 {$total} 条");
        $this->info('');

        return self::SUCCESS;
    }

    /**
     * 导入指定层级的数据
     */
    private function importLevel(int $level): int
    {
        $fileMap = [
            1 => 'provinces.json',
            2 => 'cities.json',
            3 => 'districts.json',
            4 => 'towns.json',
        ];

        $filename = $fileMap[$level] ?? null;
        if (!$filename) {
            return 0;
        }

        $path = $this->dataDir . '/' . $filename;

        if (!file_exists($path)) {
            $this->warn("数据文件不存在：{$filename}，跳过");
            return 0;
        }

        $items = json_decode(file_get_contents($path), true);
        if (empty($items)) {
            $this->warn("数据文件为空：{$filename}");
            return 0;
        }

        // 构建 parent_code → id 映射（用于关联父级）
        $codeToId = [];
        if ($level > 1) {
            $codeToId = DB::table('kylin_regions')
                ->where('level', $level - 1)
                ->pluck('id', 'code')
                ->toArray();
        }

        $data = [];
        $skipped = 0;

        foreach ($items as $item) {
            $parentId = 0;
            if ($level > 1 && !empty($item['parent_code'])) {
                $parentId = $codeToId[$item['parent_code']] ?? 0;
                if ($parentId === 0) {
                    $skipped++;
                    continue;
                }
            }

            $data[] = [
                'parent_id' => $parentId,
                'level' => $level,
                'code' => $item['code'],
                'name' => $item['name'],
                'pinyin' => $item['pinyin'] ?? null,
                'pinyin_prefix' => $item['pinyin_prefix'] ?? null,
                'sort' => $item['sort'] ?? 0,
                'created_at' => now(),
                'updated_at' => now(),
            ];
        }

        if ($skipped > 0) {
            $this->warn("跳过 {$skipped} 条无法匹配上级的数据");
        }

        // 分块插入
        foreach (array_chunk($data, 500) as $chunk) {
            DB::table('kylin_regions')->insert($chunk);
        }

        return count($data);
    }
}
