<script>
import { iap } from "@/utils/myIapCheck.js";
import store from "@/store/index.js";
import socket from "@/config/socket";
// #ifdef H5
import { h5Login } from "@/config/html5Utils";
// #endif
// // #ifdef APP-PLUS
// import APPUpdate from '@/uni_modules/zhouWei-APPUpdate/js_sdk/appUpdate';
// // #endif
// #ifdef APP-PLUS
import updata from "@/uni_modules/uni-upgrade-center-app/utils/check-update";
// #endif
import Vue from "vue";
// #ifdef APP-PLUS
	var jpushModule = uni.requireNativePlugin("JG-JPush");
	var audioObj = uni.getBackgroundAudioManager();
	// #endif   
export default {
  data() {
    return {
      platform: null, // 系统
    };
  },
  onLaunch: function (e) {
    // 检测自动更新
    // #ifdef APP-PLUS
	updata();
    // #endif


    //取出缓存数据
    store.commit("setCacheData");


	// #ifdef APP-PLUS
	const agreed = uni.getStorageSync('privacy_agreed') || (store.state.userInfo && store.state.userInfo.id);
	console.log('检测用户是否同意隐私协议', agreed)
	if (agreed) {
		console.log('同意隐私协议，开始调用极光推送', agreed)
		jpushModule.initJPushService();
		jpushModule.setLoggerEnable(true);
		plus.screen.lockOrientation("portrait-primary");
		// 设置别名
		            jpushModule.setAlias({
		                    'alias': this.lxzl.getUserInfo().userId + '',
		                    'sequence': 1
		            })
		//监听 极光推送连接状态
		this.getNotificationEnabled();
		jpushModule.addConnectEventListener(result => {
			let connectEnable = result.connectEnable
			uni.$emit('connectStatusChange', connectEnable)
		});
		jpushModule.addNotificationListener(result => { //极光推送的消息通知回调
			jpushModule.setBadge(0);
			plus.runtime.setBadgeNumber(0);
			let notificationEventType = result.notificationEventType
			let woopId = result.extras && result.extras.dataType === 'woop' && result.extras.value;
			console.log("通知", result, notificationEventType)
			// 点击事件
			if (notificationEventType == 'notificationOpened') {
				uni.navigateTo({
					url: '/pages/taskDetail/taskDetail?' + 'woopId=' + woopId
				});
			}
		});
		uni.$on('connectStatusChange', (connectStatus) => {
			var connectStr = ''
			if (connectStatus == true) {
				connectStr = '已连接'
				// this.getRegistrationID()
			} else {
				connectStr = '未连接'
			}
			console.log('监听到了连接状态变化 --- ', connectStr)
			this.connectStatus = connectStr
		})
		jpushModule.isPushStopped(res => {
			// code   0已停止推送  1未停止推送
			const { code } = res
			console.log(res, '安卓连接状态');
		})
	}
	//#endif		
			
    uni.getSystemInfo({
      success(res) {
        Vue.prototype.winWidth = res.screenWidth;
        Vue.prototype.winHeight = res.screenHeight;
        Vue.prototype.statusBarHeight = res.statusBarHeight;
      },
    });

    // #ifdef MP-WEIXIN
    if (store.state.userInfo.token) {
      socket.init();
    }
    // #endif
    // #ifdef H5
    console.log(store.state);
    if (store.state.userInfo.token) {
      socket.init();
    } else {
      h5Login("force", () => {
        socket.init();
      });
    }
    // #endif
    // #ifdef APP-PLUS
    if (store.state.userInfo.token) {
      socket.init();
    }
    // 检测是否有未关闭苹果内购订单
    iap.getChannels();
    // #endif
  },
  onShow: function (e) {
    // #ifdef MP-WEIXIN
    //获取二维码携带的参数
    let scene = decodeURIComponent(e.query.scene);
    scene = scene.split("&");
    let data = {
      //场景值
      scene: e.scene,
    };
    scene.forEach((item) => {
      let arr = item.split("=");
      if (arr.length == 2) {
        data[arr[0]] = arr[1];
      }
    });
    store.commit("setChatScenesInfo", Object.assign(e.query, data));
    //小程序更新
    if (uni.getUpdateManager) {
      const updateManager = uni.getUpdateManager();
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        // console.log(res.hasUpdate);
      });
      updateManager.onUpdateReady(function (res) {
        uni.showModal({
          title: "更新提示",
          content: "新版本已经准备好，是否重启应用？",
          success(res) {
            if (res.confirm) {
              // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              updateManager.applyUpdate();
            }
          },
        });
      });
      updateManager.onUpdateFailed(function (res) {
        // 新的版本下载失败
        uni.showModal({
          title: "已经有新版本了哟~",
          content: "新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~",
          showCancel: false,
        });
      });
    }
    // #endif
  },
  onHide: function () {},
  destroyed() {
    store.commit("setUserInfo", {
      playFlag: true,
    });
    console.log("页面销毁");
  },
  methods: {
	  	// 处理通知权限
	  			getRegistrationID() { //获取registerID
	  				jpushModule.getRegistrationID(result => {
	  					let registerID = result.registerID
	  					console.log(registerID)
	  					this.registrationID = registerID
	  					uni.setStorageSync("registerID", registerID)
	  				})
	  			},
	  			getNotificationEnabled() {
	  				if (uni.getSystemInfoSync().platform == "ios") {
	  					jpushModule.requestNotificationAuthorization((result) => {
	  						let status = result.status
	  						if (status < 2) {
	  							this.noticMsgTool()
	  						}
	  					})
	  				} else {
	  					jpushModule.isNotificationEnabled((result) => { //判断android是否打开权限
	  						if (result.code == 0) { //如果为0则表示 未打开通知权限 
	  							this.noticMsgTool()
	  						}
	  					})
	  				}
	  			},
	  			noticMsgTool() {
	  				if (uni.getSystemInfoSync().platform == "ios") {
	  					//苹果打开对应的通知栏
	  					uni.showModal({
	  						title: '通知权限开启提醒',
	  						content: '您还没有开启通知权限，无法接受到消息通知，请前往设置！',
	  						showCancel: false,
	  						confirmText: '去设置',
	  						success: function(res) {
	  							if (res.confirm) {
	  								var app = plus.ios.invoke('UIApplication', 'sharedApplication');
	  								var setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:');
	  								plus.ios.invoke(app, 'openURL:', setting);
	  								plus.ios.deleteObject(setting);
	  								plus.ios.deleteObject(app);
	  							}
	  						}
	  					});
	  				} else {
	  					//android打开对应的通知栏
	  					var main = plus.android.runtimeMainActivity();
	  					var pkName = main.getPackageName();
	  					var uid = main.getApplicationInfo().plusGetAttribute("uid");
	  					uni.showModal({
	  						title: '通知权限开启提醒',
	  						content: '您还没有开启通知权限，无法接受到消息通知，请前往设置！',
	  						showCancel: false,
	  						confirmText: '去设置',
	  						success: function(res) {
	  							if (res.confirm) {
	  								var Intent = plus.android.importClass('android.content.Intent');
	  								var Build = plus.android.importClass("android.os.Build");
	  								//android 8.0引导  
	  								if (Build.VERSION.SDK_INT >= 26) {
	  									var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
	  									intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
	  								} else if (Build.VERSION.SDK_INT >= 21) { //android 5.0-7.0  
	  									var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
	  									intent.putExtra("app_package", pkName);
	  									intent.putExtra("app_uid", uid);
	  								} else { //(<21)其他--跳转到该应用管理的详情页  
	  									intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
	  									var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
	  									intent.setData(uri);
	  								}
	  								// 跳转到该应用的系统通知设置页  
	  								main.startActivity(intent);
	  							}
	  						}
	  					});
	  				}
	  			},
	  
  },
};
</script>

<style lang="scss">
@import "@/uni_modules/uview-ui/index.scss";
@import "@/uni_modules/uni-scss/index.scss";

/* uni.css - 通用组件、模板样式库，可以当作一套ui库应用 */
@import "./common/uni.css";
@import "@/static/customicons.css";
@import "@/style/common.scss";

@import "uview-ui/index.scss";

@import "./style/input.scss";
@import "./style/table.scss";

page {
  height: 100%;
  background-color: #fff;
}

/* #ifdef H5 */
//修复H5底部导航挡住内容bug
uni-app {
  height: auto;
}

.commonPage,
.commonPageBox {
  height: calc(100vh - 50px);
}

/*每个页面公共css */
@font-face {
  font-family: "iconfont";
  /* project id 1997429 */
  src: url("https://at.alicdn.com/t/font_1997429_8xzvctxta3u.eot");
  src: url("https://at.alicdn.com/t/font_1997429_8xzvctxta3u.eot?#iefix")
      format("embedded-opentype"),
    url("https://at.alicdn.com/t/font_1997429_8xzvctxta3u.woff2")
      format("woff2"),
    url("https://at.alicdn.com/t/font_1997429_8xzvctxta3u.woff") format("woff"),
    url("https://at.alicdn.com/t/font_1997429_8xzvctxta3u.ttf")
      format("truetype"),
    url("https://at.alicdn.com/t/font_1997429_8xzvctxta3u.svg#iconfont")
      format("svg");
}

.iconfont {
  font-family: "iconfont" !important;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -webkit-text-stroke-width: 0.2px;
  -moz-osx-font-smoothing: grayscale;
}

//修复H5输入框上下不居中bug
.uni-input-form {
  height: 100%;
}

//去除地图上高德地图标识符
.amap-copyright {
  display: none !important;
}

.amap-logo {
  display: none !important;
}

.amap-ui-control-zoom {
  width: 60upx !important;
}

.amap-ui-control-zoom > * {
  width: 60upx !important;
  height: 60upx !important;
  line-height: 60upx !important;
}

.amap-ui-control-theme-dark {
  display: none !important;
}

//设置圆角
checkbox.round .wx-checkbox-input,
checkbox.round .uni-checkbox-input {
  border-radius: 100upx;
}

//设置背景色
checkbox.checkedItem[checked] .wx-checkbox-input,
checkbox.checkedItem .uni-checkbox-input-checked {
  background-color: #e5a000 !important;
  border-color: #e5a000 !important;
  color: #ffffff !important;
}

/* #endif */
</style>
