import React, { useRef } from 'react';
import { ComponentStory, ComponentMeta } from '@storybook/react';
import { OPScan } from '../../src/index';

export default {
  title: '组件/数据录入/OPScan',
  component: OPScan,
} as ComponentMeta<typeof OPScan>;

export const 扫码: ComponentStory<typeof OPScan> = (): JSX.Element => {
  const inputRef = useRef(null);

  // 创建一个模拟键盘事件的函数
  function simulateKeyboardEvent(key: string) {
    const evt = new KeyboardEvent('keydown', {
      bubbles: true,
      cancelable: true,
      key,
    });
    document.dispatchEvent(evt);
  }

  function handleClick() {
    // 模拟键盘事件输入
    const value = inputRef.current.value;
    const arr = value.split('');
    for (let i = 0; i < arr.length; i++) {
      var char = arr[i];
      console.log(char);
      simulateKeyboardEvent(char);
    }
    // 手动触发enter
    simulateKeyboardEvent('Enter');
  }

  return (
    <>
      <OPScan
        placeholder='扫拣选单/运单'
        onEnter={(v, isScan) => {
          console.log(v);
          console.log('是否扫码枪扫描', isScan, v);
        }}
      />
      <input
        ref={inputRef}
        value='PP KRIT004
'
      />
      <button type='submit' onClick={handleClick}>
        模拟扫描
      </button>
    </>
  );
};
