<template>
	<view>
		<basics v-if="PageCur=='basics'" ref="basics" id="basics"></basics>
		<application v-if="PageCur=='application'"></application>
		<works v-if="PageCur=='works'" id = "works"></works>
		<my v-if="PageCur=='my'"></my>
		<view class="cu-bar tabbar bg-white shadow foot">
			<view class="action" @click="NavChange" data-cur="basics">
				<view class='cuIcon-cu-image'>
					<image :src="'/static/new_images/tabico1' + [PageCur=='basics'?'_on':''] + '.png'"></image>
				</view>
				<view :class="PageCur=='basics'?'text-blue':'text-gray'">首页</view>
			</view>
			<view class="action" @click="NavChange" data-cur="application">
				<view class='cuIcon-cu-image'>
					<image :src="'/static/new_images/tabico2' + [PageCur == 'application'?'_on':''] + '.png'"></image>
				</view>
				<view :class="PageCur=='application'?'text-blue':'text-gray'">应用</view>
			</view>
			<view class="action" @click="NavChange" data-cur="works">
				<view class='cuIcon-cu-image'>
					<image :src="'/static/new_images/tabico3' + [PageCur == 'works'?'_on':''] + '.png'"></image>
					<view v-if="mesCount>0" class="cu-tag badge">{{mesCount}}</view>
				</view>
				<view :class="PageCur=='works'?'text-blue':'text-gray'">通知</view>
			</view>
			<view class="action" @click="NavChange" data-cur="my">
				<view class='cuIcon-cu-image'>
					<image :src="'/static/new_images/tabico4' + [PageCur == 'my'?'_on':''] + '.png'"></image>
				</view>
				<view :class="PageCur=='my'?'text-blue':'text-gray'">我的</view>
			</view>
		</view>
    <uni-popup ref="popup" background-color="#fff" :is-mask-click="false">
      <view style="text-align: center;color:#606266;width: 500upx;padding: 40upx">
        <view style="margin-bottom: 40upx;">温馨提示</view>
        <rich-text :nodes="updateVersion.modalContent"></rich-text>
      </view>
      <view style="margin-top: 40upx;display: flex">
        <button v-if="updateVersion.showCancelButton" class="cu-btn bg-blue" style="flex: 1;border-radius: 0" @click="modalCancel">{{updateVersion.cancelText}}</button>
        <button v-if="updateVersion.showConfirmButton" class="cu-btn bg-green" style="flex: 1;border-radius: 0" @click="modalConfirm">{{updateVersion.confirmText}}</button>
      </view>
    </uni-popup>
    <uni-popup ref="popup1" background-color="#fff" :is-mask-click="false">
      <view style="text-align: center;color:#606266;width: 500upx;padding: 40upx">
        <view style="margin-bottom: 40upx;">温馨提示</view>
        <view>有未签署的安全承诺，点击确认前往签署</view>
      </view>
      <view style="margin-top: 40upx;display: flex">
        <button class="cu-btn bg-green" style="flex: 1;border-radius: 0" @click="modalConfirm1">确定</button>
      </view>
    </uni-popup>
	</view>
</template>

<script>
	import {
		baseImgPath,
		basePath,
		majorSocketPath,
		loginUserId,
		formatDate,
		loginUser,
		setloginUserId,
		setCorpinfoId,
		setDeptId,
		setloginUser,
		adminPath,
		setVersion
	} from '@/common/tool.js';
	import { mapState } from 'vuex';

	export default {
		computed: {
			...mapState(['eventlist'])
		},
		data() {
			return {
				baseImgPath: baseImgPath,
				initflag:false,
				PageCur: 'basics',
				wgtVer:'',
				version:'',
				brand:'other',
				mesCount:0,
				updateVersion:{
				  showConfirmButton: false,
				  showCancelButton: false,
				  confirmText: '',
				  cancelText: '',
				  modalContent: '',
				  confirmType: '',
				  newVersionUrl: '',
				  downloadCompleteTemporaryPath: '',
				},
				innerAudioContext: null,
        isShowTabBar:true
			}
		},
		onBackPress() {
			//console.log("press back");

		plus.runtime.quit();
		   return true;
		},
		onLoad() {
			uni.startPullDownRefresh();
			this.plusReady();

			// this.checkPlatform();
			// this.checkUpdate("android");
		},
		onShow() {
      // 刷新数据
      if(this.$refs.basics){
        this.$refs.basics.getSumCount()
      }
			var _this = this;
			_this.$nextTick(() => { //等待组件渲染结束才调用
				if(_this.initflag) {
					console.info("index的initflag=="+_this.initflag);
					if(_this.PageCur=='basics' || _this.PageCur=='message' || _this.PageCur=='works') {
						var page = _this.selectComponent("#" + _this.PageCur);//按子组件ID 获取子组件对象
						// page.getData();//调用子组件init方法
						page.getPcData();//调用子组件init方法
					}
					console.info(_this.PageCur);
					// if(_this.PageCur=='works') {
					// 	var page = _this.selectComponent("#" + _this.PageCur);//按子组件ID 获取子组件对象
					// 	page.getlist();//调用子组件init方法
					// }
				}

				_this.initflag=false;//false;子组件调用跳转方法时设为true
			});
			_this.$nextTick(() => { //等待组件渲染结束才调用
				if(_this.PageCur=='basics') {
					var page = _this.selectComponent("#" + _this.PageCur);//按子组件ID 获取子组件对象
					page.getData();//调用子组件init方法
				}
			});
			const state = uni.getStorageSync('LOGIN_INIT');
			if (state === 1) {
				this.$store.dispatch('WEBSOCKET_INIT', majorSocketPath)
				this.getDisplsal();
				uni.setStorageSync('LOGIN_INIT', state+1);
			}
			this.getRedPoint();
      this.getPromiseUnsigned()
		},
		onPullDownRefresh() {
			var _this = this;
			console.info(_this.PageCur)
			if(_this.PageCur=='basics' || _this.PageCur=='message' || _this.PageCur=='works') {
				var page = _this.selectComponent("#" + _this.PageCur);//按子组件ID 获取子组件对象
				page.getData();//调用子组件init方法
			}
			setTimeout(function () {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		methods: {
      getPromiseUnsigned(){
        uni.request({
          url: basePath + '/app/corppromise/ISSIGN',
          method: 'POST',
          dataType: 'json',
          header: {
            'Content-type':'application/x-www-form-urlencoded'
          },
          data: {
            USER_ID: loginUserId
          },
          success: (res) => {
            if(res.data.ISSIGN === 1){
              this.isShowTabBar = false;
              this.$nextTick(()=>{
                this.$refs.popup1.open()
              })
            }else {
              this.isShowTabBar = true;
              this.$nextTick(()=>{
                this.$refs.popup1.close()
              })
            }
          },
          fail: (res) => {
            uni.showToast({
              icon: 'none',
              title: "服务器正在升级，请稍后再试。",
              duration: 2000
            });
          }
        });
      },
      modalConfirm1(){
        uni.reLaunch({
          url:'/pages/my/promise/sign'
        })
      },
			getDisplsal() {
				var _this = this;
				uni.showLoading({
					title: '请稍候'
				})
				uni.request({
					url: basePath + '/app/majordangersourcedisposal/findValidateData',
					method: 'POST',
					dataType: 'json',
					header: {
						'Content-type':'application/x-www-form-urlencoded'
					},
					data: {
						RESPONSIBLE_USER_ID: loginUserId
					},
					success: (res) => {
						if("success" === res.data.result && res.data.varList.length > 0) {
							var item = res.data.varList[0]
							let message = '重大危险源（' + item.MAJORDANGERSOURCE_NAME + '）生成一次' + item.ALARM_TYPE_NAME + '报警【等级：'
							if (item.ALARM_LEVEL === '1') {
								message += '一级'
							} else if (item.ALARM_LEVEL === '2') {
								message += '二级'
							} else if (item.ALARM_LEVEL === '3') {
								message += '三级'
							} else if (item.ALARM_LEVEL === '4') {
								message += '四级'
							}
							message += '】，请尽快处理'
							_this.innerAudioContext = uni.createInnerAudioContext();
							_this.innerAudioContext.autoplay = true;
							_this.innerAudioContext.loop = true;
							_this.innerAudioContext.src = '../../static/audio/alarm.mp3';
							_this.innerAudioContext.onPlay(() => {
								// console.log('开始播放');
							});
							_this.innerAudioContext.onError((e) => {
								// console.log(e.errMsg);
								// console.log(e.errCode);
							});
							uni.showModal({
								title: '警告',
								content: message,
								showCancel: false,
								confirmText: '确定',
								success: res => {
									if (res.confirm) {
										_this.innerAudioContext.stop()
										_this.innerAudioContext = null
									}
								}
							})
						}
					},
					fail: (res) => {
						uni.showToast({
							icon: 'none',
							title: "服务器正在升级，请稍后再试。",
							duration: 2000
						});
					}
				});
			},
			getRedPoint() {
				var _this = this;
				uni.showLoading({
					title: '请稍候'
				})
				uni.request({
					url: basePath + '/app/notice/getRedPoint',
					method: 'POST',
					dataType: 'json',
					header: {
						'Content-type':'application/x-www-form-urlencoded'
					},
					data: {
						USER_ID: loginUserId
					},
					success: (res) => {

						if("success" == res.data.result){
							uni.hideLoading();
							_this.mesCount = res.data.count;
						} else {
							uni.showToast({
								title: res.data.message,
								duration: 2000
							});
						}
					},
					fail: (res) => {
						uni.showToast({
							icon: 'none',
							title: "服务器正在升级，请稍后再试。",
							duration: 2000
						});
					}
				});
			},
			NavChange: function (e) {
				this.PageCur = e.currentTarget.dataset.cur
			},
			setInit(flag) {//子组件调用init方法后 无需再执行onShow方法
				this.initflag = flag;
			},
			// 获取当前版本号
			plusReady() {
				var that = this;

				// 获取本地应用资源版本号
				if (plus) {
					plus.runtime.getProperty(plus.runtime.appid, function (inf) {
						that.wgtVer = inf.version;  //获取当前版本号
						setVersion(that.wgtVer);
						that.version = plus.runtime.version;
						uni.getSystemInfo({

							success(res) {
								that.brand = res.brand.toUpperCase();
								that.checkPlatform();
							}
						});
					});
				}

			},
			getBrand() {
				var that = this;
				uni.getSystemInfo({

					success(res) {
						that.brand = res.brand.toUpperCase();
						console.log(that.brand) //手机牌子
						console.log(res.model) //手机型号
						console.log(res.screenWidth) //屏幕宽度
						console.log(res.screenHeight) //屏幕高度
					}
				});
			},
			onBackPress() {
				if(this.showMask) {
					this.showMask = false;
					return true;
				}else{
					uni.showModal({
						title: '提示',
						content: '是否退出app？',
						success: function(res) {
							if (res.confirm) {
								// 退出当前应用，改方法只在App中生效
								plus.runtime.quit();
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
					return true
				}
			},
			checkPlatform() {
				var _this=this;
				uni.getSystemInfo({
					success: (res) => {
						_this.checkUpdate(res.platform);
					}
				})
			},
			// 自动更新
			checkUpdate(platform){
				var that=this;
				uni.request({
					url: basePath + '/app/versionManagerFirst/getVersion',  //获取最新版本号
					method: 'POST',
					success: res => {
						var updateState = false
						var updateVersion = res.data.pd.VERSION.split('.')
						var phoneVersion = that.wgtVer.split('.')
						if(updateVersion.length == phoneVersion.length){
							for (let i =0;i<updateVersion.length;i++){
								let upNub = Number(updateVersion[i])
								let phNub = Number(phoneVersion[i])
								if(upNub > phNub){
									updateState = true
								}
							}
						}else{
							updateState = true
						}
						if(updateState){
							if(platform==="android"){
                this.updateVersion.newVersionUrl = this.baseImgPath + res.data.pd.FILEURL
                uni.getNetworkType({
                  success: ({networkType}) => {
                    if (networkType === 'wifi') {
                      this.updateVersion.modalContent = '发现新版本，是否更新？请保持应用最新版本，否则将无法使用。'
                    } else {
                      this.updateVersion.modalContent =
                          '发现新版本，检查到您当前使用的是移动网络，是否更新？更新时请注意流量消耗。请保持应用最新版本，否则将无法使用。'
                    }
                    this.updateVersion.confirmType = 'download'
                    this.updateVersion.confirmText = '立即更新'
                    this.updateVersion.showConfirmButton = true;
                    this.$refs.popup.open()
                  }
                })
                if(res.data.pd.ISUPDATE =='1'){

                } else {
                  this.updateVersion.cancelText = '稍后更新'
                  this.updateVersion.showCancelButton = true;
                }
							}
						}
					}
				});
			},
      modalConfirm() {
        this.updateVersion.confirmType === 'download' ? this.downloadNewVersion() : this.installNewVersion()
      },
      modalCancel() {
        this.$refs.popup.close()
      },
      downloadNewVersion() {
        this.updateVersion.showConfirmButton = false;
        this.updateVersion.showCancelButton = false;
        this.updateVersion.modalContent = '正在下载新版本，请稍后...'
        const downloadTask = uni.downloadFile({
          url: this.updateVersion.newVersionUrl,
          success: (res) => {
            this.updateVersion.downloadCompleteTemporaryPath = res.tempFilePath
          }
        });
        downloadTask.onProgressUpdate((res) => {
          this.updateVersion.modalContent = `正在下载新版本，请稍后...<br>已经下载${res.progress}%`
          if (res.progress === 100) {
            this.updateVersion.showConfirmButton = true;
            this.updateVersion.confirmType = 'install'
            this.updateVersion.confirmText = '立即安装'
            this.updateVersion.modalContent = '下载成功，点击立即安装进行安装。'
          }
        });
      },
      installNewVersion() {
        plus.runtime.install(
            this.updateVersion.downloadCompleteTemporaryPath, {
              force: true
            },
            function (res) {
              plus.runtime.restart();
            }
        );
      },
		}
	}
</script>

<style>

</style>
