export default class scan {
  static Page(page) {
    ['onShow', 'onHide', 'onUnload'].forEach((f) => {
      const raw = page[f];
      var code = '';
      var timer = null;

      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('前置摄像头内容: ' + r.code);
            });

            //物理扫码枪
            my.ix.onKeyEventChange(page._keyEventListener = (r) => {
              let cur = getCurrentPages().slice(-1)[0];
              if (cur && cur.onKeyPress) {
                 //特殊处理  keycode需要减7
                if (r.keyCode >= 7 && r.keyCode <= 16) {
                  code = code + (r.keyCode - 7)
                }
                if(timer != null){
                  clearTimeout(timer);
                }
                timer = setTimeout(() => {
                  //兼容扫描枪
                  cur.onKeyPress.call(cur, code);
                   console.log('物理扫码枪内容: ' + code);
                  code = '';
                }, 500);
              }
            });
          }
        } 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);
  }
}