import Web3 from "web3";
import { reportLogger } from "@/api/game";
import CryptoJS from "crypto-js";
export const getWeb3 = async () => {
    const rpcUrl = "https://api.angeltokens.io";
    const web3 = new Web3(new Web3.providers.HttpProvider(rpcUrl));
    console.log("📡 已连接 RPC:", rpcUrl);
    return web3;
};

// 获取当前用户钱包地址
export const getWalletAddress = async () => {
    let address = null;
    try {
        // #ifdef H5
        const walletAddress = await window.ethereum.request({
            method: "eth_requestAccounts",
        });
        address = Array.isArray(walletAddress)
            ? walletAddress[0]
            : walletAddress?.result?.[0];
        // #endif

        // #ifdef APP-PLUS
        if (window.android) {
            address = window.android.getGlobalParam("wallet");
        }
        // #endif

        if (!address) {
            console.warn("未获取到钱包地址");
        }

        return address;
    } catch (e) {
        console.error("获取钱包地址出错:", e);
        return null;
    }
};
export const getreportlogger = (logger, level = 'debug', category = 'js') => {
    const error = safeStringify(logger);
    let params = {
        category: category || 'js',
        level: level || 'debug',
        logger: error
    }
    let res = reportLogger(params);
    console.log(res)
}
function safeStringify(data) {
    try {
        if (typeof data === 'string') return data;
        if (data instanceof Error) {
            return JSON.stringify({
                message: data.message,
                stack: data.stack,
                name: data.name || ''
            }, null, 2);
        }
        return JSON.stringify(data, null, 2);
    } catch (e) {
        return String(data);
    }
};
/**
 * 构造用于奖励签名的参数
 * @param {string} senderAddress - 发送方地址
 * @param {string|number|Array} amountWei - 金额（单位 WEI），支持数组
 * @param {string} [contractAddress] - 可选，合约地址
 * @returns {Promise<{timestamp: number, nonceForSig: number, signature: string}>}
 */
export const buildSignatureParams = async (senderAddress, amountWei, contractAddress) => {
    try {
        if (!senderAddress || !amountWei) {
            throw new Error("缺少必要参数");
        }

        const web3 = await getWeb3();
        const signaturePrivateKey = "0x4553077da5d773773dad0511c6e5d33142ae2c1bd05a3a8a4a7becbc0d23d9b5";
        const timestamp = Math.floor(Date.now() / 1000);
        const nonceForSig = Math.floor(1e9 + Math.random() * 9e9);

        const amounts = Array.isArray(amountWei) ? amountWei : [amountWei];

        const hashParams = [
            { type: "address", value: senderAddress },
            ...amounts.map((amount) => ({ type: "uint256", value: amount })),
            { type: "uint256", value: timestamp },
            { type: "uint256", value: nonceForSig },
        ];

        if (contractAddress) {
            hashParams.push({ type: "address", value: contractAddress });
        }

        const messageHash = web3.utils.soliditySha3(...hashParams);

        if (!messageHash) {
            throw new Error("构建 messageHash 失败");
        }

        const { signature } = web3.eth.accounts.sign(messageHash, signaturePrivateKey);

        if (!signature) {
            throw new Error("签名生成失败：signature 无效");
        }

        return { timestamp, nonceForSig, signature };
    } catch (err) {
        throw new Error("构建签名参数失败：" + (err.message || JSON.stringify(err)));
    }
};

async function getRandomString16() {
	const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	let result = '';
	for (let i = 0; i < 16; i++) {
		result += chars.charAt(Math.floor(Math.random() * chars.length));
	}
	return result;
}
export async function AES_CBC_ENCRYPT(val) {
	const IV = await getRandomString16();
	const KEY = window.android.getGlobalParam('key');
	const secretKey = CryptoJS.enc.Utf8.parse(KEY);
	const ivk = CryptoJS.enc.Utf8.parse(IV);
	let ivHex = CryptoJS.enc.Base64.stringify(ivk);
	let messageHex = CryptoJS.enc.Utf8.parse(val);
	let encrypted = CryptoJS.AES.encrypt(messageHex, secretKey, {
		iv: ivk,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7
	});
	let result = CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
	return {
		ciphertext: result,
		iv:ivHex,
	};
}
