package utils

import (
	"github.com/gogf/gf/v2/crypto/gaes"
	"github.com/gogf/gf/v2/crypto/gmd5"
	"github.com/gogf/gf/v2/encoding/gbase64"
	"github.com/gogf/gf/v2/os/gmlock"
	"github.com/google/uuid"
	"strings"
)

func GenerateRandomUUID() string {
	uidRes := ""
	gmlock.LockFunc("uuid", func() {
		uid, _ := uuid.NewV7()
		uidRes = strings.ReplaceAll(uid.String(), "-", "")
	})
	return uidRes
}

// TmpEncrypt 临时加密
func TmpEncrypt(s string) string {
	return gmd5.MustEncryptString(s + "e6d1aa6aa8de4fd0ab970e042b0c41df")
}

// EncryptPassword 密码加密
func EncryptPassword(password, salt string) string {
	return gmd5.MustEncryptString(gmd5.MustEncryptString(password) + gmd5.MustEncryptString(salt))
}

// EncryptPasswordAES 使用 AES 对称加密密码（可逆）
func EncryptPasswordAES(password string) (string, error) {
	// 使用固定的加密密钥和初始化向量
	key, _ := gbase64.DecodeString("P0x6Gy6dXIpPbhE7PHxaHbfZHhsbT2qNPlx3qbHTP1o=")
	iv, _ := gbase64.DecodeString("nywao1XkDXeYwbPeWh+SxA==")

	// 加密密码
	encryptedBytes, err := gaes.Encrypt([]byte(password), key, iv)
	if err != nil {
		return "", err
	}

	// 返回 base64 编码的加密结果
	return gbase64.EncodeToString(encryptedBytes), nil
}

// DecryptPasswordAES 使用 AES 对称解密密码
func DecryptPasswordAES(encryptedPassword string) (string, error) {
	// 使用固定的解密密钥和初始化向量
	key, _ := gbase64.DecodeString("P0x6Gy6dXIpPbhE7PHxaHbfZHhsbT2qNPlx3qbHTP1o=")
	iv, _ := gbase64.DecodeString("nywao1XkDXeYwbPeWh+SxA==")

	// base64 解码
	encryptedBytes, err := gbase64.DecodeString(encryptedPassword)
	if err != nil {
		return "", err
	}

	// 解密密码
	decryptedBytes, err := gaes.Decrypt(encryptedBytes, key, iv)
	if err != nil {
		return "", err
	}

	return string(decryptedBytes), nil
}
