<script>
	//#ifdef MP-ALIPAY
	import 'vant-aliapp/dist/__antmove/component/componentClass.js'
	import monitor from '@/utils/alipayLogger.js'
	//#endif
	import $http from "./utils/https";
	import Utils from "./utils/utils";
	import httpConfig from "./utils/httpConfig";
	import Cache from './utils/cache';
	import {
	  loginFun,
	  nearHospitalModalOpen,
	  getHospList
	} from "./utils/common";
	// #ifdef H5
	import wechath5 from "@/utils/wechath5";
	import baseConfig from "@/config/app";
	// #endif
	
	let userData = Cache.get('userData')
	export default {
		globalData: {
			miniVersion: '', // 小程序版本
			pubAccCode: '', // 公众号
			share: false, // 分享默认为false
			// #ifdef H5
			height: 50,
			// #endif
			// #ifndef H5
			height: 0,
			// #endif
			navHeight: 50,
			statusBarData: {},
			statusBarHeight: uni.getSystemInfoSync()['statusBarHeight'] || 10,
			tim: null,
			context: null,
			isLogOut: false,
			initTim: false,
			userData: {},
			docObj: {},
			locObj: {},
			patObj: {},
			schDate: "",
			backPage: 2,
			writeObj: {
				schDateKey: "",
				schTimeKey: "",
				fileList: [],
				disesTime: "",
				disesNote: ""
			},
			isUpdatePatList: false, // 是否需要更新就诊人列表数据
			SDKAPPID: +userData.imAppID || 0,
			SECRETKEY: userData.imSecret || '',
			reservationEntrance: "", // 预约入口标识
			platform: '', // 当前平台
			provider: '',
			appId: '2021004100602607', // 应用APPID
			alipayQuery: '' ,// 支付宝小程序关联普通二维码参数值
			tabBarSettings: {
			    tabBarBadge: {
					messageCount: 0, // 对应消息数
			        triageUnreadMessageCount: 0, // 导诊未读消息数
			    },
			    guideHospConfig: userData.guideHospConfig
			}
		},
		onLaunch(options) {
			const self = this
			console.log('App Launch')
			console.log('options')
			console.log(options)
			console.log('this.globalData === ', this.globalData)
			//#ifdef MP
			let accountInfo = uni.getAccountInfoSync();
			let version = accountInfo.miniProgram.version ? accountInfo.miniProgram.version : '';
			this.globalData.miniVersion = version
			
			// 登录
			loginFun(this, this.globalData).then(data => {
			    console.log('onLaunch login执行完成')
			    const allHospitalData = this.$cache.get('allHospitalData');
			    // 如果没有医院数据，获取医院数据
			    if(!allHospitalData) {
			        this.$cache.set('Hospitalthis.$cacheTimeMap', timeMap)
			        getHospList(this).then(() => {
			          console.log('获取医院列表数据')
			        })
			    }
			})

			// 获取支付平台类型
			uni.getProvider({
				service: 'payment',
				success: function(res) {
					console.log('provider', res.provider)
					self.globalData.provider = res.provider[0]
				}
			});

			// 获取IP地址
			uni.request({
				url: httpConfig.ipDeault +'/localIP',
				success: function(res) {
					// console.log('IP地址: ',res.data);
					let userData = this.$cache.get('userData');
					this.$cache.set('userData', {
						...userData,
						ipAddress: res.data.ipv4
					});
				}
			});

			// 判断是否由分享进入小程序
			if (options && (options.scene === 1007 || options.scene === 1008)) {
				this.globalData.share = true
			} else {
				this.globalData.share = false
			}

			//获取设备顶部窗口的高度（不同设备窗口高度不一样，根据这个来设置自定义导航栏的高度）
			const {
				navHeight, // 头部高度PX
				navBottom,
				navRight,
				statusBarHeight,
				navTitleHeight
			} = Utils.calNavBarHeight();
			console.log(navHeight, navBottom)
			this.globalData.height = navHeight;
			this.globalData.statusBarData = {
				statusBarHeight,
				navBottom,
				navRight,
				navTitleHeight
			}

			uni.getSetting({
				success: (res) => {
					if (!res.authSetting['scope.camera']) { //获取摄像头权限
						uni.authorize({
							scope: 'scope.camera',
							success() {
								console.log("用户已经同意小程序使用摄像头功能")
							},
							fail() {}
						})
					}
					if (!res.authSetting['scope.record']) {
						uni.authorize({
							scope: 'scope.record',
							success() {
								// 用户已经同意小程序使用录音功能，后续调用 uni.startRecord 接口不会弹窗询问
								console.log("用户已经同意小程序使用录音功能")
							}
						})
					}
				},
				fail(error) {
					console.log(error)
				}
			})
			//#endif
			
			// #ifdef H5
			if(options && options.query.state) {
				this.globalData.pubAccCode = options.query.state
				const userData = Cache.get("userData")
				Cache.set("userData", {
					...userData,
					pubAccCode: options.query.state
				})
			}
			// #endif

			//#ifdef MP-ALIPAY
			console.log(monitor)
			monitor.init({
				pid: "y3y+igdwvrhwrosbgzmvpa==",
				options: options,
				sample: 1,
				autoReportApi: false,
				autoReportPage: false,
				miniVersion: version
			});
			this.globalData.platform = 'alipay'
			const appIdRes = my.getAppIdSync();
			this.globalData.appId = appIdRes.appId
			//#endif

			//#ifdef MP-WEIXIN
			this.globalData.platform = 'weixin'
			//#endif

			uni.onNetworkStatusChange(function(res) {
				if (!res.isConnected) {
					uni.showToast({
						title: '网络似乎不太顺畅。',
						duration: 2000,
						icon: 'none',
					})
				}
			})
		},
		onShow(options) {
			console.log('app onShow options', options)
			const self = this

			//#ifdef MP-ALIPAY
			if (options && options.query && [1011, 1012, 1013].indexOf(+options.scene) > -1) this.globalData.alipayQuery = options.query.qrCode
			if (options && options.query && [1300].indexOf(+options.scene) > -1) this.globalData.alipayQuery = options.query.path
			//#endif

			//微信
			//#ifdef MP-WEIXIN
			this.globalData.scene = options.scene;
			if (this.globalData.scene === 1038 && options.referrerInfo.hasOwnProperty('extraData')) {
				this.globalData.authCode = options.referrerInfo.extraData.authCode;
			}

			// 进入应用，活动市场人员ID绑定患者ID入口数据处理
			if (options.query && options.query.q && options.query.q.indexOf('hospital') > -1) {
				const decodeURL = decodeURIComponent(options.query.q)
				const paramsObj = Util.getQueryString(decodeURL)
				if (paramsObj) this.globalData.activityObj = paramsObj
			}

			// 扫描二维码、长按图片识别二维码、扫描手机相册中选取的二维码，调用01060001：微信设备与市场人员ID关联接口
			if (self.globalData.activityObj && self.globalData.activityObj.marketerID && [1011, 1012, 1013].indexOf(options.scene) > -1) {
				console.log('activityObj scene:', self.globalData.activityObj, options.scene)
				let data = {
					params: [{
						markPersonID: self.globalData.activityObj && self.globalData.activityObj.marketerID
					}]
				}
				$http.post("urlS", self, {
					code: '01060001',
					data: data,
					success(res) {
						console.log('01060001:', res)
					},
					error(err) {
						console.log('01060001 err：', err)
					}
				})
			}
			//#endif
		},
		onHide: function() {
			// console.log('App Hide')
		}
	}
</script>

<style lang="scss">
	/* 对于SCSS文件，使用@use替代@import - 必须放在最顶部 */
	@use "@/static/common.scss" as common;
	@use "@/static/base.scss" as base;
	@use "@/static/iconfont.scss" as iconfont;

	/* 对于CSS文件，继续使用@import */
	@import "@/static/vant-common.css";
	

	/*每个页面公共css */
	page {
		/* #ifdef MP */
		min-height: 100vh;
		/* #endif */
		background-color: #f7f7f7;
	}

	.placeholder {
		color: #808080;
	}
	body {
		font-size: 28rpx;
	}
</style>