import BasePlatform from './BasePlatform';
import RequestManager from '@/common/request.js'
import {
	sleep,
	parseQueryString
} from '@/common/util.js'
import {
	getOrderStatus
} from '@/common/server/order.js'
/**
 * 小程序平台
 */
class MiniProgramPlatform extends BasePlatform {
	constructor() {
		super();
		this.code = 'MP-WEIXIN';
		this.env = 'miniProgram';

	}

	getPayData(url, data) {
		return data;
	}
	pay({
		data
	}, event) {
		console.log(this, event);

		return new Promise(async (resolve, reject) => {
			let config = await this.getConfig();
			if (config.isWebPay) {
				console.log('开启H5支付', data);
				console.log(data);
				let fullPath = event.$scope.$page.fullPath;
				//页面路径
				console.log(fullPath, "fullPath");

				let tips = data.tips ? data.tips : "您即将进入客服聊天界面完成支付，也可前往「我的」页面下载官方APP，享受更便捷的购物及充值服务。";
				const res = await event.$refs.payDialog.showDialogContact("支付提示", tips, "前往支付");
				if (res == 'success') {
					// resolve('success');
					console.log(data.data, 'data.data');
					let url = data.requestPay;
					await sleep(500);
					let payPostData = data.data;
					payPostData['return_url'] = fullPath;
					let respay = await RequestManager.post(url, payPostData, false);

					if (respay.status === 1) {
						event.$refs.payDialog.showDialogHand("支付提示",
							"支付成功后，请点击「支付已完成」按钮查看所购商品。如支付完成1分钟后仍显示异常，请关闭当前窗口，前往「我的」-「消费记录」查看订单状态。",
							"支付已完成", "关闭", async () => {
								let resPayStatus = await getOrderStatus(data.data['order_num']);
								if (resPayStatus.data == 1) {
									event.$refs.payDialog.closeHand();
									resolve('success');
								} else {
									uni.showToast({
										title: resPayStatus.msg,
										icon: 'none',
										duration: 1000
									});
								}
							});

					}


				}


			}
			let provider = "weixin";
			uni.requestPayment({
				provider,
				...data,
				success: res => {
					// console.log(res)
				},
				fail: err => {

				},
				complete: res => {
					console.log('complete (res)', res)
					if (res.errMsg == 'requestPayment:fail cancel') {
						uni.showToast({
							title: '取消支付',
							icon: 'none',
							duration: 500,
							success: () => {
								/* 取消订单 */
								resolve('cancel')
							}
						})


					}
					if (res.errMsg == 'requestPayment:ok') {
						uni.showToast({
							title: '支付成功',
							icon: 'success',
							duration: 500,
							success: () => {
								resolve('success')
							}
						})
					}
				}
			})
		})
	}

	share({
		title,
		desc,
		image,
		url
	}) {
		wx.showShareMenu({
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline']
		});
		// 监听用户点击分享按钮
		wx.onShareAppMessage(() => ({
			title,
			imageUrl: image
		}));
	}
	/**
	 * 选择地址
	 * @returns 
	 */
	chooseAddress() {
		return new Promise((resolve, reject) => {
			//#ifdef MP-WEIXIN
			uni.chooseAddress({
				success: res => {
					res.detailed_address = res.provinceName + res.cityName + res.countyName +
						res.detailInfo;
					resolve(res)
				},
				fail: err => {
					reject(err)
				}
			});
			//#endif
		});
	}
	downloadFile(url) {
		return new Promise((resolve, reject) => {
			// 下载图片到本地
			wx.downloadFile({
				url: url,
				success: (res) => {
					if (res.statusCode === 200) {
						const tempFilePath = res.tempFilePath; // 获取临时文件路径
						// 保存图片到相册
						wx.saveImageToPhotosAlbum({
							filePath: tempFilePath,
							success: () => {
								uni.showToast({
									title: '保存成功',
									icon: 'success',
								});
							},
							fail: (err) => {
								uni.showToast({
									title: '保存失败',
									icon: 'none',
								});
								console.error('保存失败', err);
							},
						});
					} else {
						uni.showToast({
							title: '图片下载失败',
							icon: 'none',
						});
						console.error('图片下载失败', res);
					}
				},
				fail: (err) => {
					uni.showToast({
						title: '图片下载失败',
						icon: 'none',
					});
					console.error('图片下载失败', err);
				},
			});
		});
	}
	AppLaunch(options) {
		this.getConfig();
		console.log("AppLaunch", options);
		const updateManager = uni.getUpdateManager();
		updateManager.onCheckForUpdate(function (res) {
			// 请求完新版本信息的回调
			console.log(res.hasUpdate);
		});
		updateManager.onUpdateReady(function (res) {
			uni.showModal({
				title: "更新提示",
				content: "新版本已经准备好，是否重启应用？",
				success(res) {
					if (res.confirm) {
						// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
						updateManager.applyUpdate();
					}
				},
			});
		});
		updateManager.onUpdateFailed(function (res) {
			// 新的版本下载失败
		});
		// setTimeout(() => {
		// 	const currentPage = getCurrentPages().pop();
		// 	console.log('currentPagecurrentPagecurrentPage', currentPage);
		// }, 300);

		// if (options != null && options.path == "pages/index/index") {
		// 	uni.switchTab({
		// 		url: '/pages/shouye/index'
		// 	});
		// }
	}
	async appData() {
		const t= await uni.getAccountInfoSync();
		console.log("getAccountInfoSync",t);
		await this.loadCacheData();
		uni.switchTab({
			url: '/pages/shouye/index'
		});
		// this.getConfig().then(res => {
		// 	console.log(res, 'res');
		// })
	}
	async getOrderNo(event) {
		return new Promise(async (resolve, reject) => {
			console.log(event.$scope.$page.fullPath, 'this.$scope.$page.fullPath');

			const query = parseQueryString(event.$scope.$page.fullPath);
			console.log(query, 'query');
			if (query.order_num) {
				let old_order_num = uni.getStorageSync('order_num');
				//判断是否已经获取过了
				if (old_order_num != query.order_num) {
					uni.showLoading({
						title: '获取订单中...'
					});
					uni.setStorageSync('order_num', query.order_num);
					await sleep(1500);
					uni.hideLoading();
					resolve(query.order_num);
				} else {
					console.log('重复执行获取订单');
					uni.hideLoading();
					resolve(null);
				}
			} else {
				uni.hideLoading();
				resolve(null);
			}
		});
	}
	delOrderNo() { }

	/**
	 * 重写获取用户中心菜单列表，添加微信小程序特有菜单
	 * @returns {Array} 菜单项数组
	 */
	getUserMenuList() {
		// 获取基础菜单列表
		const baseMenuList = super.getUserMenuList();

		// 添加客服菜单项（仅微信小程序）
		const customServiceMenu = {
			id: 9,
			show: true,
			title: '客服',
			icon: 'ms/s9.png',
			path: '',
			isCustomService: true,
			// 客服按钮不需要处理函数，由微信小程序原生组件处理
			handler: () => { }
		};

		// 将客服菜单插入到用户协议后面
		const agreementIndex = baseMenuList.findIndex(item => item.title === '用户协议');
		if (agreementIndex !== -1) {
			baseMenuList.splice(agreementIndex + 1, 0, customServiceMenu);
			return baseMenuList;
		}
		// 兜底：放到末尾
		return [...baseMenuList, customServiceMenu];
	}
	handleLogout() {
		uni.showModal({
			title: '提示',
			content: '确定要退出登录吗？',
			success: (res) => {
				if (res.confirm) {
					uni.removeStorageSync('token');
					uni.removeStorageSync('userinfo');
					uni.switchTab({
						url: '/pages/shouye/index'
					});
				}
			}
		});
	}
}
export default MiniProgramPlatform;