<template>
  <view class="content"></view>
</template>

<script>
var main, receiver, filter
export default {
  props: ['model'],
  data () {
    return {
      scanCode: '',
      _codeQueryTag: false
    }
  },
  created: function (option) {
    console.log('created')
    if (uni.getSystemInfoSync().platform == 'android') {
      this.initScan()
      this.startScan()
    }
  },
  activated () {
    if (uni.getSystemInfoSync().platform == 'android') {
      this.initScan()
      this.startScan()
    }
  },
  onHide: function () {
    if (uni.getSystemInfoSync().platform == 'android') {
      this.stopScan()
    }
  },
  onUnload: function () {
    if (uni.getSystemInfoSync().platform == 'android') {
      this.stopScan()
    }
  },
  deactivated: function () {
    console.log('组件卸载')
    /*页面退出时一定要卸载监听,否则下次进来时会重复，造成扫一次出2个以上的结果*/
    if (uni.getSystemInfoSync().platform == 'android') {
      this.stopScan()
    }
  },

  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)
          }
        }
      )
    },
    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
      }
      if (this.model == 'uni') {
        uni.$emit('scancodedate', par)
      } else {
        _this.$emit('scancodedate', par)
      }
    }
  }
}
</script>
