<script>
	import config from "./common/config";
	import {
		showNotification
	} from "@/utils/notify.js"
	import ws from "@/utils/websocket.js"; // WebSocket 封装类
	import NotifyPermission from "@/utils/notification-permission.js"



	/**
	 * Copyright (c) 2013-Now http://aidex.vip All rights reserved.
	 */
	export default {
		onLaunch() {
			// 国际化，设置当前语言
			if (this.vuex_locale) {
				this.$i18n.locale = this.vuex_locale;
				this.$u.api.lang({
					lang: this.vuex_locale
				});
			}


			// 监听登录成功
			uni.$on("loginSuccess", () => {
				// NotifyPermission.ensurePermission(() => {
				// 	// 权限已开，执行你的逻辑
				// 	this.initWebSocket()
				// })
				// // 仅在 Android 13+ 才需要
				if (plus.os.name === "Android" && parseInt(plus.os.version) >= 13) {
					var permission = "android.permission.POST_NOTIFICATIONS";
					// 请求权限
					plus.android.requestPermissions(
						[permission],
						(resultObj) => {
							this.initWebSocket()
						},
						(error) => {

						}
					);
				} else {
					this.initWebSocket()
				}
			})
			//只有在基座运行的情况下才能打印看到
			const clientInfo = plus.push.getClientInfo()
			console.log('clientid:', clientInfo.clientid)


			this.$store.commit('$uStore', {
				name: 'vuex_push_clientId',
				value: clientInfo.clientid
			});

			//监听系统通知栏点击事件
			plus.push.addEventListener("click", function(msg) {
				console.log("用户点击了推送消息：", msg);
				if (msg.payload) {
					if (msg.payload.type == 100) {
						uni.navigateTo({
							url: "/pages/sys/workbench/earlyWarning/warnDetail?item=" + msg.payload.data,
						});
					} else if (msg.payload.type == 200) {
						uni.navigateTo({
							url: "/pages/sys/workbench/order/orderDetail?item=" + msg.payload.data,
						});
					}
				}
			});
			// 收到推送（前台透传）
			// plus.push.addEventListener("receive", function(msg) {
			// 	console.log("收到推送消息：", msg);
			// });
			// 设置底部导航栏角标
			// uni.setTabBarBadge({
			//   index: 0,
			//   text: '3'
			// });
			// uni.removeTabBarBadge({
			//   index: 0
			// });
		},
		methods: {
			initWebSocket() {
				let url = this.vuex_config.baseUrl +
					'/resource/websocket?clientid=dab457a1ea14411787c240db05bb0832&Authorization=Bearer ' + this
					.vuex_token;
				console.log('t1', url)
				ws.connect(url)
				ws.setDispatchHandler(this.handleWsMessage)
				// this.ws = uni.connectSocket({
				// 	url: url, // 鉴权
				// 	success: () => console.log("连接请求已发送")
				// })

				// this.ws.onOpen(() => {
				// 	console.log("WebSocket已连接")
				// })

				// this.ws.onMessage((res) => {
				// 	console.log('t1', 1111111111)
				// 	this.handleWsMessage(res.data)
				// })

				// this.ws.onClose(() => {
				// 	console.log("WebSocket已关闭")
				// })

				// this.ws.onError((err) => {
				// 	console.error("WebSocket错误", err)
				// })
			},

			handleWsMessage(data) {
				if (data != 'ping') {
					try {
						showNotification(data.title, data.content, data)
						// const msg = JSON.parse(data)
						// console.log("收到消息:", msg)
						// uni.$emit("wsMessage", msg) // 分发消息
					} catch (e) {
						console.error("消息解析失败:", data)
					}
				}

			},

			closeWebSocket() {
				if (this.ws) {
					this.ws.close()
				}
			}
		}
	}
</script>
<style>
	@import url("~@/static/iconfont/iconfont.css");
</style>
<style lang="scss">
	@import "uview-ui/index.scss";
	@import "pages/common/aidex.scss";
</style>