// utils/wxsdk.js —— 封装微信扫一扫 不用旧的了
import { wechatApi } from '@/api/index.js'

const getWx = () => window.jWeixin || window.wx
const entryUrl = window.__WX_ENTRY_URL__ || window.location.href.split('#')[0]
let configPromise = null
let configUrl = ''
let configReady = false

const isIOS = () => /iphone|ipad|ipod/i.test(navigator.userAgent)

const getConfigUrl = () => {
	// iOS 微信 WebView 的 JS-SDK 签名 URL 需要使用 SPA 首次进入的地址。
	if (isIOS()) {
		return entryUrl
	}

	return window.location.href.split('#')[0]
}

/**
 * 初始化微信 JS-SDK
 */
export async function initWxConfig() {
	const wx = getWx()
	if (!wx) {
		throw new Error('微信 SDK 未加载')
	}

	const url = getConfigUrl()
	console.log(url);

	if (configReady && configUrl === url) {
		return
	}

	if (configPromise && configUrl === url) {
		return configPromise
	}

	configUrl = url
	configReady = false

	configPromise = wechatApi.getJssdkConfig(url).then((data) => {
		const { app_id, timestamp, nonce_str, signature } = data

		return new Promise((resolve, reject) => {
			wx.config({
				debug: false,
				appId: app_id,
				timestamp: timestamp,
				nonceStr: nonce_str,
				signature: signature,
				jsApiList: ['scanQRCode']
			})
			wx.ready(() => {
				console.log('微信 SDK 就绪')
				configReady = true
				resolve()
			})
			wx.error((err) => {
				console.error('wx.config 失败', err)
				configReady = false
				configPromise = null
				reject(err)
			})
		})
	}).catch((e) => {
		console.error('获取微信签名失败', e)
		configPromise = null
		configReady = false
		throw e
	})

	return configPromise
}

/**
 * 调起微信扫一扫
 * @returns {Promise<string>}  扫码结果字符串
 */
export async function wxScan() {
	await initWxConfig()
	const wx = getWx()
	if (!wx) {
		throw new Error('微信 SDK 未加载')
	}

	return new Promise((resolve, reject) => {
		wx.scanQRCode({
			needResult: 1,
			scanType: ['qrCode', 'barCode'],
			success(res) {
				console.log('扫码成功:', res)
				resolve(res.resultStr)
			},
			fail(err) {
				console.error('扫码失败:', err)
				reject(err)
			}
		})
	})
}

/**
 * 检查是否在微信环境中
 */
export function isInWechat() {
	return /micromessenger/i.test(navigator.userAgent)
}
