<script>
	import {
		getDictByKey,
		getAppVersion,
		getRealLinkDomainName
	} from '@/api/common';
	import {
		appCheckUdate,
		openDownload
	} from '@/utils/APPUpdate.js';
	import {
		getUserInfo,
		getPushLogRead
	} from '@/api/user';
	import {
		mapGetters,
		mapActions
	} from 'vuex';

	let updateDownloadTask = null;
	let notificationIntance = null;
	let pausing = false;
	let innerAudioContext;
	let notification;
	let uPushPlugin;

	// #ifdef APP-PLUS
	import {
		getTlsSig
	} from '@/api/common.js';
	import {
		qconfig
	} from './utils/config';
	// import { getImAdminToken } from '@/pages_im/api/imApi';
	// import { ar } from 'date-fns/locale';
	// #endif


	let offlineMsg = null;
	let offlineHandleNewMsg = null;

	export default {
		globalData: {
			wsUrl: 'ws://doctor.ai.cdwjyyh.com',
			corpId: 'ww70ac72e824957fc9', //客服企业id
			miniprogamId: "gh_7a6a32e5ef61",
		},
		onLaunch: function(options) {
			uni.hideTabBar();
			//设置字体大小
			// let fontsize = uni.getStorageSync('fontSize');
			// if (fontsize) {
			// 	uni.setStorageSync('fontSize', fontsize);
			// } 
			// else {
			// 	let scale = this.getSystemFontScale();
			// 	let oriFontSize = 18;
			// 	fontsize = oriFontSize * scale;
			// 	if (fontsize < oriFontSize) {
			// 		fontsize = oriFontSize;
			// 	}
			// 	if (fontsize < 16) {
			// 		fontsize = 16;
			// 	}
			// 	if (fontsize >= 21) {
			// 		fontsize = 21;
			// 	}
			// 	uni.setStorageSync('fontSize', fontsize);
			// }

			uni.removeStorageSync('openUrl');
			if (this.$isLogin()) {
				uni.setStorageSync("onLaunch", 1);
			}
			let that = this;

			// #ifdef APP-PLUS

			//#endif
		},
		onLoad() {

		},
		onShow() {

			var that = this;
			// #ifdef APP-PLUS
			if (uni.$u.os() === 'android') {
				this.checkUpdateApp();
			}
			// this.checkPermission(["android.permission.BLUETOOTH_CONNECT"],"蓝牙",function(){
			// 		console.log('checkPermission BLUETOOTH_CONNECT OK!');
			// });

			// #endif

		},

		onHide() {
			console.log("qxj onHide");
			uni.removeStorageSync('onLaunch');
			// if(uni.$u.os() === 'android'){
			// 	IMSDK.asyncApi(IMSDK.IMMethods.SetAppBackgroundStatus, IMSDK.uuid(), true);
			// 	// meetingModule?.onListenerAppBackground(true);
			// }

		},
		computed: {

		},
		methods: {
			checkPermission(permissions, permissionName, success) {
				plus.android.requestPermissions(permissions, function(e) {
					if (e.deniedAlways.length > 0) { //权限被永久拒绝
						// 弹出提示框解释为何需要读写手机储存权限，引导用户打开设置页面开启
						uni.showModal({
							title: permissionName + '权限',
							content: '您可能拒绝了' + permissionName + '权限或您的设备无需设置权限',
							success: function(res) {
								if (res.confirm) {
									// console.log('用户点击确定');
								} else if (res.cancel) {
									// console.log('用户点击取消');
								}
							}
						});
					}
					if (e.deniedPresent.length > 0) { //权限被临时拒绝
						plus.android.requestPermissions(permissions)
					}
					if (e.granted.length > 0) { //权限被允许
						if (success) {
							success();
						}
					}
				}, function(e) {
					
				});
			},
			// 处理Launch信息
			handlerLaunchMsg() {
				let that = this;
				// 监听通知点击事件
				plus.push.addEventListener('click', function(msg) {
					console.log('应用通过点击通知启动:', msg);
					let newServerMsg = msg.payload;
					// uni.switchTab({url: 'pages_im/pages/conversation/conversationList/index'});
					//uni.$u.throttle(() => that.notifyGoToChat(newServerMsg), 1000);
				});
				// 获取启动时的通知
				plus.push.getClientInfoAsync(function(info) {
					console.log("qxj getClientInfoAsync", info);
					if (info.id && info.id == "unipush") { //荣耀离线推送
						offlineMsg = info;
					}
					if (info.title && info.content && info.payload) {
						// uni.switchTab({url: 'pages_im/pages/conversation/conversationList/index'});
					}
					if (info.launch && info.launch.payload) {
						let newServerMsg = info.launch.payload;
						console.log('应用通过通知启动:', info);
						// uni.switchTab({url: 'pages_im/pages/conversation/conversationList/index'});
						//uni.$u.throttle(() => that.notifyGoToChat(newServerMsg), 1000);
					}
				}, function(err) {
					console.error("Error getting client info:", err);
				});
			},

			getSystemFontScale: function() {
				let scale = 1;
				if (uni.getSystemInfoSync) {
					let systemInfo = uni.getSystemInfoSync();
					if (systemInfo.fontSizeSetting) {
						scale = systemInfo.fontSizeSetting / 16; // 16 是默认字体大小
					}
				}
				return scale;
			},
			adjustFontSize: function() {
				let scale = getSystemFontScale();
				let rootElement = document.documentElement;
				rootElement.style.fontSize = 16 * scale + 'px';
			},
			/* 检查更新 在线更新 */
			checkUpdateApp() {
				//  获取manifest.json里的配置信息
				let that = this;
				plus.runtime.getProperty(plus.runtime.appid, function(widgetinfo) {
					// console.log("qxj widgetinfo:"+JSON.stringify(widgetinfo));
					// 可以根据manifest.json里的应用名称来进行针对性的APP升级
					if (widgetinfo.name == qconfig.appName) {
						//APP名称
						// 获取manifest.json里的版本号
						let platform = uni.getSystemInfoSync().platform;
						let isAndroid = platform == 'android';
						let type = isAndroid ? 5 : 2;
						// console.log("qxj widgetinfo:"+type);
						getAppVersion(type).then((srcData) => {
									if (srcData.code == 200) {
										//console.log("qxj widgetinfo:"+srcData);
										let data = srcData.data;
										let version = widgetinfo.versionCode, //用户当前app版本
											appVersion = data.versionCode, //升级包版本
											appName = widgetinfo.name, //app名称
											isForce = data.isForce, //是否强制热更新
											updateConfig = JSON.parse(data.updateConfig),
											appurl = data.url, //升级包地址
											intro = data.note; //升级包提示
										//如果用户版本号小于升级包版本号，先升级
										let afterVer = false;
										if (plus.runtime.channel == 'baidu') {
											afterVer = that.$qconfig.isAppStore ? updateConfig.baidu : false;
										} else if (plus.runtime.channel == 'huawei') {
											afterVer = that.$qconfig.isAppStore ? updateConfig.huawei : false;
										} else if (plus.runtime.channel == 'xiaomi') {
											afterVer = that.$qconfig.isAppStore ? updateConfig.xiaomi : false;
										} else if (plus.runtime.channel == 'yyb') {
											afterVer = that.$qconfig.isAppStore ? updateConfig.yyb : false;
										} else {
											afterVer = that.$qconfig.isAppStore ? isForce : true;
										}
										if (data && version < appVersion && afterVer) {
											uni.showModal({
												title: '更新提示',
												confirmText: '立即升级',
												content: intro,
												cancelText: '确定',
												confirmText: '取消',
												success: (res) => {
													if (res.cancel) {
														openDownload(srcData.data);
													} else if (res.confirm) {
														if (isForce == 1) {
															uni.showToast({
																title: '请先升级APP版本',
																icon: 'none',
																duration: 2000
															});
															//退出app
															setTimeout(function() {
																plus.runtime.quit();
															}, 2000);
														}
													}
												},
												fail: () => {
													uni.hideLoading();
												}
											});
										}
									}
								},
								(rej) => {}
							)
							.catch(() => {
								//联网失败, 结束加载
								this.mescroll.endErr();
							});
					}
				});
			}

		}
	};
</script>

<style lang="scss">
	/*每个页面公共css */
	@import '@/uni_modules/uview-plus/index.scss';

	/*#ifndef APP-NVUE*/

	view {
		box-sizing: border-box;
	}

	.ellipsis {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.ellipsis2 {
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
	}

	uni-modal {
		z-index: 1100;
	}


	.no-data-box {
		height: 100%;
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;

		image {
			width: 264upx;
			height: 212upx;
		}

		.empty-title {
			margin-top: 20rpx;
			font-size: 28rpx;
			color: gray;
		}
	}

	/*#endif*/
</style>

<style lang="less">
	/*每个页面公共css */
	// @import './assets/iconfont/iconfont.css';
	@import './assets/css/common.less';
	/* 全局flex样式 */
	@import './common/css/flexCommon.css';

	/*引入全局补充样式*/
	@import './assets/css/czy/es.1.base.css';
	@import './assets/css/czy/es.2.color.css';
	@import './assets/css/czy/es.3.icon.css';
	@import './assets/css/czy/es.4.view.css';

	.textOne {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	.textTwo {
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}
</style>