/*
 * 文 件 名:  MockPileClientStarter
 * 版    权:  华设设计集团股份有限公司
 * 描    述:  Mock充电桩客户端独立启动器
 * 修 改 人:  lvwenbin
 * 修改时间:  2025/12/23
 */
package com.ruoyi.ems.charging.mock;

import com.ruoyi.ems.charging.mock.config.MockPileConfig;
import com.ruoyi.ems.charging.mock.simulator.MockPileClientManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Mock充电桩客户端独立启动器
 * 可以独立于Spring运行,用于测试
 *
 * Usage:
 *   java -jar mock-pile.jar [serverHost] [serverPort] [configType]
 *
 * Examples:
 *   java -jar mock-pile.jar                          # 默认: 127.0.0.1:8234, simple配置
 *   java -jar mock-pile.jar 192.168.1.100 8234       # 指定服务器
 *   java -jar mock-pile.jar 127.0.0.1 8234 highway   # 高速服务区完整配置
 *
 * @author lvwenbin
 * @version [版本号, 2025/12/23]
 */
public class MockPileClientStarter {

    private static final Logger log = LoggerFactory.getLogger(MockPileClientStarter.class);

    public static void main(String[] args) {
        // 解析命令行参数
        String serverHost = args.length > 0 ? args[0] : "127.0.0.1";
        int serverPort = args.length > 1 ? Integer.parseInt(args[1]) : 8234;
        String configType = args.length > 2 ? args[2] : "simple";

        log.info("========================================");
        log.info("   Mock充电桩客户端启动器");
        log.info("========================================");
        log.info("服务器地址: {}:{}", serverHost, serverPort);
        log.info("配置类型: {}", configType);
        log.info("----------------------------------------");

        // 创建配置
        MockPileConfig config;
        if ("highway".equalsIgnoreCase(configType)) {
            config = MockPileConfig.createHighwayServiceAreaConfig();
            log.info("使用高速服务区配置:");
            log.info("  - 4台充电主机");
            log.info("  - 共30把充电枪");
            log.info("  - 4台600kW水冷枪 + 26台250kW风冷枪");
        } else {
            config = MockPileConfig.createSimpleTestConfig();
            log.info("使用简单测试配置:");
            log.info("  - 1台充电主机");
            log.info("  - 1把充电枪(120kW)");
        }

        config.setServerHost(serverHost);
        config.setServerPort(serverPort);

        // 设置模拟参数
        config.setHeartbeatIntervalSeconds(10);
        config.setChargingReportIntervalSeconds(5);
        config.setChargingCycleSeconds(120);      // 2分钟一个充电周期
        config.setChargingDurationSeconds(120);   // 充电时长2分钟
        config.setAutoChargingEnabled(true);

        log.info("模拟参数:");
        log.info("  - 心跳间隔: {}秒", config.getHeartbeatIntervalSeconds());
        log.info("  - 数据上报间隔: {}秒", config.getChargingReportIntervalSeconds());
        log.info("  - 充电周期: {}秒", config.getChargingCycleSeconds());
        log.info("  - 充电时长: {}秒", config.getChargingDurationSeconds());
        log.info("  - 自动充电: {}", config.isAutoChargingEnabled() ? "启用" : "禁用");
        log.info("----------------------------------------");

        // 创建并启动管理器
        MockPileClientManager manager = new MockPileClientManager(config);
        manager.startAll();

        // 添加关闭钩子
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            log.info("收到关闭信号,正在停止...");
            manager.stopAll();
        }));

        // 定时打印状态
        ScheduledExecutorService statusPrinter = Executors.newSingleThreadScheduledExecutor();
        statusPrinter.scheduleAtFixedRate(manager::printStatus, 30, 30, TimeUnit.SECONDS);

        // 交互式命令行
        log.info("========================================");
        log.info("可用命令:");
        log.info("  status  - 显示当前状态");
        log.info("  start <桩号> <枪号> - 手动开始充电");
        log.info("  stop <桩号> <枪号> - 手动停止充电");
        log.info("  list    - 列出所有桩和枪");
        log.info("  quit    - 退出程序");
        log.info("========================================");

        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("> ");
            String line = scanner.nextLine().trim();

            if (line.isEmpty()) {
                continue;
            }

            String[] parts = line.split("\\s+");
            String cmd = parts[0].toLowerCase();

            try {
                switch (cmd) {
                    case "status":
                        manager.printStatus();
                        break;

                    case "start":
                        if (parts.length >= 3) {
                            manager.startCharging(parts[1], parts[2]);
                        } else {
                            System.out.println("用法: start <桩号> <枪号>");
                        }
                        break;

                    case "stop":
                        if (parts.length >= 3) {
                            manager.stopCharging(parts[1], parts[2]);
                        } else {
                            System.out.println("用法: stop <桩号> <枪号>");
                        }
                        break;

                    case "list":
                        System.out.println("可用的桩和枪:");
                        manager.getAllClients().forEach(client -> {
                            System.out.println("  桩: " + client.getPileCode());
                            client.getAllGunStates().forEach(gun -> {
                                System.out.println("    枪" + gun.getGunNo() + ": " +
                                        (gun.isCharging() ? "充电中" : "空闲") +
                                        ", " + gun.getRatedPower() + "kW");
                            });
                        });
                        break;

                    case "quit":
                    case "exit":
                        System.out.println("正在退出...");
                        statusPrinter.shutdownNow();
                        manager.stopAll();
                        System.exit(0);
                        break;

                    default:
                        System.out.println("未知命令: " + cmd);
                        break;
                }
            } catch (Exception e) {
                System.out.println("命令执行出错: " + e.getMessage());
            }
        }
    }
}
