<script>
	import {
		getTasksUpdate
	} from './services/app'
	import {
		initFilter
	} from './utils/common'
	import request from './utils/request'
	import config from './config/common'
	import checkappupdate from './utils/checkappupdate.js'

	export default {
		globalData: {
			noticeAndTask: {
				Task: 0,
				Msg: 0
			}
		},
		data() {
			return {
				getUpdateFn: undefined
			}
		},
		onLaunch: function() {
			const token = uni.getStorageSync('accessToken')
			const orgId = uni.getStorageSync('orgId')
			const Tenant = uni.getStorageSync('Tenant')
			const appInfo = uni.getStorageSync('appInfo')
			if (!token || !orgId || !Tenant || !appInfo) {
				uni.reLaunch({
					url: 'pages/login/index'
				})
			}

			// checkappupdate.check({
			// 	versionContent: '1.升级提示框改造早早早哦啊早\n2.提示标语更新\n3.其他优化升级，建议全员升级',
			// 	versionNumber: '1.0.022',
			// 	appurl: '大大哇',
			// 	apk:'false',
			// 	versionNow:'1.0.021'
			// })
			const store = this.$store
			// #ifndef MP
			uni.onTabBarMidButtonTap(function() {
				uni.chooseImage({
					count: 6, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera'],
					success: (res) => {
						const url = config.serviceHost('/PF/File/UploadFile')
						request.upload(url, res.tempFilePaths).then((result) => {
							if (result.IsSuccessful) {
								// TODO: 目前只支持一张照片
								store.commit('updateImageLists', [{
									IMG_FILE_ID: result.Data.imgFileID,
									IMG_FILE_PATH: result.Data.imgFilePath
								}]);
								uni.showActionSheet({
									title: '选择上报类型',
									itemList: ['随手拍', '隐患上报'],
									success: (e) => {
										if (e.tapIndex === 0) {
											uni.navigateTo({
												url: '/pages/camera/index'
											})
										} else {
											uni.navigateTo({
												url: '/pages/apply/subPages/riskReport'
											})
										}
									}
								})
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					complete: function(com) {
						console.log('choose image complete', com)
					}
				})
			})
			// #endif

			// 检查更新
			// #ifdef APP-PLUS
			if (this.judgeTabbar()) {
				// 在有tabbar页时，提示更新
				getTasksUpdate(json).then(res => {
					if (res.Data.AppVersion) {
						this.checkVersionUpdate(res.Data.AppVersion)
					}
				})
			}
			// #endif
		},
		onShow: function() {
			console.log('App Show')
			const orgId = uni.getStorageSync('orgId')
			const json = initFilter(orgId)
			// 检查更新
			// #ifdef APP-PLUS
			if (this.judgeTabbar()) {
				// 在有tabbar页时，提示更新
				getTasksUpdate(json).then(res => {
					if (res.Data.AppVersion) {
						this.checkVersionUpdate(res.Data.AppVersion)
					}
				})
			}
			// #endif

			// 获取任务和消息更新
			const timingUpdate = () => {
				if (this.judgeTabbar()) {
					getTasksUpdate(json).then(res => {
						getApp().globalData.noticeAndTask = res.Data
						if (res.Data) {
							if (res.Data.Task > 0 || res.Data.Msg > 0) {
								// 设置tab红点
								uni.showTabBarRedDot({
									index: 0
								})
							} else {
								uni.hideTabBarRedDot({
									index: 0
								})
							}
						}
					})
				}
			}
			setTimeout(timingUpdate, 1000)
			this.getUpdateFn = setInterval(timingUpdate, 60000)
		},
		onHide: function() {
			console.log('App Hide')
			clearInterval(this.getUpdateFn)
		},
		onExit: function() {
			console.log('App Exit')
			clearInterval(this.getUpdateFn)
		},
		methods: {
			judgeTabbar() {
				let pages = getCurrentPages()
				if (pages.length > 0) {
					let prevPage = pages[pages.length - 1]
					if (prevPage.route === 'pages/index/index2' || prevPage.route === 'pages/performance/index1' ||
						prevPage.route === 'pages/my/index1' || prevPage.route === 'pages/apply/index') {
						return true
					}
				}
			},
			checkVersionUpdate(versionInfo) {
				const latestVersion = parseInt(versionInfo.Code.split('.').join(''))
				// const localVersion = parseInt(plus.runtime.version.split('.').join(''))
				plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
					const localVersion = parseInt(widgetInfo.version.split('.').join(''))
					if (latestVersion > localVersion) {
						if (versionInfo.Upgrade >= 0 && versionInfo.Url) {
							if (versionInfo.Upgrade === 0) { // 资源包更新
								checkappupdate.check({
									versionContent: versionInfo.Desc,
									versionNumber: versionInfo.Code,
									versionNow: widgetInfo.version,
									appurl: config.uni_app_web_source_url + versionInfo.Url,
									apk: 'false'
								})
								// uni.showModal({
								// 	title: "有新的版本（" + latestVersion + "），请更新",
								// 	content: versionInfo.Desc,
								// 	cancelText: '稍后更新',
								// 	confirmText: '立即更新',
								// 	success: (res) => {
								// 		if (res.confirm) {
								// 			uni.showLoading({
								// 				title: "下载资源包",
								// 				mask: true,
								// 			})
								// 			uni.downloadFile({ // 下载资源包
								// 				url: config.uni_app_web_source_url +
								// 					versionInfo.Url,
								// 				success: (downloadResult) => {
								// 					uni.hideLoading()
								// 					if (downloadResult.statusCode ===
								// 						200) {
								// 						plus.runtime.install(downloadResult
								// 							.tempFilePath, { // 安装资源包
								// 								force: false
								// 							},
								// 							function() {
								// 								console.log(
								// 									'install success...'
								// 								);
								// 								plus.runtime
								// 									.restart(); // 重启APP
								// 							},
								// 							function(e) {
								// 								console.error(e,
								// 									'install fail...'
								// 								);
								// 							})
								// 					}
								// 				}
								// 			})
								// 		} else if (res.cancel) {
								// 			// 暂不更新
								// 		}
								// 	}
								// })
							} else if (versionInfo.Upgrade === 1) { // 整包更新
								checkappupdate.check({
									versionContent: versionInfo.Desc,
									versionNumber: versionInfo.Code,
									versionNow: widgetInfo.version,
									appurl: config.uni_app_web_source_url + versionInfo.Url,
									apk: 'true'
								})
								// uni.showModal({
								// 	title: "更新提示",
								// 	content: '版本号：' + versionInfo.Desc,
								// 	success: (res) => {
								// 		if (res.confirm) {
								// 			var appurl = ''
								// 			if (plus.os.name === 'Android') {
								// 				appurl = config.uni_app_web_source_url + versionInfo
								// 					.Url;
								// 			} else {
								// 				// 其它平台
								// 				// appurl = versionInfo.pathIos;
								// 			}
								// 			plus.runtime.openURL(appurl); // 跳转应用发布平台
								// 		}
								// 	}
								// })
							}
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	@import "/uni_modules/uview-ui/index.scss";
	@import '/static/iconfont/iconfont.css';

	/*每个页面公共css */
	/* #ifdef MP */
	page {
		width: 100vw;
	}

	/* #endif */
</style>