package cn.iocoder.yudao.module.member.util;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


public class QRCodeWithJWTUtil {
    private static final String SECRET_KEY = "your_secret_key"; // 使用HS256算法生成秘钥
    public static final String BASE_PATH = "qrCodes/";
    public static final String QR_PREFIX_ZF = "";
    public static final String QR_PREFIX_HX = "HX";
//    public static void main(String[] args) throws WriterException, IOException {
//        // 用户ID
//        Long userId = 123L;
//
//        // 生成包含JWT的二维码
//        String jwt = generateJWT(userId, 1); // 1分钟后过期
//        String fileName = "QRCode_" + userId + ".png";
//        generateQRCode(jwt, 350, 350, BASE_PATH+fileName); // 生成二维码并保存
//    }

    // 生成 JWT
    public static String generateJWT(Long userId) {
        // 创建 JWT payload
        Map<String, Object> payload = new HashMap<>();
        payload.put("userId", userId);

        // 设置过期时间为1分钟
        long expireTime = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(1);
        payload.put("exp", expireTime); // 添加过期时间到 payload

        // 生成 JWT

        return JWTUtil.createToken(payload, SECRET_KEY.getBytes());
    }

    // 生成二维码图片
    public static String generateQRCode(String data, int width, int height, String filePath)  {
        BufferedImage generate = QrCodeUtil.generate(data, width, height);

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(generate, "png", baos);
            byte[] imageBytes = baos.toByteArray();
            return "data:image/png;base64," + Base64.getEncoder().encodeToString(imageBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    // 验证JWT是否有效和未过期
    public static String validateJWT(String jwt) {
        boolean isValid = JWTUtil.verify(jwt, SECRET_KEY.getBytes());
        if (isValid) {
            System.out.println("JWT 验证成功！");
            // 解析 JWT
            JSONObject payloads = JWTUtil.parseToken(jwt).getPayloads();
            Map<String, Object> map = JSONUtil.toBean(payloads, Map.class);
            return map.get("userId").toString();
        } else {
            System.out.println("JWT 验证失败！");
        }
        return null;
    }


    public static void main(String[] args) {
        String encode = "https://yclhit.com:8896/qrCodes/code?id=177799";
//      System.out.println(encode);
        String fileName = "QRCode_" + "test" + ".png";
        String path = QRCodeWithJWTUtil.BASE_PATH+fileName;
        String s = QRCodeWithJWTUtil.generateQRCode(encode, 350, 350, path);
        System.out.println(s);
    }
}
