const ALIPAY_PENDING_REFRESH_KEY = 'pending_alipay_payment_refresh';
const ALIPAY_PAYMENT_DATA_KEY = 'pending_alipay_payment_data';

export const PAYMENT_REFRESH_TARGETS = {
	PACKAGE_ORDER: 'package-order',
	ORDER_LIST: 'order-list',
	MY_WALLET: 'my-wallet'
};

export function isValidWechatPayConfig(payConfig) {
	return !!payConfig &&
		typeof payConfig.package === 'string' &&
		payConfig.package.startsWith('prepay_id=');
}

export function getAlipayPaymentUrl(paymentLink) {
	return getAlipayPaymentUrls(paymentLink).copyUrl;
}

export function getAlipayPaymentUrls(paymentLink) {
	if (!paymentLink) {
		return { copyUrl: '', qrUrl: '' };
	}

	if (typeof paymentLink === 'string') {
		return { copyUrl: paymentLink, qrUrl: paymentLink };
	}

	return {
		copyUrl: paymentLink.copy_link || paymentLink.qr_link || '',
		qrUrl: paymentLink.qr_link || paymentLink.copy_link || ''
	};
}

export function isValidAlipayPaymentLink(paymentLink) {
	return !!getAlipayPaymentUrl(paymentLink);
}

export function markPendingPaymentRefresh(target) {
	if (!target) return;
	uni.setStorageSync(ALIPAY_PENDING_REFRESH_KEY, {
		target,
		timestamp: Date.now()
	});
}

export function consumePendingPaymentRefresh(target) {
	const pending = uni.getStorageSync(ALIPAY_PENDING_REFRESH_KEY);
	if (!pending || pending.target !== target) {
		return false;
	}

	uni.removeStorageSync(ALIPAY_PENDING_REFRESH_KEY);
	return true;
}

export function getPendingAlipayPaymentData() {
	return uni.getStorageSync(ALIPAY_PAYMENT_DATA_KEY) || null;
}

function encodePaymentUrl(value) {
	try {
		return btoa(unescape(encodeURIComponent(value)))
			.replace(/\+/g, '-')
			.replace(/\//g, '_')
			.replace(/=+$/, '');
	} catch (e) {
		return '';
	}
}

function getAlipayPaymentPageUrl(refreshTarget, payUrl, qrUrl) {
	const params = [`t=${Date.now()}`];
	if (refreshTarget) {
		params.push(`from=${encodeURIComponent(refreshTarget)}`);
	}
	if (payUrl) {
		const encodedPayUrl = encodePaymentUrl(payUrl);
		if (encodedPayUrl) {
			params.push(`pay64=${encodedPayUrl}`);
		}
	}
	if (qrUrl) {
		const encodedQrUrl = encodePaymentUrl(qrUrl);
		if (encodedQrUrl) {
			params.push(`qr64=${encodedQrUrl}`);
		}
	}

	return `/pages/alipay-payment/alipay-payment?${params.join('&')}`;
}

function getAlipayPaymentBrowserUrl(pageUrl) {
	if (typeof window === 'undefined' || !window.location) {
		return pageUrl;
	}

	const { origin, pathname } = window.location;
	const pagePath = pageUrl.replace(/^\//, '');
	const basePath = pathname.includes('/pages/')
		? pathname.slice(0, pathname.indexOf('/pages/'))
		: pathname.replace(/\/[^/]*$/, '');

	return `${origin}${basePath}/${pagePath}`;
}

function navigateToAlipayPaymentPage(pageUrl, resolve, reject) {
	uni.navigateTo({
		url: pageUrl,
		success: () => resolve({ redirecting: true }),
		fail: () => {
			uni.redirectTo({
				url: pageUrl,
				success: () => resolve({ redirecting: true }),
				fail: () => {
					if (typeof window !== 'undefined' && window.location) {
						window.location.href = getAlipayPaymentBrowserUrl(pageUrl);
						resolve({ redirecting: true });
						return;
					}

					reject(new Error('\u6253\u5f00\u652f\u4ed8\u5b9d\u652f\u4ed8\u9875\u5931\u8d25'));
				}
			});
		}
	});
}

export function openAlipayPayment(paymentLink, refreshTarget) {
	return new Promise((resolve, reject) => {
		const { copyUrl, qrUrl } = getAlipayPaymentUrls(paymentLink);

		if (!copyUrl && !qrUrl) {
			reject(new Error('\u652f\u4ed8\u94fe\u63a5\u65e0\u6548'));
			return;
		}

		markPendingPaymentRefresh(refreshTarget);
		uni.setStorageSync(ALIPAY_PAYMENT_DATA_KEY, {
			copyUrl,
			qrUrl,
			refreshTarget,
			timestamp: Date.now()
		});

		navigateToAlipayPaymentPage(getAlipayPaymentPageUrl(refreshTarget, copyUrl, qrUrl), resolve, reject);
	});
}

export function wechatH5Pay(payConfig) {
	return new Promise((resolve, reject) => {
		if (!isValidWechatPayConfig(payConfig)) {
			reject(new Error('\u652f\u4ed8\u53c2\u6570\u65e0\u6548'));
			return;
		}

		if (typeof WeixinJSBridge === 'undefined') {
			reject(new Error('\u8bf7\u5728\u5fae\u4fe1\u4e2d\u6253\u5f00'));
			return;
		}

		WeixinJSBridge.invoke('getBrandWCPayRequest', {
			appId: payConfig.app_id,
			timeStamp: payConfig.timestamp,
			nonceStr: payConfig.nonce_str,
			package: payConfig.package,
			signType: payConfig.sign_type,
			paySign: payConfig.pay_sign
		}, function(res) {
			if (res.err_msg === 'get_brand_wcpay_request:ok') {
				resolve({
					success: true,
					message: '\u652f\u4ed8\u6210\u529f'
				});
			} else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
				reject({
					cancelled: true,
					message: '\u5df2\u53d6\u6d88\u652f\u4ed8'
				});
			} else {
				reject({
					success: false,
					message: '\u652f\u4ed8\u5931\u8d25',
					error: res
				});
			}
		});
	});
}

export function showPaymentToast(success, message) {
	uni.showToast({
		title: message || (success ? '\u652f\u4ed8\u6210\u529f' : '\u652f\u4ed8\u5931\u8d25'),
		icon: success ? 'success' : 'none',
		duration: 2000
	});
}

export function handlePaymentError(error) {
	if (error.cancelled) {
		showPaymentToast(false, '\u5df2\u53d6\u6d88\u652f\u4ed8');
		return;
	}

	showPaymentToast(false, error.message || '\u652f\u4ed8\u5931\u8d25');
}
