<template>
	<view>
		<basics v-if="PageCur=='basics'" id="basics"></basics>
		<application v-if="PageCur=='application'"
                 :dys="dys"
                 :dzg="dzg"
                 :specialRectificationInspectHiddenCount="specialRectificationInspectHiddenCount"
                 :superviseinspecthiddenCount = "superviseinspecthiddenCount"
    ></application>
		<works v-if="PageCur=='works'" id = "works"></works>
		<my v-if="PageCur=='my'" id = "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/tabbar/basics' + [PageCur=='basics'?'_cur':''] + '.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/tabbar/application' + [PageCur == 'application'?'_cur':''] + '.png'"></image>
          <view v-if="(hidCount+specialRectificationInspectHiddenCount+superviseinspecthiddenCount)>0" class="cu-tag badge">
            {{hidCount+specialRectificationInspectHiddenCount+superviseinspecthiddenCount}}
          </view>
				</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/tabbar/works' + [PageCur == 'works'?'_cur':''] + '.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/tabbar/my' + [PageCur == 'my'?'_cur':''] + '.png'"></image>
				</view>
				<view :class="PageCur=='my'?'text-blue':'text-gray'">我的</view>
			</view>
		</view>
	</view>
</template>

<script>
  import { decryptAes } from "@/common/aesUtil";
	import {
		basePath,
		isRest,
		loginUserId,
		formatDate,
		loginUser,
		setloginUserId,
		setCorpinfoId,
		setDeptId,
		setloginUser,
		adminPath,
		setVersion,
		corpinfoId,
		setIsRest,
    baseImgPath
	} from '@/common/tool.js';

	export default {
		data() {
			return {
				initflag:false,
				PageCur: 'basics',
				wgtVer:'',
				version:'',
				brand:'other',
				mesCount:0,
        hidCount:0,
        dys:0,
        dzg:0,
        specialRectificationInspectHiddenCount: 0,
        superviseinspecthiddenCount: 0,
			}
		},
		onBackPress() {
			//console.log("press back");

			uni.showModal({
				title: '是否退出',
				confirmText: '退出',
				success: function(res) {
					if (res.confirm) {
						setloginUserId(null);
						setCorpinfoId(null);
						setDeptId(null);
						setloginUser(null);
						uni.removeStorage({key: 'USER'});
						uni.reLaunch({
							url: '/pages/login/home'
						});
					}
				}.bind(this)//此处bind是关键
			})
			return true;
		},
		onShow() {
			var _this = this;
			_this.$nextTick(() => { //等待组件渲染结束才调用
				if(_this.initflag) {
					console.info("index的initflag=="+_this.initflag);
					if(_this.PageCur=='basics' || _this.PageCur=='message') {
						var page = _this.selectComponent("#" + _this.PageCur);//按子组件ID 获取子组件对象
						// page.getData();//调用子组件init方法
					}
					 if(_this.PageCur=='works') {
					 	var page = _this.selectComponent("#" + _this.PageCur);//按子组件ID 获取子组件对象
						page.getData();//调用子组件init方法
						page.getPcData();//调用子组件init方法
					 }
					 if(_this.PageCur=='my') {
					 	var page = _this.selectComponent("#" + _this.PageCur);//按子组件ID 获取子组件对象
						page.getData();//调用子组件init方法
					 }
				}

				_this.initflag=false;//false;子组件调用跳转方法时设为true
			});
			_this.$nextTick(() => { //等待组件渲染结束才调用
				if(_this.PageCur=='basics') {
					var page = _this.selectComponent("#" + _this.PageCur);//按子组件ID 获取子组件对象
					// page.getData();//调用子组件init方法
				}
			});

      this.mesCount = 0
      this.hidCount = 0
      this.dys = 0
      this.dzg = 0
			this.getRedPoint();
		},
 		onLoad() {
			 this.plusReady();
			// this.checkPlatform();
			// this.checkUpdate("android");
		},
		plusReady() {
			uni.startPullDownRefresh();

		},
		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: {

			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: {
            CORPINFO_ID:loginUser.CORPINFO_ID,
            USER_ID:loginUser.USER_ID,
					},
					success: (res) => {
            res.data = decryptAes(res.data);
						if("success" == res.data.result){
							uni.hideLoading();
							_this.mesCount = res.data.count;
							if(_this.mesCount > 0){
                uni.setTabBarBadge({ //显示数字
                  index: 2,//tabbar下标
                  text: _this.mesCount//数字
                })
              }else{
                uni.hideTabBarRedDot({ //隐藏红点
                  index:2
                })
              }
						} else {
							uni.showToast({
								title: res.data.message,
								duration: 2000
							});
						}
					},
					fail: (res) => {
						uni.showToast({
							icon: 'none',
							title: "服务器正在升级，请稍后再试。",
							duration: 2000
						});
					}
				});

        uni.request({
          url: basePath + '/app/hidden/getCountByUserId',
          method: 'POST',
          dataType: 'json',
          header:{
            'Content-type':'application/x-www-form-urlencoded'
          },
          data: {
            userId: loginUserId,
            USER_NAME: loginUser.NAME,
            CHECK_DEPARTMENT_ID: loginUser.DEPARTMENT_ID,
            IS_MAIN:loginUser.ISMAIN,
            CORPINFO_ID:loginUser.CORPINFO_ID,
            USER_ID:loginUser.USER_ID,
          },
          success: (res) => {
            res.data = decryptAes(res.data);
            if (res.data != null) {
              _this.hidCount += res.data.hidCount.dys || 0
              _this.hidCount += res.data.hidCount.dzg || 0
              _this.dys += res.data.hidCount.dys || 0
              _this.dzg += res.data.hidCount.dzg || 0
            }
          }
        });
        _this.getSpecialRectificationInspectHiddenCount()
        _this.getSuperviseinspecthiddenCount()
			},
      getSpecialRectificationInspectHiddenCount() {
        var _this = this;
        if (_this.isEnd) {
          return
        }
        uni.showLoading({
          title: '请稍候'
        });
        uni.request({
          url: basePath + '/app/specialRectificationInspectHidden/list',
          method: 'POST',
          dataType: 'json',
          header:{
            'Content-type':'application/x-www-form-urlencoded'
          },
          data: {
            tm:new Date().getTime(),
            STATE:1,
            showCount:10,
            currentPage:0,
            CORPINFO_ID:loginUser.CORPINFO_ID
          },
          success: (res) => {
            res.data = decryptAes(res.data);
            if (res.data.result == 'success') {
              uni.hideLoading();
              _this.specialRectificationInspectHiddenCount = res.data.page.totalResult;

            } else {
              uni.showToast({
                title: res.data.message,
                duration: 2000
              });
            }
          }
        });

      },
      getSuperviseinspecthiddenCount() {
        var _this = this;
        if (_this.isEnd) {
          return
        }
        uni.showLoading({
          title: '请稍候'
        });
        uni.request({
          url: basePath + '/app/superviseinspecthidden/list',
          method: 'POST',
          dataType: 'json',
          header:{
            'Content-type':'application/x-www-form-urlencoded'
          },
          data: {
            STATE:1,
            showCount:10,
            currentPage:0,
            CORPINFO_ID:loginUser.CORPINFO_ID
          },
          success: (res) => {
            res.data = decryptAes(res.data);
            if (res.data.result == 'success') {
              uni.hideLoading();
              _this.superviseinspecthiddenCount = res.data.page.totalResult;
            } else {
              uni.showToast({
                title: res.data.message,
                duration: 2000
              });
            }
          }
        });

      },
			NavChange: function (e) {
				this.PageCur = e.currentTarget.dataset.cur
			},
			setInit(flag) {//子组件调用init方法后 无需再执行onShow方法
				this.initflag = flag;
			},
			// 获取当前版本号
			plusReady() {
				var that = this;

				// 获取本地应用资源版本号
				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();
              console.log(that.brand) //手机牌子
              console.log(res.model) //手机型号
              console.log(res.screenWidth) //屏幕宽度
              console.log(res.screenHeight) //屏幕高度
						}
					});
				});

			},
			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) //屏幕高度
					}
				});
			},
			checkPlatform() {
				var _this=this;
				uni.getSystemInfo({
					success: (res) => {
						_this.checkUpdate(res.platform);
					}
				})
			},
			// 自动更新
			checkUpdate(platform){
				var that=this;
				uni.request({
					url: basePath + '/app/versionmanager/getVersion',  //获取最新版本号
					method: 'POST',
					data: {
						FILETYPE:platform,
						CORPINFO_ID:loginUser.CORPINFO_ID,
						USER_ID:loginUser.USER_ID,
					  },
					success: res => {
            res.data = decryptAes(res.data);
            console.log("发布版本：" + res.data.pd.VERSION + " -> " + Number(res.data.pd.VERSION.replace(/\./g, "")))
            console.log("运行版本：" + that.wgtVer + " -> " + Number(that.wgtVer.replace(/\./g, "")))
            console.log(Number(res.data.pd.VERSION.replace(/\./g, "")) > Number(that.wgtVer.replace(/\./g, "")))
						if(Number(res.data.pd.VERSION.replace(/\./g, "")) > Number(that.wgtVer.replace(/\./g, ""))){
              if(platform=="android"){
                plus.nativeUI.confirm( "请保持应用最新版本，否则将无法使用。", function(e){
                  if(e.index == 0){
                    var url2 = encodeURI(baseImgPath + res.data.pd.FILEURL);
                    plus.runtime.openURL(url2, function(res) {});
                    setTimeout(function() {
                      plus.runtime.quit();
                    }, 2000);
                  } else {
                    plus.runtime.quit();
                  }
                }, "下载更新", ["下载"] );
              }else{
                plus.nativeUI.confirm( "请保持应用最新版本，否则将无法使用。", function(e){
                  if(e.index == 0){
                    var url='itms-apps://itunes.apple.com/cn/app/id1632339513?mt=8';// 应用在appstore的地址
                    plus.runtime.openURL(url);
                    setTimeout(function() {
                      const threadClass = plus.ios.importClass("NSThread");
                      const mainThread = plus.ios.invoke(threadClass, "mainThread");
                      plus.ios.invoke(mainThread, "exit");
                    }, 2000);
                  }
                }, "下载更新", ["下载"] );
              }
						}
					},

					fail: (res) => {
						uni.showToast({
							icon: 'none',
							title: "服务器正在升级，请稍后再试。",
							duration: 2000
						});
					}
				});
			},
		}
	}
</script>

<style>

</style>
