<script>
	import chat from '@/libs/chat.js'
	import {
		getAppVersion
	} from '@/api/common.js'
	import {
		getMessageDetail,
		checkInfo,
	} from '@/api/message.js'
	import {
		useLocale
	} from '@/locale/useLocale';
	import {
		useChatStore
	} from '@/store/modules/chat'
	import {
		useUserStore
	} from '@/store/modules/user'
	const chatStore = useChatStore()

	export default {
		data() {
			return {
				version: 0,
				resVersion: 0,
				modileSystem: 'android',
				Apk: ''
			}
		},
		onLaunch() {
			/* 空路由拦截 */
			uni.addInterceptor("reLaunch", {
				invoke(e) {
					if (e.url == "/") {
						history.back();
						return false;
					}
				},
			});
			// #ifndef  MP || H5
			/* 获取设备信息 */
			uni.getSystemInfo({
				success(res) {
					uni.setStorageSync('systemInfo', res.ua)
				}
			})

			const token = uni.getStorageSync("token");
			if (!token) return
			chat.initSocket()
			const userStore = useUserStore()
			userStore.getCurrentUser().then(res => {
				const {
					initLocale
				} = useLocale();
				initLocale()
			})

			this.handlePush()

			// this.getAppVersion()

			// 开启消息通知弹窗
			this.setPermissions()
			// #endif

		},
		methods: {
			handlePush() {
				// 获取unipushID
				uni.getPushClientId({
					success: (res) => {
						uni.setStorageSync('push_clientid', res.cid)
					},
					fail(err) {}
				})

				// 处理推送消息
				uni.onPushMessage(res => {
					const data = res.data.payload.data
					// 公告跟系统消息
					if (data.messageType == 1 || data.messageType == 3) {
						uni.navigateTo({
							url: '/pages/message/messageDetail/index?id=' + data.id
						});
						return
					}
					// 流程消息（包括委托）
					if (data.messageType == 2) {
						return this.toFlow(data.id)
					}
					// 日程消息
					if (data.messageType == 4) {
						return this.toSchedule(data.id)
					}
					// 聊天
					if (data.messageType == 100) {
						return this.toIm(res.data.payload)
					}
				})
			},
			setPermissions() {
				if (plus.os.name == 'Android') { // 判断是Android
					var main = plus.android.runtimeMainActivity();
					var pkName = main.getPackageName();
					var uid = main.getApplicationInfo().plusGetAttribute("uid");
					var NotificationManagerCompat = plus.android.importClass(
						"android.support.v4.app.NotificationManagerCompat");
					//android.support.v4升级为androidx
					if (NotificationManagerCompat == null) {
						NotificationManagerCompat = plus.android.importClass(
							"androidx.core.app.NotificationManagerCompat");
					}
					var areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled();
					// 未开通‘允许通知’权限，则弹窗提醒开通，并点击确认后，跳转到系统设置页面进行设置  
					if (!areNotificationsEnabled) {
						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");
									//android 8.0引导  
									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) { //android 5.0-7.0  
										var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
										intent.putExtra("app_package", pkName);
										intent.putExtra("app_uid", uid);
									} else { //(<21)其他--跳转到该应用管理的详情页  
										intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
										var uri = Uri.fromParts("package", mainActivity.getPackageName(),
											null);
										intent.setData(uri);
									}
									// 跳转到该应用的系统通知设置页  
									main.startActivity(intent);
								}
							}
						});
					}
				} else if (plus.os.name == 'iOS') { // 判断是ISO
					var isOn = undefined;
					var types = 0;
					var app = plus.ios.invoke('UIApplication', 'sharedApplication');
					var settings = plus.ios.invoke(app, 'currentUserNotificationSettings');
					if (settings) {
						types = settings.plusGetAttribute('types');
						plus.ios.deleteObject(settings);
					} else {
						types = plus.ios.invoke(app, 'enabledRemoteNotificationTypes');
					}
					plus.ios.deleteObject(app);
					isOn = (0 != types);
					if (isOn == false) {
						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);
								}
							}
						});
					}
				}
			},
			getAppVersion() {
				getAppVersion().then(res => {
					let data = res.data.sysVersion || ''
					const matches = data.match(/(\d+\.\d+\.\d+)/);
					if (matches && matches.length > 0) this.Apk =
						`https://cdn.jnpfsoft.com/apk/Android-java-${matches[0]}.apk`
					data.trim();
					this.version = Number(data.replace(/[^0-9]/ig, ""))
					this.$nextTick(() => {
						this.onUpdate()
					})
				}).catch((err) => {})
			},
			onUpdate() {
				plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
					let resVersion = this.define.sysVersion;
					resVersion.trim();
					this.resVersion = Number(resVersion.replace(/[^0-9]/ig, ""))
					if (this.version != this.resVersion) {
						process.env.NODE_ENV === "production" ?
							uni.setStorageSync('isUpdate', 1) : uni.removeStorageSync('isUpdate')
						uni.showModal({ //提醒用户更新
							title: "立即更新版本",
							success: (res) => {
								if (res.confirm) {
									uni.removeStorageSync('isUpdate')
									let system = plus.os.name;
									if (system === 'Android') {
										// let url = devLanguage ? javaApk : dotNetApk;
										if (!this.Apk) return this.$u.toast('下载链接为空')
										plus.runtime.openURL(this.Apk)
										// uni.downloadFile({
										// 	//下载地址
										// 	url: url,
										// 	success: data => {
										// 		if (data.statusCode === 200) {
										// 			plus.runtime.install(data
										// 				.tempFilePath, {
										// 					force: false
										// 				},
										// 				function() {
										// 					plus.runtime
										// 						.restart();
										// 				});
										// 		}
										// 	}
										// })
									} else {
										plus.runtime.launchApplication({
											action: `itms-apps://itunes.apple.com/cn/app/id${'appleId自行配置'}`
										}, function(e) {});
									}
								} else if (res.cancel) {
									if (this.modileSystem == 'ios') {
										plus.ios.import("UIApplication")
											.sharedApplication()
											.performSelector("exit")
									} else if (this.modileSystem == 'android') {
										plus.runtime.quit();
									}
								}
							}
						})
					}
				})
			},
			// 打开聊天页面
			toIm(item) {
				chatStore.reduceBadgeNum(0)
				uni.navigateTo({
					url: '/pages/message/im/index?name=' + item.realName + '/' + item.account + '&formUserId=' +
						item.formUserId +
						'&headIcon=' +
						item
						.headIcon
				})
			},
			// 打开日程页面
			toSchedule(id) {
				getMessageDetail(id).then(res => {
					chatStore.setMsgInfoNum()
					let bodyText = res.data.bodyText ? JSON.parse(res.data.bodyText) : {};
					if (bodyText.type == 3) return
					let groupId = bodyText.groupId || ''
					uni.navigateTo({
						url: '/pages/workFlow/schedule/detail?groupId=' + groupId +
							'&id=' + bodyText.id
					});
				})
			},
			// 打开流程页面
			toFlow(id) {
				getMessageDetail(id).then(res => {
					chatStore.setMsgInfoNum()
					let bodyText = res.data.bodyText ? JSON.parse(res.data.bodyText) : {};
					if (res.data.flowType == 2) {
						let url = '/pages/workFlow/entrustAgent/index'
						url = bodyText.type == 1 ? url + '?index=1' : url + '?index=2'
						uni.navigateTo({
							url: url
						});
						return
					}
					let config = {
						fullName: res.data.title,
						id: bodyText.operatorId || res.data.id,
						...bodyText
					}
					checkInfo(bodyText.operatorId || config.taskId, config.opType).then(res => {
						config.opType = res.data.opType;
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/workFlow/flowBefore/index?config=' +
									this.jnpf.base64.encode(JSON.stringify(config))
							});
						}, 300)
					})
				})
			}
		}
	}
</script>

<style lang="scss">
	/*每个页面公共css */
	@import "@/uni_modules/vk-uview-ui/index.scss";
	@import "@/assets/iconfont/ym/iconfont.css";
	@import "@/assets/iconfont/custom/iconfont.css";
	@import "@/assets/scss/common.scss";
	@import "@/assets/scss/components.scss";
</style>