<!-- <template>
	<view v-if="isRiskVisiable">
		<u-upload>

		</u-upload>
	</view>
</template> -->
<script>
	import {
		getTasksUpdate
	} from './services/app'
	import {
		getEnum
	} from './services/common'
	import {
		GetNewRiskAreaInfo,
	} from './services/apply/subPages/SK/SKServices.js'
	import {
		getRequest,
	} from './services/apply/FOServices/FOServices';
	import {
		getAreaLists
	} from './services/apply/HMServices/HMServices'
	import {
		initFilter,
		guid
	} from './utils/common'
	import request from './utils/request'
	import config from './config/common'
	import checkappupdate from './utils/checkappupdate.js'

	// import riskReport from "./pages/apply/subPages/riskReport.vue"
	// Vue.component('risk', riskReport)

	export default {
		globalData: {
			noticeAndTask: {
				Task: 0,
				Msg: 0
			},
			isOnline: true,
			Month: '', //更新区域
			timestamp: '', //调用数据更新 判断
		},
		data() {
			return {
				isRiskVisiable: false,
				getUpdateFn: undefined,
			}
		},
		onLaunch: function() {
			this.initNetworkMonitor()
			const token = uni.getStorageSync('accessToken')
			const orgId = uni.getStorageSync('orgId')
			const Tenant = uni.getStorageSync('Tenant')
			const appInfo = uni.getStorageSync('appInfo')
			// debugger
			// uni.preloadPage({
			// 	url: 'pages/apply/subPages/riskReport'
			// })
			if (!token || !orgId || !Tenant || !appInfo) {
				//基础数据缓存
				this.loadAreaNew()
				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() {
				// debugger
				// this.isRiskVisiable = true
				// uni.$showRisk() 
				// // uni.riskReport
				// uni.navigateTo({
				// 	url: '/pages/apply/subPages/riskReport'
				// })

				uni.chooseImage({
					count: 6, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera', 'album'],
					success: (res) => {
						if (getApp().globalData.isOnline == null || getApp().globalData.isOnline) {
							const url = config.serviceHost('/PF/File/UploadFile')
							request.upload(url, res.tempFilePaths).then((result) => {
								if (result.IsSuccessful) {
									// TODO: 目前只支持一张照片
									store.commit('updateImageLists', [{
										tempFiles: res.tempFiles,
										IMG_FILE_ID: result.Data.imgFileID,
										IMG_FILE_PATH: result.Data
											.imgFilePath,
										isOnline: result.Data.isOnline
									}]);
									// uni.showActionSheet({
									// 	title: '选择上报类型',
									// 	itemList: ['随手拍', '隐患上报'],
									// 	success: (e) => {
									// 		if (e.tapIndex === 0) {
									// 			uni.navigateTo({
									// 				url: '/pages/camera/index'
									// 			})
									// 		} else {
									// 			uni.navigateTo({
									// 				url: '/pages/apply/subPages/riskReport'
									// 			})
									// 		}
									// 	}
									// })
									uni.navigateTo({
										url: '/pages/apply/subPages/SK/riskHandelEditNew'
									})
								}
							}).catch((error) => {
								console.log(error)
							});
						} else {
							try {
								//如果没有网络的情况 只有 手动隐患上报
								var RiskUpInfo = uni.getStorageSync('riskUpInfo')
								if (RiskUpInfo == null || RiskUpInfo == '') {
									RiskUpInfo = []
								}
								let arr = []
								res.tempFiles.map(i => {
									arr.push({
										name: i.name,
										path: i.path,
										size: i.size
									})
									// RiskUpInfo.push(i)
								})
								var imgFile = {
									imgFileID: guid(),
									'tempFiles': arr,
									'isOnline': false,
									'filePath': res.tempFilePaths[0],
									'OrgId': orgId,
									'userID': appInfo?.appInfoData?.User?.ID
								}
								RiskUpInfo.push(imgFile) //不做修改
								uni.setStorageSync('riskUpInfo', RiskUpInfo)

								//如果没有网络的情况 只有 手动隐患上报
								uni.navigateTo({
									url: '/pages/apply/subPages/SK/riskHandelEditNew?isOnline=false&IMG_FILE_ID=' +
										imgFile.imgFileID
								})
							} catch (e) {
								//TODO handle the exception
							}
						}
					},
					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
								})
							}
						}
					})
				}
			}
			if (this.globalData.isOnline) {
				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)
		},
		// onNetworkStatusChange: function() {
		// 	getApp().globalData.isOnline = res.isConnected;
		// },
		methods: {
			initNetworkMonitor() {
				// 获取初始网络状态
				uni.getNetworkType({
					success: (res) => {
						this.globalData.isOnline = res.networkType !== 'none';
					},
					fail: (err) => {
						this.globalData.isOnline = false
					}
				});
				// 监听网络变化
				uni.onNetworkStatusChange((ret) => {
					// try {
					// 	console.log('网络变化:onNetworkStatusChange 'uniPlatform:' + uni.getSystemInfoSync().uniPlatform +' window:'+window)
					// } catch {}
					if (uni.getSystemInfoSync().uniPlatform == 'web') {

						// try {
						// 	console.log('web:addEventListener')
						// } catch {}
						// 	debugger
						window.addEventListener('online', () => {
							// try {
							// 	console.log('web:online1' + this.globalData.isOnline)
							// } catch {}
							this.globalData.isOnline = true
							// try {
							// 	console.log('web:online2' + this.globalData.isOnline)
							// } catch {}

							//基础数据缓存
							this.loadAreaNew()
							//基础数据缓存
							var gbTimeSpance = getApp().globalData.timestamp
							var timestamp = (new Date()).Format('yyyyMMddHHmmss')
							//数据操作
							if (gbTimeSpance == undefined || gbTimeSpance == '' || timestamp -
								gbTimeSpance > 10) {
								this.globalData.timestamp = timestamp
								// /BS/BSRiskSubmit/UploadFileRiskCache
								const url = config.serviceHost('/SK/SKHiddenDangerHandReport/UploadFileRiskCache')
								request.processCachedData(url)
							}
						});
						window.addEventListener('offline', () => {
							// try {
							// 	console.log('web:offline1' + this.globalData.isOnline)
							// } catch {}
							this.globalData.isOnline = false
							// try {
							// 	console.log('web:offline2' + this.globalData.isOnline)
							// } catch {}
						});
					} else {
						try {
							console.log(' 非 web onNetworkStatusChange  暂时没处理 缓存 isConnected:' + ret)
						} catch {}
						this.globalData.isOnline = ret.isConnected;

						if (this.globalData.isOnline) {
							//基础数据缓存
							this.loadAreaNew()

							//基础数据缓存
							var gbTimeSpance = getApp().globalData.timestamp
							var timestamp = (new Date()).Format('yyyyMMddHHmmss')
							//数据操作
							if (gbTimeSpance == undefined || gbTimeSpance == '' || timestamp - gbTimeSpance > 10) {
								this.globalData.timestamp = timestamp
								// /BS/BSRiskSubmit/UploadFileRiskCache
								const url = config.serviceHost('/SK/SKHiddenDangerHandReport/UploadFileRiskCache')
								request.processCachedData(url)
							}
						}
					}
				});
			},

			async loadArea() {
				var areaLists = uni.getStorageSync('listAreas')
				if ((areaLists == null || areaLists == '') && this.globalData.Month == '') {
					this.globalData.Month = (new Date()).getMonth()
					const orgId = uni.getStorageSync('orgId')
					if (orgId && orgId != '') {
						const json = initFilter(orgId, "", "NAME", 0)
						json.Limit = 500
						json.SelectField = ['ID', 'CODE', 'NAME']
						await getAreaLists(json).then(res => {
							if (res.IsSuccessful) {
								var listA = res.Data.map(e => {
									return {
										ID: e.ID,
										CODE: e.CODE,
										NAME: e.NAME
									}
								})

								var listAreas = {
									'm': this.globalData.Month,
									'data': listA
								}
								uni.setStorageSync('listAreas', listAreas);
							}
						})

						// uni.request({
						// 	url: '/pages/apply/subPages/riskReport', // 替换为目标页面接口地址
						// 	method: 'GET',
						// 	success(res) {
						// 		debugger
						// 		if (res.statusCode === 200) {
						// 			uni.setStorageSync('offlinePage', JSON.stringify(res.data));
						// 			// 缓存数据到 localStorage
						// 			// localStorage.setItem('offlinePage', JSON.stringify(res.data));
						// 			// console.log('页面数据缓存成功');
						// 		}
						// 	},
						// 	fail(err) {
						// 		console.error('缓存页面失败，请自行先打开一次隐患上报页面', err);
						// 	}
						// });
					}
				}
			},
			async loadAreaNew() {
				var areaLists = uni.getStorageSync('listAreas')
				if (areaLists == null || areaLists == '') {
					const orgId = uni.getStorageSync('orgId')
					if (orgId && orgId != '') {
						const json = initFilter(orgId, "", "NAME", 0)
						json.Limit = 500
						json.SelectField = ['ID', 'CODE', 'NAME']
						await GetNewRiskAreaInfo(json).then(res => {
							if (res.IsSuccessful) {
								var listAreas = res
								uni.setStorageSync('listAreas', listAreas);
							}
						})
						const jsons = initFilter(orgId)
						getRequest(jsons, "/FM/UserProductionUnitSet/OrderPaged").then(res => {
							var mineTypeStorage = res
							uni.setStorageSync('mineTypeStorage', mineTypeStorage);
						})
						// var dataParm = {
						// 	'name': "SKProductionUnit"
						// }
						// await getEnum(dataParm).then(res => {
						// 	if (res != undefined && res.length > 0) {
						// 		for (let i = 0; i < res.length; i++) {
						// 			res[i].name = res[i].NAME
						// 			res[i].code = res[i].ID
						// 		}
						// 	}
						// 	var mineTypeStorage = res
						// 	uni.setStorageSync('mineTypeStorage', mineTypeStorage);
						// })
					}
				}
			},

			judgeTabbar() {
				if (this.globalData.isOnline) {
					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';

	.operate-radio .u-radio__text {
		color: #606266 !important;
		white-space: normal !important;
		flex: 1 !important
	}

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

	/* #endif */
</style>