export default class scan {
  static Page(page) {
    ['onShow', 'onHide', 'onUnload'].forEach((f) => {
      const raw = page[f];
      var code = '';
      var isScaning = false;
      page[f] = (...args) => {
        if (f === 'onShow') {
          if (!page._keyEventListener) {
            //摄像头
            my.ix.onCodeScan((r) => {
              if (r.success) {
                let cur = getCurrentPages().slice(-1)[0];
                cur.onKeyPress.call(cur, code);
              }
              console.log('code: ' + r.code);
            });

            //物理扫码枪
            my.ix.onKeyEventChange(page._keyEventListener = (r) => {
              let cur = getCurrentPages().slice(-1)[0];
              if (cur && cur.onKeyPress) {
                if (isScaning == false) {
                  isScaning = true
                  code = (r.keyCode - 7) + ''
                  setTimeout(() => {
                    //兼容扫描枪  
                    cur.onKeyPress.call(cur, code);
                    isScaning = false
                  }, 1000);
                } else {
                  //特殊处理  keycode需要减7
                  if (r.keyCode >= 7 && r.keyCode <= 16) {
                    code = code + (r.keyCode - 7)
                  }
                }
              }
            });
          }
        } else if (f === 'onHide' || f === 'onUnload') {
          if (page._keyEventListener) {
            my.ix.offKeyEventChange(page._keyEventListener);
            page._keyEventListener = null;
            //摄像头资源释放
            my.ix.offCodeScan();
          }
        }
        if (raw instanceof Function) {
          let cur = getCurrentPages().slice(-1)[0];
          raw.call(cur, ...args);
        }
      };
    });
    return Page(page);
  }
}