import Request from '@/common/request.js';
let request = new Request().http
const api = {
	// 支付
	zfbPayment: '/app/live/liveOrder/aliPayment', // 支付宝付款
	weChatPayment: '/app/live/liveOrder/weChatPayment', // 微信付款


	// updateConfirm: (orderId, type) => `/app/live/liveOrder/updateConfirm/${orderId}/${type} `, // 取消/支付订单确认



}


// 支付

// 支付宝付款
export function zfbPayment(data) {
	return request(api.zfbPayment, data, 'POST', 'application/json;charset=UTF-8')
}
// 微信付款
// export function weChatPayment(data) {
// 	return request(api.weChatPayment, data, 'POST', 'application/json;charset=UTF-8')
// }
/**
 * 微信支付（全平台适配简化版）
 * @param {String} orderId 订单ID
 * @param {Number} amount 金额（单位：分）
 * @returns {Promise}
 */
// export function weChatPayment(orderId, amount) {
export function weChatPayment(data) {
	return new Promise((resolve, reject) => {
		let res = {
"code": 200,
"msg": "success",
"payType": 1,
"result": {"timeStamp":"1757906581","package":"prepay_id=wx151123017811185ff21654a23ca0660000","paySign":"XZOdWmeUE4vtrsTiBcgc830dI5cTxDMOld4nEodSImjtnxNP7g4ehBCYBT9lSXQviX2CAqYfYS3Nazt81jCz3U8rjcxvf0IP1rKzesYHozTwkTh9PfOMu5kwBIf48pF1pG8P4w02cBMvfmEvN8c9ISc1Lx528IqV/pC12cxGTNBktH8UFFU5hdEmbpu9sI+4VfDpgroHs5y8xx2DK072LulF8g9xQvP2Hif/PFuEphBRmdxAN7Cp+gX6kHYmIijPe10eI0dTG/L0nR/r3UPUt9vubUnLW0cnYnimQ0FW5A1ANXN4LdCO+R3jFONsu99qpw/7uqrpJ1vUVpEvLu8fTg==","appId":"wx503cf8ab31f83dd4","signType":"RSA","nonceStr":"RKjdY0O5yroLPnEjXmTMtAEFIq2AhD63"}
}
				invokePayment(res.data)
					.then(resolve)
					.catch(err => {
						handlePaymentError(err);
						reject(err);
					});

		// 1. 获取支付参数
		// totalFee: amount, // platform: getPlatform() // 自动识别平台
		// request(api.weChatPayment, data, 'POST', 'application/json;charset=UTF-8')
		// 	.then(res => {
		// 		// 2. 调用平台支付
				// invokePayment(res.data)
				// 	.then(resolve)
				// 	.catch(err => {
				// 		handlePaymentError(err);
				// 		reject(err);
				// 	});
		// 	})
		// 	.catch(err => {
		// 		handlePaymentError(err);
		// 		reject(err);
		// 	});
	});
}

// ==================== 内部方法 ====================
function getPlatform() {
	// #ifdef MP-WEIXIN
	return 'miniprogram';
	// #endif
	// #ifdef APP-PLUS
	return 'app';
	// #endif
	// #ifdef H5
	return 'h5';
	// #endif
}

function invokePayment(payData) {
	return new Promise((resolve, reject) => {
		// #ifdef MP-WEIXIN
		uni.requestPayment({
			provider: 'wxpay',
			...payData, // 直接展开小程序所需参数
			success: (res) => {
				uni.showToast({
					title: '支付成功'
				});
				resolve(res);
			},
			fail: (err) => {
				reject(new Error(formatError(err)));
			}
		});
		// #endif

		// #ifdef APP-PLUS
		uni.requestPayment({
			provider: 'wxpay',
			orderInfo: payData.orderInfo,
			success: resolve,
			fail: (err) => {
				reject(new Error(formatError(err)));
			}
		});
		// #endif

		// #ifdef H5
		if (typeof WeixinJSBridge === 'undefined') {
			return reject(new Error('请在微信浏览器中打开'));
		}

		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',
			payData,
			(res) => {
				if (res.err_msg === 'get_brand_wcpay_request:ok') {
					resolve(res);
				} else {
					reject(new Error(res.err_msg || '支付失败'));
				}
			}
		);
		// #endif
	});
}

function formatError(err) {
	if (err.errMsg) {
		if (err.errMsg.includes('cancel')) return '支付已取消';
		if (err.errMsg.includes('fail')) return '支付失败';
	}
	return err.message || '支付异常';
}

function handlePaymentError(err) {
	console.error('[支付错误]', err);
	uni.showToast({
		title: err.message,
		icon: 'none',
		duration: 3000
	});
}

// 微信
// export function userAddr(userId, data={}) {
// 	return request(api.userAddr(userId), data, 'GET', 'application/json;charset=UTF-8')
// }