import React, { useCallback, useImperativeHandle, useRef } from "react";
import { showMessage } from "../../../../util";

export interface UploadType {
  chooseFile: () => void
}

export default React.forwardRef<UploadType, { accept: string, upload: (files: FileList) => void }>(function ({ accept, upload }, ref) {

  const input = useRef<HTMLInputElement>(null)

  useImperativeHandle(ref, () => ({
    chooseFile: () => {
      input.current!.click();
    }
  }), [])

  const onChange: React.ChangeEventHandler<HTMLInputElement> = useCallback((e) => {
    console.log('files', e.target.files)
    if (e.target.files) { //console.debug(input.current!.files)
      e.preventDefault();

      let file = e.target.files[0]
      if (file) {
        const fileSize = file.size
        const isLt5G = fileSize / 1024 / 1024 / 1024 < 5
        if (!isLt5G) {
          showMessage('warn', '上传文件大小不超过5G')
          return
        }
      }
      e.target.files && upload(e.target.files)
    }
  }, [upload])

  const onInputClick: React.MouseEventHandler<HTMLInputElement> = useCallback((e) => {
    input.current!.value = ''
  }, [])

  return <input ref={input} type="file" multiple={false} accept={accept ?? "image/png"} style={{ visibility: 'hidden' }}
    onChange={onChange}
    onClick={onInputClick}
  />
})