<?php

namespace App\Console\Commands;

use App\Models\TextbookSeries;
use App\Services\TextbookApiService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SyncTextbookSeries extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sync:textbook-series {--dry-run : 仅显示将要同步的数据，不实际执行}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步 MySQL 中的教材系列数据到题库服务';

    protected $apiService;

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->apiService = app(TextbookApiService::class);

        $this->info('开始同步教材系列数据...');

        // 获取MySQL中的所有系列
        $mysqlSeries = DB::connection('mysql')
            ->table('textbook_series')
            ->orderBy('id')
            ->get();

        $this->info('MySQL中共有 ' . $mysqlSeries->count() . ' 个系列');

        // 获取题库服务中的所有系列
        try {
            $apiSeries = $this->apiService->getTextbookSeries();
            $existingIds = collect($apiSeries['data'] ?? [])->pluck('id')->toArray();
        } catch (\Exception $e) {
            $this->error('获取题库服务数据失败: ' . $e->getMessage());
            return 1;
        }

        $this->info('题库服务中已有 ' . count($existingIds) . ' 个系列');

        $dryRun = $this->option('dry-run');
        $syncedCount = 0;
        $errorCount = 0;

        foreach ($mysqlSeries as $series) {
            // 检查是否已存在
            if (in_array($series->id, $existingIds)) {
                $this->line("系列 {$series->id} ({$series->name}) 已存在，跳过");
                continue;
            }

            if ($dryRun) {
                $this->line("将同步: ID {$series->id}, 名称 {$series->name}, 别名 {$series->slug}");
                continue;
            }

            try {
                // 准备数据（指定ID以保持一致性）
                $data = [
                    'id' => $series->id,  // 指定相同的ID
                    'name' => $series->name,
                    'slug' => $series->slug,
                    'publisher' => $series->publisher,
                    'region' => $series->region,
                    'stages' => json_decode($series->stages, true),
                    'is_active' => (bool)$series->is_active,
                    'sort_order' => (int)$series->sort_order,
                    'meta' => json_decode($series->meta, true),
                ];

                // 调用API创建
                $result = $this->apiService->createTextbookSeries($data);

                if (isset($result['data'])) {
                    $this->info("✓ 同步成功: ID {$series->id}, 名称 {$series->name}");
                    $syncedCount++;
                } else {
                    $this->error("✗ 同步失败: ID {$series->id}, 名称 {$series->name}");
                    $errorCount++;
                }
            } catch (\Exception $e) {
                $this->error("✗ 同步失败: ID {$series->id}, 错误: " . $e->getMessage());
                Log::error('同步系列失败', ['id' => $series->id, 'error' => $e->getMessage()]);
                $errorCount++;
            }
        }

        if (!$dryRun) {
            $this->newLine();
            $this->info("同步完成! 成功: {$syncedCount}, 失败: {$errorCount}");
        } else {
            $this->newLine();
            $this->info("dry-run 模式完成。如需实际同步，请去掉 --dry-run 参数");
        }

        return 0;
    }
}
