var main, receiver, filter
export default {
  data () {
    return {
      scanCode: '',
      _codeQueryTag: false
    }
  },
  created: function (option) {
    console.log('created')
    console.log(this.$store.state.app.scancodedate)
    if (uni.getSystemInfoSync().platform == 'android') {
      this.initScan()
      this.startScan()
    }
    const _this = this
    uni.addInterceptor('navigateTo', {
      success (e) {
        _this.watchRouter()
      }
    })
    uni.addInterceptor('redirectTo', {
      success (e) {
        _this.watchRouter()
      }
    })
    uni.addInterceptor('switchTab', {
      success (e) {
        _this.watchRouter()
      }
    })
    uni.addInterceptor('navigateBack', {
      success (e) {
        _this.watchRouter()
      }
    })
  },
  methods: {
    initScan () {
      console.log('---------------------initScan---------')
      let _this = this
      main = plus.android.runtimeMainActivity() //获取activity
      var IntentFilter = plus.android.importClass(
        'android.content.IntentFilter'
      )
      filter = new IntentFilter()
      filter.addAction('com.android.serial.BARCODEPORT_RECEIVEDDATA_ACTION') // 换你的广播动作
      receiver = plus.android.implements(
        'io.dcloud.feature.internal.reflect.BroadcastReceiver',
        {
          onReceive: function (context, intent) {
            plus.android.importClass(intent)
            let code = intent.getStringExtra('DATA') // 换你的广播标签
            _this.queryCode(code)
          }
        }
      )
    },
    watchRouter () {
      this.$store.commit('app/RESET_SCANCODEDATE')
    },
    startScan () {
      main.registerReceiver(receiver, filter)
    },
    stopScan () {
      main.unregisterReceiver(receiver)
    },
    queryCode: function (code) {
      //防重复
      const _this = this
      if (_this._codeQueryTag) return false
      _this._codeQueryTag = true
      setTimeout(function () {
        _this._codeQueryTag = false
      }, 150)
      var id = code
      let par = {
        code: id
      }
      console.log(
        'this.$store.state.app.scancodedate',
        this.$store.state.app.scancodedate
      )
      uni.$emit(this.$store.state.app.scancodedate, par)
    }
  }
}
