import {
	baseUrl
} from './base.js'
import CryptoJS from "@/common/crypto-js.min.js"
const aesEncrypt = (word, keyStr, iv) => {
	let key = CryptoJS.enc.Utf8.parse(keyStr)
	let ivs = CryptoJS.enc.Utf8.parse(iv)
	let srcs = CryptoJS.enc.Utf8.parse(word)
	let encrypted = CryptoJS.AES.encrypt(srcs, key, {
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.ZeroPadding,
		iv: ivs
	});
	return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
}

// 小程序端使用
const arrayBuffer2String = (arr) => {
	if (typeof arr === 'string') {
		return arr;
	}
	var tmparr = new Uint8Array(arr);
	var str = '';
	for (var i = 0; i < tmparr.length; i++) {
		var one = tmparr[i].toString(2);
		var v = one.match(/^1+?(?=0)/);
		if (v && one.length == 8) {
			var bytesLength = v[0].length;
			var store = tmparr[i].toString(2).slice(7 - bytesLength);
			for (var st = 1; st < bytesLength; st++) {
				store += tmparr[st + i].toString(2).slice(2);
			}
			str += String.fromCharCode(parseInt(store, 2));
			i += bytesLength - 1;
		} else {
			str += String.fromCharCode(tmparr[i]);
		}
	}
	return str;
}
// 小程序端使用
const string2ArrayBuffer = (str) => {
	var bytes = new Array();
	var len, c;
	len = str.length;
	for (var i = 0; i < len; i++) {
		c = str.charCodeAt(i);
		if (c >= 0x010000 && c <= 0x10FFFF) {
			bytes.push(((c >> 18) & 0x07) | 0xF0);
			bytes.push(((c >> 12) & 0x3F) | 0x80);
			bytes.push(((c >> 6) & 0x3F) | 0x80);
			bytes.push((c & 0x3F) | 0x80);
		} else if (c >= 0x000800 && c <= 0x00FFFF) {
			bytes.push(((c >> 12) & 0x0F) | 0xE0);
			bytes.push(((c >> 6) & 0x3F) | 0x80);
			bytes.push((c & 0x3F) | 0x80);
		} else if (c >= 0x000080 && c <= 0x0007FF) {
			bytes.push(((c >> 6) & 0x1F) | 0xC0);
			bytes.push((c & 0x3F) | 0x80);
		} else {
			bytes.push(c & 0xFF);
		}
	}
	var array = new Int8Array(bytes);
	return array.buffer;
}


const getEncode64 = (str) => {
	// 对编码的字符串转化base64
	// 如果是小程序
	// #ifdef MP  
	let arrayBuffer = string2ArrayBuffer(str)
	let base64 = wx.arrayBufferToBase64(arrayBuffer)
	return base64
	// #endif
	// 如果不是小程序  小程序下btoa会报错未定义
	// #ifndef MP
	let base64 = btoa(str);
	return base64
	// #endif
}
const request = (params, method) => {
	let key = 'r5r8bloufgv12548';
	let iv = '01goyvbnx845fiwm';
	let baseData = {
		loading: true,
		showText: '加载中...',
		url: '',
		loading: true,
		header: {
			// 'content-type': 'application/json',
			"content-type": "application/x-www-form-urlencoded",
			// "Authorization": 'Bearer' + uni.getStorageSync('token')
			"token": uni.getStorageSync('token') || '',
		}
	}
	params = {
		...baseData,
		...params
	}
	let {
		url,
		data,
		loading,
		header,
		showText
	} = params
	data = data ? data : {}
	let otherParams = {
		m: 'yzd_edu',
		i: 2,
		c: 'entry',
		a: 'wxapp',
		deviceType: 'wxapp',
		// deviceType: 'wxh5',
	}
	console.log(data,'dafdafafafgasfafafga')
	if (data.data) {
		data.data = getEncode64(aesEncrypt(getEncode64(JSON.stringify(data.data)), key, iv))
	}
	data = {
		...otherParams,
		...data
	}
	console.log(data,'lllllllllllllllllllllllllllllll')
	if (params.loading) {
		uni.showLoading({
			title: showText
		})
	}
	url = url.includes('http') ? url : baseUrl + url
	return new Promise((reslove, reject) => {
		uni.request({
			url,
			data,
			method,
			header,
			success: (res) => {
				uni.hideLoading()
				uni.stopPullDownRefresh()
				console.log('%c请求结果:', 'color:green;', res.data, url);
				if (res.statusCode == 200) {
					if (res.data.errno != 2004 && res.data.errno != 2003 && res.data.errno != 2001 && res.data.errno != 2002 && res.data.errno != 0) {
						uni.showToast({
							title: res.data.message,
							icon: 'none',
							mask: true
						})
						reject(res.data)
					} else {
						reslove(res.data)
					}
				} else {
					uni.showToast({
						title: res.data.message,
						icon: 'none',
						mask: true
					})
					reject(res.data)
				}
			},
			fail: (err) => {
				uni.hideLoading()
				uni.stopPullDownRefresh()
				console.log('%c请求失败:', 'color:red;', err, url);
				uni.showToast({
					title: err.errMsg,
					icon: 'none',
					mask: true
				})
				reject(err)
			}
		})
	})
}

const http = {
	// http对象中的方法
	get: async params => {
		return await request(params, 'GET')
	},
	post: async params => {
		return await request(params, 'POST')
	},
	put: async params => {
		return await request(params, 'PUT')
	},
	delete: async params => {
		return await request(params, 'DELETE')
	}
}

export default http;
