
import CryptoJS from "crypto-js";
import {
	deepClone
} from "../uni_modules/uv-ui-tools/libs/function/index.js";
const request = (method = 'GET', serverUrl, domainUrl, params, dataType = "json") => {
	let currentUrl
	// try {
	// 	let pages = getCurrentPages();
	// 	let currentPage = pages[pages.length - 2];
	// 	currentUrl = currentPage.route;
	// 	currentUrl = pageData[currentUrl]
	// } catch (e) {

	// }
	let q = serverUrl
	// 头部header
	let header = {};
	// 请求地址
	serverUrl = serverUrl;
	if (q == 'test') {
		serverUrl = "http://10.3.0.24:9209/"
		header['x-token'] = "bdf87a98-eef0-47df-9faf-41d547b0457e"
	}
	let url = serverUrl+domainUrl//domianUrl(serverUrl, domainUrl);
	if (q != 'test') {
		// params = deepClone(params);
	}

	var key ='e4rOtnF8tJjtHO7ecZeJHN1rapED5ImB'// uni.getStorageSync('encrypt') || "default_encrypt_key";
	let data = {};
	console.log("传参", method === "GET" || method === "DELETE" || q == 'q')
	if (method === "GET" || method === "DELETE" || q == 'q') {
		params.timestamp = Math.floor(new Date().getTime() / 1000);
		params.nonce = generateUUID();
		let keys = Object.keys(params);
		keys.sort();
		for (let i in keys) {
			keys[i] = keys[i] + "=" + encodeURIComponent(params[keys[i]]);
		}
		let temp = keys.join("&") + "&" + CryptoJS.MD5(key).toString();
		params.signature = CryptoJS.MD5(temp).toString();
		data = {
			url: url + "?" + encodeParam(params),
			method,
			header: header // setheader(dataType, header),
		};
	} else if (method === "POST" || method === "PUT") {
		let temp = decodeParam(url);
		temp.timestamp = Math.floor(new Date().getTime() / 1000);
		temp.nonce = generateUUID();
		let keys = Object.keys(temp);
		keys.sort();
		for (let i in keys) {
			keys[i] = keys[i] + "=" + encodeURIComponent(temp[keys[i]]);
		}
		let s = keys.join("&");
		s += "&" + JSON.stringify(params);
		s += "&" + CryptoJS.MD5(key).toString();
		temp.signature = CryptoJS.MD5(s).toString();
		url = url.split("?")[0] + "?" + encodeParam(temp);

		data = {
			url,
			method,
			header: header,
			data: params,
		};
	}

	console.log("传参详情", data)
	return data;
}
// 辅助函数：参数编码
function encodeParam(data) {
	let params = deepClone(data);
	let url = '';
	let keys = Object.keys(params);
	keys.forEach(res => {
		if ((params[res] && params[res] != "") || params[res] === 0) {
			if (typeof (params[res]) != 'string' && typeof (params[res]) != 'number') {
				params[res] = 'Object';
			}
			url += "&";
			url += res;
			url += "=";
			url += encodeURIComponent(params[res]);
		}
	});
	url = url ? url.substring(1) : '';
	return url;
}

// 辅助函数：参数解码
function decodeParam(zipStr) {
	var route = '';
	for (var i = 0; i < zipStr.length; i += 1) {
		var chr = zipStr.charAt(i);
		if (chr === '+') {
			route += ' ';
		} else if (chr === '%') {
			var asc = zipStr.substring(i + 1, i + 3);
			if (parseInt('0x' + asc) > 0x7f) {
				route += decodeURI('%' + asc.toString() + zipStr.substring(i + 3, i + 9).toString());
				i += 8;
			} else {
				route += String.fromCharCode(parseInt('0x' + asc));
				i += 2;
			}
		} else {
			route += chr;
		}
	}
	let data = route.split('?');
	let params = {};
	let data2;
	try {
		if (data.length >= 2) {
			data2 = data[1].split('&');
		} else if (data.length == 1) {
			data2 = data[0].split('&');
		} else {
			return {};
		}
	} catch (e) {
		return {};
	}
	data2.forEach(res => {
		let parts = res.split('=');
		if (parts.length >= 2) {
			params[parts[0]] = decodeURIComponent(parts.slice(1).join('='));
		}
	});
	return params;
}

// AES解密函数
const deCode = (str) => {
	try {
		var key = CryptoJS.enc.Utf8.parse(uni.getStorageSync('decrypt'));
		let iv = key.clone();
		iv.sigBytes = 16;
		iv.clamp();
		let res = CryptoJS.AES.decrypt(str, key, {
			iv,
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7,
		}).toString(CryptoJS.enc.Utf8);
		return JSON.parse(res);
	} catch (error) {
		console.error('Decryption error:', error);
		throw new Error('Failed to decrypt data');
	}
};

// 生成UUID
function generateUUID() {
	var d = new Date().getTime();
	var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
		/[xy]/g,
		function (c) {
			var r = (d + Math.random() * 16) % 16 | 0;
			d = Math.floor(d / 16);
			return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
		}
	);
	return uuid;
}

const postJson = (serverUrl, url, params = {}) => {
	return request('POST', serverUrl, url, params, 'json');
};
const x = postJson("https://flaunt.batiao8.com", "/api/image/segment/base64", {
	"file": "[encoded data, 420228 characters]"
})
console.log(x)