<script>
	// APP 和 小程序平台
	// #ifdef  APP-PLUS || MP-WEIXIN

	import COS from 'cos-wx-sdk-v5';
	// #endif



	// #ifdef APP-PLUS
	import Aegis from 'aegis-weex-sdk';
	// #endif

	// #ifdef MP-WEIXIN
	import Aegis from 'aegis-mp-sdk';
	// #endif

	// #ifdef H5
	import Aegis from 'aegis-web-sdk';
	// #endif
	import logger from './utils/logger'; // app.js
	import {
		genTestUserSig
	} from './debug/GenerateTestUserSig.js';
	import printer from './components/print/index.js'; // app.js
	// const aegis = new Aegis({
	// 	id: 'iHWefAYqKznuxWjLnr', // 项目key
	// 	reportApiSpeed: true, // 接口测速
	// });
	// uni.$aegis = aegis
	// 首先需要通过 uni.requireNativePlugin("ModuleName") 获取 module
	// #ifdef APP-PLUS
	var jpushModule = uni.requireNativePlugin("JG-JPush");
	var audioObj = uni.getBackgroundAudioManager();
	// #endif

	export default {

		globalData: {
			// #ifdef H5
			// mainurl: "/api/?s=",
			// #endif
			// #ifndef H5
			mainurl: 'https://hbkuaishi.com/hiver',
			// mainurl: 'http://192.168.100.32:8888/hiver',
			// #endif
			// weburl: 'https://taketest.sdwanyue.com/',
			weburl: 'https://takeout.sdwanyue.com/',
			// weburl: 'https://take.sdwanyue.com/',
			userinfo: '',
			safeAreaInsets: '',
			statusBarHeight: 0, //状态栏高度
			screenHeight: 0,
			windowHeight: 0, //页面高度
			pageHeight: 0,
			//安全区域
			safeArea: '',
			safeAreaBottom: 0,
			top: 0, //顶部高度
			menuButtonWidth: 0, //顶部按钮宽度
			menuButtonLeft: 0, //顶部按钮距离
			menuButtonHeight: 44,
			_i18n: '',
			$t: '',
			userInfo: {},
			registrationID: '',
			printData: [], // 打印任务队列，按顺序存储待打印的通知数据
			isPrinting: false, // 标记当前是否正在打印，防止并发
		},
		onLaunch: function() {
			let context = this;
			//这里是热更新的代码
			// #ifdef APP-PLUS  
			plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {

				// uni.request({  
				//     url: '',  
				//     data: {  
				//         version: widgetInfo.version,  
				//         name: widgetInfo.name  
				//     },  
				//     success: (result) => {  
				//         var data = result.data;  
				//         if (data.update && data.wgtUrl) {  
				//             uni.downloadFile({  
				//                 url: data.wgtUrl,  
				//                 success: (downloadResult) => {  
				//                     if (downloadResult.statusCode === 200) {  
				//                         plus.runtime.install(downloadResult.tempFilePath, {  
				//                             force: false  
				//                         }, function() {  
				//                             console.log('install success...');  
				//                             plus.runtime.restart();  
				//                         }, function(e) {  
				//                             console.error('install fail...');  
				//                         });  
				//                     }  
				//                 }  
				//             });  
				//         }  
				//     }  
				// });  
			});
			// #endif
			this.globalData._i18n = this.$i18n //这是原型链上的$i18n
			this.globalData.$t = function(str) {
				let $i18n = context.globalData.$i18n //这里去拿global的i18n
				return context.$t(str)
			}
			this.getAreaSize()
			// this.getRegistrationID()
			// #ifdef APP-PLUS
			jpushModule.initJPushService();

			jpushModule.setLoggerEnable(true);
			plus.screen.lockOrientation("portrait-primary");
			//监听 极光推送连接状态
			this.getNotificationEnabled();
			jpushModule.addConnectEventListener(result => {
				let connectEnable = result.connectEnable
				if (connectEnable == true) {
					setTimeout(() => {
						this.getRegistrationID();
					}, 1000);
				} else {

				}
			});
			jpushModule.addNotificationListener(result => { //极光推送的消息通知回调
				jpushModule.setBadge(0);
				plus.runtime.setBadgeNumber(0);
				let notificationEventType = result.notificationEventType
				let woopId = result.extras && result.extras.dataType === 'woop' && result.extras.value;
				//用户点击了通知消息
				if (result.notificationEventType === 'notificationOpened') {
					if (this.NB.isAndroidOrIOS() == 'iOS') {
						this.handlePushClick(result.ios.inAppExtras);
					} else {
						this.handlePushClick(result.android.inAppExtras);
					}

				}
				//用户收到了通知消息
				if (result.notificationEventType == 'notificationArrived') {
					if (result.content.includes('订单出餐已超时')) {
						this.onPlayAudio(2)
					} else if (result.content.includes('您有一笔配送订单无人接单')) {
						this.onPlayAudio(5)
					} else if (result.content.includes('您有一笔新的指定配送单，请及时接单')) {
						this.onPlayAudio(10)
					} else if (result.content.includes('您有一笔配送中订单用户申请退款')) {
						this.onPlayAudio(11)
					} else if (result.content.includes('抢单大厅来新单啦')) {
						this.onPlayAudio(12)
					} else if (result.content.includes('您有中转配送订单超时未送达中转点')) {
						this.onPlayAudio(7)
					} else if (result.content.includes('您有一笔订单用户申请售后，请尽快处理')) {
						this.onPlayAudio(8)
					} else if (result.content.includes('您有一个后台指派单，请及时查看')) {
						this.onPlayAudio(13)
					} else {
						if (result.content.includes('您有一笔新的订单')) {
							this.onPlayAudio(4)
						} else if (result.content.includes('您有一笔新的到店订单')) {
							this.onPlayAudio(3)
						} else if (result.content.includes('您有一笔订单申请退款')) {
							this.onPlayAudio(1)
						} else if (result.content.includes('您有一笔商家自配送订单，请立即处理')) {
							this.onPlayAudio(6)
						} else if (result.content.includes('您有一笔预约订单可以出餐啦')) {
							this.onPlayAudio(9)
						}
						// 将消息数据推入打印队列
						this.globalData.printData.push(JSON.parse(result.android.inAppExtras))
						// 若当前未在打印，则启动队列处理
						if (!this.globalData.isPrinting) {
							this.processPrintQueue()
						}
					}
				}

			});
			jpushModule.isPushStopped(res => {
				// code   0已停止推送  1未停止推送
				const {
					code
				} = res
			})
			//#endif



			// 将原生插件挂载在 uni 上
			// #ifdef APP-PLUS
			// uni.$TUICalling = TUICalling;
			// #endif
			// 如果您已创建了 tim，请将 tim 实例挂载在 wx 上，且不可以修改 wx.$TIM（修改变量可能导致 TUICalling 组件无法正常使用）, 完成 TUICalling 初始化，
			// 如果您没有创建，可以不传

			// #ifdef APP-PLUS
			// if (this.NB.isAndroidOrIOS() == 'iOS') {
			// 	this.globalData.GaoDeAppKey = 'b1aadb7457eae6aa40a0c8ed58ae0456'
			// } else {
			// 	this.globalData.GaoDeAppKey = '43cff70e1deb9455185e2c8cf8363aec'
			// }
			if (this.NB.isAndroidOrIOS() == 'iOS') {
				this.globalData.GaoDeAppKey = 'f32a7750d2a2c3d7459f85185c867c4f'
			} else {
				this.globalData.GaoDeAppKey = 'a88be362cab2d0f18608bedcc47ace9a'
			}
			this.globalData.GaoDeKey_amapkey = '97a3e0a8bf3f3ca77193b81c48d92ee2'
			// #endif
			// #ifdef MP-WEIXIN
			this.globalData.GaoDeKey_amapkey = '52de86da47be2ea547c37dd382025a0c'
			// #endif
			if(uni.getStorageSync('peisongyuan')) return; 
			if (!uni.getStorageSync('bluetoothDeviceId')) {
				uni.showModal({
					title: '提示',
					content: '您还没有连接打印机，将无法为您打印小票！',
					confirmText: '连接蓝牙',
					cancelText: '暂不连接',
					success: function(res) {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/myCenter/setPrint'
							})
						}
					}
				});
			}
		},
		computed: {
			i18n() {
				return this.$t('index')
			},
		},
		methods: {
			processPrintQueue() {
				if (this.globalData.printData.length === 0) {
					this.globalData.isPrinting = false
					return
				}
				this.globalData.isPrinting = true
				printer.getData(() => {
					this.globalData.printData.shift()
					this.processPrintQueue()
				})
			},
			// 统一处理推送点击逻辑
			handlePushClick(extras) {
				if (!extras) return;
				let data = extras;
				if (typeof data === 'string') {
					try {
						data = JSON.parse(data);
					} catch (e) {
						return;
					}
				}
				const targetUrl = `/pages/shop/orderDetail?id=${data.order_id}`;
				uni.setStorageSync('push_jump_url', targetUrl);
				const pages = getCurrentPages();
				if (pages.length > 0) {
					setTimeout(() => {
						this.executeJump(targetUrl);
					}, 300);
				}
			},
			// 执行跳转
			executeJump(url) {
				uni.navigateTo({
					url: url,
					fail: (err) => {
						uni.redirectTo({
							url: url
						});
					}
				});
			},
			onPlayAudio(type) {
				var audio = null;
				audio = uni.getBackgroundAudioManager();
				audio.title = "通知音";
				audio.singer = "通知音";
				// #ifdef APP-PLUS
				if (type == 1) { //退款
					audio.src = 'https://jewel-shop.oss-cn-beijing.aliyuncs.com/cb24e35cfb1b48a58823633f23398d45.mp3';
				} else if (type == 2) { //超时
					audio.src = 'https://jewel-shop.oss-cn-beijing.aliyuncs.com/4d20a1cbc92c42f4b70de1b9dacb7979.mp3';
				} else if (type == 3) { //到店订单
					audio.src = 'https://jewel-shop.oss-cn-beijing.aliyuncs.com/3ced308cf72348a3adeb07d003ced5f3.mp3';
				} else if (type == 4) { //新订单
					audio.src = 'https://jewel-shop.oss-cn-beijing.aliyuncs.com/c60ef3944e58461fbe7ce23ae38c70a2.mp3';
				} else if (type == 5) { //无人接单
					audio.src = 'https://jewel-shop.oss-cn-beijing.aliyuncs.com/e41404ed7c964ec4a203f0a7404585af.mp3';
				} else if (type == 6) { //自配送
					audio.src = 'https://jewel-shop.oss-cn-beijing.aliyuncs.com/7050e7134dc24f56992fe405605d480e.mp3';
				} else if (type == 7) { //中转超时
					audio.src = 'https://jewel-shop.oss-cn-beijing.aliyuncs.com/2fe04974ece245a79cd078dc7def773d.mp3';
				} else if (type == 8) { //申请售后
					audio.src = 'https://jewel-shop.oss-cn-beijing.aliyuncs.com/1f3bfb020a9c4eb9af7c11e850538f56.mp3';
				} else if (type == 9) { //预约订单可以出餐
					audio.src = 'https://jewel-shop.oss-cn-beijing.aliyuncs.com/1b6b61995c214e0799feaa4f7d4fe0fa.mp3';
				} else if (type == 10) { //指定配送单，请及时接单
					audio.src = 'https://jewel-shop.oss-cn-beijing.aliyuncs.com/53ef5cd4eb924475a20f63d70d698b16.mp3';
				} else if (type == 11) { //配送中订单用户申请退款
					audio.src = 'https://jewel-shop.oss-cn-beijing.aliyuncs.com/b602782769d04fa09eb7a09557996b6a.mp3';
				} else if (type == 12) { //抢单大厅来新单啦
					audio.src = 'https://jewel-shop.oss-cn-beijing.aliyuncs.com/a6bdf5b02fc249ac924e8da277ac5bfc.mp3';
				} else if (type == 13) { //后台指派单
					audio.src = 'https://jewel-shop.oss-cn-beijing.aliyuncs.com/645c2bbb398d4e2e95490c66e5ba6d2b.mp3';
				}
				
				// #endif

				audio.play();
				audio.onEnded(function(res) {
					audio = null;
				})
			},
			getAreaSize() {
				var res = uni.getSystemInfoSync()
				this.globalData.safeAreaInsets = res.safeAreaInsets
				this.globalData.windowHeight = res.windowHeight
				this.globalData.screenHeight = res.screenHeight
				this.globalData.safeArea = res.safeArea
				this.globalData.top = res.safeArea.top
				this.globalData.statusBarHeight = res.statusBarHeight
				this.globalData.pageHeight = this.globalData.windowHeight
				this.globalData.safeAreaBottom = res.screenHeight - res.safeArea.bottom
				this.globalData.pageHeight = this.globalData.windowHeight + 44 + this.globalData.top

			},
			getRegistrationID() { //获取registerID
				jpushModule.getRegistrationID(result => {
					let registerID = result.registerID
					if (result && result.registerID) {
						this.globalData.registrationID = registerID
						uni.setStorageSync("registerID", registerID)
					}
					// uni.setStorageSync("signPerson", result.signPerson)
				})
			},
			getNotificationEnabled() {
				if (uni.getSystemInfoSync().platform == "ios") {
					jpushModule.requestNotificationAuthorization((result) => {
						let status = result.status
						if (status < 2) {
							this.noticMsgTool()
						}
					})
				} else {
					jpushModule.isNotificationEnabled((result) => {
						if (result.code == 0) {
							this.noticMsgTool()
						}
					})
				}
			},
			noticMsgTool() {
				if (uni.getSystemInfoSync().platform == "ios") {
					uni.showModal({
						title: '通知权限开启提醒',
						content: '您还没有开启通知权限，无法接受到消息通知，请前往设置！',
						showCancel: false,
						confirmText: '去设置',
						success: function(res) {
							if (res.confirm) {
								var app = plus.ios.invoke('UIApplication', 'sharedApplication');
								var setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:');
								plus.ios.invoke(app, 'openURL:', setting);
								plus.ios.deleteObject(setting);
								plus.ios.deleteObject(app);
							}
						}
					});
				} else {
					var main = plus.android.runtimeMainActivity();
					var pkName = main.getPackageName();
					var uid = main.getApplicationInfo().plusGetAttribute("uid");
					uni.showModal({
						title: '通知权限开启提醒',
						content: '您还没有开启通知权限，无法接受到消息通知，请前往设置！',
						showCancel: false,
						confirmText: '去设置',
						success: function(res) {
							if (res.confirm) {
								var Intent = plus.android.importClass('android.content.Intent');
								var Build = plus.android.importClass("android.os.Build");

								if (Build.VERSION.SDK_INT >= 26) {
									var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
									intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
								} else if (Build.VERSION.SDK_INT >= 21) {
									var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
									intent.putExtra("app_package", pkName);
									intent.putExtra("app_uid", uid);
								} else {
									intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
									var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
									intent.setData(uri);
								}
								main.startActivity(intent);
							}
						}
					});
				}
			},
		},
	}
</script>

<style>
	@import url("./App.css");
</style>