<script>
import Vue from 'vue'
import io from "@hyoga/uni-socket.io"
import utils from '@/common/utils/utils';
// #ifdef  APP-PLUS
import { permissionListener } from '@/common/utils/permissionTips.js'
// #endif
export default {
	globalData: {
	  $util: null
	},
  onLaunch: function () {
		this.globalData.$util = utils;
		console.log('~~~~~~~~');
		console.log(this.globalData);
    this.$store.commit('initApp')
    let capsuleWidth = 0;
    uni.getSystemInfo({
      success: function (e) {
			
        // #ifndef MP
        Vue.prototype.StatusBar = e.statusBarHeight
        if (e.platform == 'android') {
					
					permissionListener()
          Vue.prototype.CustomBar = e.statusBarHeight + 50
        } else {
          Vue.prototype.CustomBar = e.statusBarHeight + 45


        }
        // #endif
        // #ifdef MP-WEIXIN
        Vue.prototype.StatusBar = e.statusBarHeight
        let menu = wx.getMenuButtonBoundingClientRect()

        console.log(menu)
        Vue.prototype.Custom = menu
        Vue.prototype.CustomBar = menu.bottom + menu.top - e.statusBarHeight
        let temp = menu.bottom - e.statusBarHeight
        Vue.prototype.$barHeight = temp + (temp - menu.height);
        Vue.prototype.$barTrueHeight = menu.height;
        Vue.prototype.$menuButtonWidth = menu.width + (e.windowWidth - menu.right) * 2;
        Vue.prototype.$menuButtonRightWidth = e.windowWidth - menu.right;
        capsuleWidth = (e.windowWidth - menu.right) * 2 + menu.width
        // #endif
        // #ifdef MP-ALIPAY
        Vue.prototype.StatusBar = e.statusBarHeight
        Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight
        // #endif
        let unitRatio = 750 / uni.getSystemInfoSync().windowWidth
        Vue.prototype.StatusBarRpx = Vue.prototype.StatusBar * unitRatio
        Vue.prototype.CustomBarRpx = Vue.prototype.CustomBar * unitRatio
        Vue.prototype.unitRatio = unitRatio
        console.log(Vue.prototype.CustomBar)
        Vue.mixin({
          data() {
            return {
              StatusBar: Vue.prototype.StatusBar, //状态栏高度(px)
              CustomBar: Vue.prototype.CustomBar, //整个标题栏高度(px)
              StatusBarRpx: Vue.prototype.StatusBarRpx, //状态栏高度(rpx)
              CustomBarRpx: Vue.prototype.CustomBarRpx, //整个标题栏高度(rpx)
              capsuleWidth: capsuleWidth
            }
          },
        })
      },
    })
    // #ifdef APP-PLUS
		
    this.handleTestingVersion()
    // 锁定屏幕显示方向为竖屏正方向
    plus.screen.lockOrientation('portrait-primary')
    // 推送服务
    plus.push.addEventListener('click', (message) => {
      this.pushCallback(message)
    })
    // #endif
    global.token && this.$store.dispatch('getCartList')

    if (global.token) {
      this.socketFun();
    }
    uni.$on("loginSuccess", this.socketFun);
  },
  onShow: function () {
    console.log('APP Show')
    // #ifdef APP-PLUS
    // 获取参数
    const args = plus.runtime.arguments
    if (args) {
      plus.runtime.arguments = null
      plus.runtime.arguments = ''
      let params_str = args.split('?')[1]
      if (params_str) {
        let params = params_str.split('&').reduce(function (total, item) {
          let arr = item.split('=')
          total[arr[0]] = arr[1]
          return total
        }, {})
		console.log('params=', params)
		// if (params.type && params.type === 'invite') {
		// 	uni.navigateTo({
		// 		url: `${params.path}?invite_code=${params.invite_code}`,
		// 	})
		// } else {
			// params 参数: path 跳转路径 options 参数
			uni.navigateTo({
				url: `${params.path}?goods_id=${params.goods_id}&activity_id=${params.activity_id}&sku_id=${params.sku_id}&bargain_id=${params.bargain_id}`,
			})
		// }
      
      }
    }
    // #endif
  },
  onHide: function () {
    // 用户退出app时，把二次验证状态改为true
    console.log('APP Hide')
  },
  methods: {
    // 更新检测
    handleTestingVersion() {
    	let _platform = uni.getSystemInfoSync().platform;
    	let client =  _platform === 'android' ? 3 : 2
      plus.runtime.getProperty(plus.runtime.appid, widgetInfo => {
        console.log(widgetInfo)
        global.VERSION_CODE=widgetInfo.version
        console.log(global.apiUrls.publicUpdateAPP1)
          this.$api.post(global.apiUrls.publicUpdateAPP1, { version: widgetInfo.version, app_ident: 'user', client: client}).then(res => {
             console.log(res.data.data.version, widgetInfo.versionCode)
            if(res.data.code == 1 && res.data.data.version - 0 > widgetInfo.versionCode){
              plus.nativeUI.toast('检测到新版本'+ res.data.data.version_name+'，后台更新中...');
    					console.log(12345)
              let wgtUrl = res.data.data.version_url;
              console.log(wgtUrl)
              let apkUrl = res.data.data.version_apk_url || '';
              uni.downloadFile({
                url: wgtUrl,
                success: (downloadResult) => {
                  if (downloadResult.statusCode === 200) {
                    plus.runtime.install(downloadResult.tempFilePath, { force: false }, function() {
                      plus.runtime.restart();
                    }, function(e) {
                      if (plus.os.name == 'Android' && apkUrl) {
                        uni.downloadFile({
                          url: apkUrl,
                          success: (downloadResult) => {
                            if (downloadResult.statusCode === 200) {
                              plus.runtime.install(downloadResult.tempFilePath);
                            }
                          }
                        });
                      }else{
    										plus.runtime.launchApplication({
    											action: `https://apps.apple.com/cn/app/%E8%90%AC%E5%AE%B6%E5%95%86%E8%B6%85/id6738980656`
    										}, function(e) {
    											console.log('Open system default browser failed: ' + e.message);
    										});
    									}
                    });
                  } else if (downloadResult.statusCode === 400) {
                    if (plus.os.name == 'Android' && apkUrl) {
                      uni.downloadFile({
                        url: apkUrl,
                        success: (downloadResult) => {
                          if (downloadResult.statusCode === 200) {
                            plus.runtime.install(downloadResult.tempFilePath);
                          }
                        }
                      });
                    } else {
    										plus.runtime.launchApplication({
    											action: `https://apps.apple.com/cn/app/%E8%90%AC%E5%AE%B6%E5%95%86%E8%B6%85/id6738980656`
    										}, function(e) {
    											console.log('Open system default browser failed: ' + e.message);
    										});
    									}
                  }
                }
              });
            }else{
              console.log('没有新的版本')
              // this.$message.info('已经是最新版本')
            }
          })
        });
    },
    socketFun() {
      /**
       * ! 与后台一块定义好的 socket URL 接口
       */
      this.$api.post(global.apiUrls.IMAuthenticate, {}).then((res) => {
        /**
         * ! 层级是不是一样的
         */
        global.WEBSOCKET = res.data.data.socket_url;
        Vue.prototype.$socket = io(res.data.data.socket_url, {
          transports: [ 'websocket', 'polling' ]
        });

        // 断线重连
        this.$socket.on("reconnect", function () {
          console.log("重连成功");
        });


        // 监听连接成功事件
        this.$socket.on("connect", () => {
          console.log("连接成功------------------------------------");
          // 将自己注册到SOCKET
          this.$socket.emit("conn", {
            uid: res.data.data.uid,
            userSig: res.data.data.userSig,
          });
        });

        // 注册成功后才可接收消息
        this.$socket.on("conn", function (data) {
          console.log(data)
          if (data[0] == "ok") {
            console.log("注册成功");
          } else {
            console.log("注册失败");
          }
        });

        // 监听断线
        this.$socket.on("disconnect", function () {
          console.log("已下线");
        });

        // 监听接收消息
        this.$socket.on("broadcastingListen", function (data) {
          console.log("接收消息", data);
          // myAudio.play();
          for (var i = 0; i < data.length; i++) {
            console.log(data[i]); // 与你发送的msg 一致
            /**
             * ! 来消息了之后在
             */
            uni.$emit("receiveMsg", data[i]);
          }
        });
      });
    },
    // 推送回调
    pushCallback(message) {
      this.$urouter.navigateTo('/pages/service-message/message/message-type/index')
    },
    // #ifdef APP-PLUS
    // 权限检查
    checkPermissions() {
      // #ifdef APP-PLUS
      if (plus.os.name == 'Android') {
        // 判断是Android
        var main = plus.android.runtimeMainActivity()
        var pkName = main.getPackageName()
        var uid = main.getApplicationInfo().plusGetAttribute('uid')
        var NotificationManagerCompat = plus.android.importClass('android.support.v4.app.NotificationManagerCompat')
        var areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled()
        // 未开通‘允许通知’权限，则弹窗提醒开通，并点击确认后，跳转到系统设置页面进行设置
        if (!areNotificationsEnabled) {
          uni.showModal({
            title: this.$t('通知权限开启提醒'),
            content: this.$t('您还没有开启通知权限，无法接受到消息通知，是否前往设置？'),
            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)
              }
            },
          })
        }
      } else if (plus.os.name == 'iOS') {
        // 判断是IOS
        var isOn = undefined
        var types = 0
        var app = plus.ios.invoke('UIApplication', 'sharedApplication')
        var settings = plus.ios.invoke(app, 'currentUserNotificationSettings')
        if (settings) {
          types = settings.plusGetAttribute('types')
          plus.ios.deleteObject(settings)
        } else {
          types = plus.ios.invoke(app, 'enabledRemoteNotificationTypes')
        }
        plus.ios.deleteObject(app)
        isOn = 0 != types
        if (isOn == false) {
          uni.showModal({
            title: this.$t('通知权限开启提醒'),
            content: this.$t('您还没有开启通知权限，无法接受到消息通知，是否前往设置？'),
            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)
              }
            },
          })
        }
      }
      // #endif
    },
    // #endif
  },
}
</script>

<style lang="scss">
/* #ifndef APP-PLUS-NVUE */
@import './style/icon.css';
@import './style/main.css';
@import './style/animation.css';
@import './style/iconfont.css';
@import './style/common.scss';
@import './style/diyStyle.scss';
/* #endif */
</style>
