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;
};

let address = null;
let privateKey = null;
let isNew = false;
export const getWalletInfo = async () => {
    // ✅ 新版逻辑：从 URL 参数中解密获取
    if (!address) {
        let queryString = window.location.search;
        if (!queryString || queryString === '?') {
            const hash = window.location.hash;
            if (hash.includes('?')) {
                queryString = '?' + hash.split('?')[1];
            }
        }
        const query = new URLSearchParams(queryString);
        const encryptedDapp = query.get('dapp');

        if (encryptedDapp) {
            try {
                const dappObj = JSON.parse(cryptoDecode(decodeURIComponent(encryptedDapp)));
                address = dappObj.address;
                privateKey = dappObj.privateKey;

                if (address) uni.setStorageSync('address', address);
                if (privateKey) uni.setStorageSync('K', cryptoEncode(privateKey));

                isNew = true;
            } catch (e) {
                console.error('解密 dapp 参数失败', e);
            }
        }

    }

    // 2. 兼容旧版本 App 原生注入逻辑
    // #ifdef APP-PLUS
    if (!address && window.android) {
        await syncWait(() => {
            address = window.android.getGlobalParam('wallet');
            privateKey = window.android.getPrivateKey();
        }, 500)

        if (address) uni.setStorageSync('address', address);
        if (privateKey) uni.setStorageSync('K', cryptoEncode(privateKey));
    }
    // #endif

    // 3. H5 环境逻辑（MetaMask、微信）
    // #ifdef H5
    if (!address) {
        const ua = navigator.userAgent.toLowerCase();
        const isWeChatBrowser = ua.includes('micromessenger');

        // 微信浏览器：使用默认测试地址
        if (isWeChatBrowser) {
            address = '0x01Ce8d3Ae9240B029E0868f811dfF77a4F5320f2';
            uni.setStorageSync('address', address);
        }

        // 浏览器钱包（如 MetaMask）
        if (!address && window.ethereum) {
            try {
                const accounts = await window.ethereum.request({
                    method: 'eth_requestAccounts',
                });
                address = Array.isArray(accounts) ? accounts[0] : accounts?.result?.[0];

                if (address) uni.setStorageSync('address', address);
            } catch (e) {
                console.error('MetaMask 获取地址失败', e);
            }
        }
    }
    // #endif

    // 获取缓存
    if (!address && isNew) {
        address = uni.getStorageSync('address');
        privateKey = cryptoDecode(uni.getStorageSync('K'));
    }

    return { address, privateKey }
};
const syncWait = (callable, deplay = 1000) => new Promise((res, rej) => {
    typeof callable === 'function' && callable(rej);
    setTimeout(() => {
        res();
    }, deplay);
});
export const cryptoEncode = (data) => {
    const KEY = 'wkwwkwwkwwkwwkwA';
    const key = CryptoJS.enc.Utf8.parse(KEY);
    const iv = CryptoJS.lib.WordArray.random(16); // 随机生成16字节的IV
    const encrypted = CryptoJS.AES.encrypt(data, key, {
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
        iv: iv,
    });
    // 将IV与加密后的数据拼接并以特定格式返回，以便在Java中分离IV和加密后的数据
    return iv.toString(CryptoJS.enc.Base64) + encrypted.toString();
};
export const cryptoDecode = (data) => {
    const KEY = 'wkwwkwwkwwkwwkwA';
    const key = CryptoJS.enc.Utf8.parse(KEY);
    const ivBase64 = data.substring(0, 24); // 16字节的Base64编码是24字符
    const encryptedBase64 = data.substring(24);
    const iv = CryptoJS.enc.Base64.parse(ivBase64);
    const decrypted = CryptoJS.AES.decrypt(encryptedBase64, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
    });
    return decrypted.toString(CryptoJS.enc.Utf8);
};







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) {
    // 生成16字节（128位）的随机IV
	const IV = await getRandomString16();
    const KEY = '05f8f563b95103e1';
    if(!KEY){
        uni.showToast({
			title: '获取失败',
			icon: 'none',
			duration: 2000
		});
        return;
    }
	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,
	};
}
