import config from "../config";
let AccessToken

async function getAccessToken() {
	const accountInfo = await uni.getAccountInfoSync();
	console.log(accountInfo);
	const appID = accountInfo.miniProgram.appId
	return new Promise((resolve, reject) => {
		uni.request({
			url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appID}&secret=${config.secret}`,
			method: "GET",
			success(res) {
				resolve(res.data.access_token)
			},
			fail(err) {
				console.error(err)
				resolve(false)
			}
		})
	})
}


function getCode(data, token) {
	return new Promise((resolve) => {
		uni.request({
			url: `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${token}`,
			method: "POST",
			responseType: "arraybuffer",
			data: JSON.stringify(data),
			success(res) {
				resolve(res)
			},
			fail(err) {
				console.error(err)
				resolve(false)
			}
		})
	})
}

export async function getMiniCode(data) {
	const token = await getAccessToken()
	const code = await getCode(data, token)
	const arrayBuffer = new Uint8Array(code.data)
	const base64 = wx.arrayBufferToBase64(arrayBuffer)
	return `data:image/jpeg;base64,${base64}`
}