package com.ruoyi.common.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Scanner;

/**
 * 简化版许可证密钥生成工具
 * 用于生成指定到期时间的许可证密钥
 *
 * @author ruoyi
 * @date 2026-02-09
 */
public class LicenseKeyGeneratorSimple {

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("=== 许可证密钥生成工具（简化版）===\n");

        while (true) {
            System.out.println("请选择操作：");
            System.out.println("1. 生成指定天数的许可证");
            System.out.println("2. 生成指定到期日期的许可证");
            System.out.println("3. 验证许可证密钥");
            System.out.println("0. 退出");
            System.out.print("\n请输入选项: ");

            String choice = scanner.nextLine().trim();

            switch (choice) {
                case "1":
                    generateByDays(scanner);
                    break;
                case "2":
                    generateByDate(scanner);
                    break;
                case "3":
                    validateKey(scanner);
                    break;
                case "0":
                    System.out.println("退出程序");
                    scanner.close();
                    return;
                default:
                    System.out.println("无效选项，请重新输入\n");
            }
        }
    }

    /**
     * 生成指定天数的许可证
     */
    private static void generateByDays(Scanner scanner) {
        System.out.print("\n请输入许可证有效天数（例如：30、90、365）: ");
        String input = scanner.nextLine().trim();

        try {
            int days = Integer.parseInt(input);

            // 当前时间作为激活时间
            Date now = new Date();
            long activationTime = now.getTime();

            // 计算到期时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            calendar.add(Calendar.DAY_OF_MONTH, days);
            Date expiryDate = calendar.getTime();
            long expiryTime = expiryDate.getTime();

            // 生成许可证密钥
            String encryptedKey = LicenseEncryptUtil.generateLicenseKey(activationTime, expiryTime, days);

            // 输出结果
            System.out.println("\n========================================");
            System.out.println("许可证密钥生成成功！");
            System.out.println("========================================");
            System.out.println("激活时间: " + DATE_FORMAT.format(now));
            System.out.println("到期时间: " + DATE_FORMAT.format(expiryDate));
            System.out.println("有效天数: " + days + " 天");
            System.out.println("\n许可证密钥（请复制以下内容）:");
            System.out.println("----------------------------------------");
            System.out.println(encryptedKey);
            System.out.println("----------------------------------------\n");

            // 解密并验证许可证
            String decryptedData = LicenseEncryptUtil.decrypt(encryptedKey);

            // 解析许可证数据：格式为 "激活时间|到期时间|试用天数|校验码"
            String[] parts = decryptedData.split("\\|");

            try {
                long activationTimeMs = Long.parseLong(parts[0]);
                long expiryTimeMs = Long.parseLong(parts[1]);
                int trialDays = Integer.parseInt(parts[2]);
                String checksum = parts[3];

                // 验证校验码
                String expectedChecksum = LicenseEncryptUtil.generateChecksum(
                        activationTimeMs, expiryTimeMs, trialDays);
                if (!checksum.equals(expectedChecksum)) {
                    System.out.println("许可证校验码验证失败");
                }

                // 检查是否过期
                Date expiryTime2 = new Date(expiryTimeMs);

                if (now.after(expiryTime2)) {
                    System.out.println("许可证已过期，到期时间: {}" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, expiryTime2));
                    return;
                }

                System.out.println("许可证验证通过，到期时间: {}" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, expiryTime2));
            } catch (NumberFormatException e) {
                System.out.println("许可证数据解析失败" + e);
                return;
            }

            // 验证生成的密钥
            System.out.println("密钥验证:✓ 有效");
            System.out.println("========================================\n");

        } catch (NumberFormatException e) {
            System.out.println("输入格式错误，请输入数字\n");
        } catch (Exception e) {
            System.out.println("生成失败: " + e.getMessage() + "\n");
        }
    }

    /**
     * 生成指定到期日期的许可证
     */
    private static void generateByDate(Scanner scanner) {
        System.out.print("\n请输入到期日期（格式：yyyy-MM-dd，例如：2027-12-31）: ");
        String dateInput = scanner.nextLine().trim();

        try {
            // 解析日期（设置为当天的23:59:59）
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date expiryDate = inputFormat.parse(dateInput);

            // 设置为当天的23:59:59
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(expiryDate);
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            expiryDate = calendar.getTime();
            long expiryTime = expiryDate.getTime();

            // 当前时间作为激活时间
            Date now = new Date();
            long activationTime = now.getTime();

            // 计算天数
            long diffMillis = expiryTime - activationTime;
            int days = (int) (diffMillis / (1000 * 60 * 60 * 24));

            if (days <= 0) {
                System.out.println("到期日期必须在当前日期之后\n");
                return;
            }

            // 生成许可证密钥
            String licenseKey = LicenseEncryptUtil.generateLicenseKey(activationTime, expiryTime, days);

            // 输出结果
            System.out.println("\n========================================");
            System.out.println("许可证密钥生成成功！");
            System.out.println("========================================");
            System.out.println("激活时间: " + DATE_FORMAT.format(now));
            System.out.println("到期时间: " + DATE_FORMAT.format(expiryDate));
            System.out.println("有效天数: " + days + " 天");
            System.out.println("\n许可证密钥（请复制以下内容）:");
            System.out.println("----------------------------------------");
            System.out.println(licenseKey);
            System.out.println("----------------------------------------\n");

            // 验证生成的密钥
            boolean isValid = LicenseEncryptUtil.validateLicenseKey(licenseKey);
            System.out.println("密钥验证: " + (isValid ? "✓ 有效" : "✗ 无效"));
            System.out.println("========================================\n");

        } catch (Exception e) {
            System.out.println("日期格式错误或生成失败: " + e.getMessage() + "\n");
        }
    }

    /**
     * 验证许可证密钥
     */
    private static void validateKey(Scanner scanner) {
        System.out.print("\n请输入要验证的许可证密钥: ");
        String licenseKey = scanner.nextLine().trim();

        if (licenseKey.isEmpty()) {
            System.out.println("许可证密钥不能为空\n");
            return;
        }

        try {
            // 解析许可证
            Map<String, Object> licenseInfo = LicenseEncryptUtil.parseLicenseKey(licenseKey);

            if (licenseInfo == null) {
                System.out.println("\n========================================");
                System.out.println("✗ 许可证密钥无效（解析失败或校验码错误）");
                System.out.println("========================================\n");
                return;
            }

            // 获取信息
            long activationTime = (Long) licenseInfo.get("activationTime");
            long expiryTime = (Long) licenseInfo.get("expiryTime");
            int trialDays = (Integer) licenseInfo.get("trialDays");

            Date activationDate = new Date(activationTime);
            Date expiryDate = new Date(expiryTime);
            Date now = new Date();

            boolean isValid = LicenseEncryptUtil.validateLicenseKey(licenseKey);
            int remainingDays = LicenseEncryptUtil.getRemainingDays(licenseKey);

            // 输出结果
            System.out.println("\n========================================");
            System.out.println("许可证信息");
            System.out.println("========================================");
            System.out.println("激活时间: " + DATE_FORMAT.format(activationDate));
            System.out.println("到期时间: " + DATE_FORMAT.format(expiryDate));
            System.out.println("有效天数: " + trialDays + " 天");
            System.out.println("当前时间: " + DATE_FORMAT.format(now));
            System.out.println("\n状态: " + (isValid ? "✓ 有效" : "✗ 已过期"));
            if (isValid) {
                System.out.println("剩余天数: " + remainingDays + " 天");
            }
            System.out.println("========================================\n");

        } catch (Exception e) {
            System.out.println("\n验证失败: " + e.getMessage() + "\n");
        }
    }
}
