import { ref, computed } from 'vue';
import { CHANGE_EVENT } from '../_util/constants';
import useFormAdaptor from '../_util/use/useFormAdaptor';
import { useNormalModel } from '../_util/use/useModel';

function genUid(seed) {
  return Date.now() + seed;
}

//  <input type="file" /> 所需的数据
const useInputFile = (props, emit) => {
  const [currentFiles, updateCurrentFiles] = useNormalModel(props, emit);
  const inputRef = ref(null);

  // 表单组件的总体disabled状态
  const {
    isFormDisabled
  } = useFormAdaptor();
  const disabled = computed(() => props.disabled || isFormDisabled.value);
  const accept = computed(() => props.accept);
  const acceptStr = computed(() => accept.value.join(','));
  const multiple = computed(() => props.multiple);
  const openFileExplorer = () => {
    if (disabled.value) {
      return;
    }
    inputRef.value.click();
  };
  let tempIndex = 1;
  const handleInputFileChange = e => {
    const target = e.target;
    const files = Array.from(target.files);
    if (!files) {
      return;
    }
    files.forEach(rawFile => {
      const uid = genUid(tempIndex++);
      rawFile.uid = uid;
    });
    updateCurrentFiles(files);
    emit(CHANGE_EVENT, files);

    // 若不重置，重复选择相同文件，change 事件可能不触发
    target.value = null;
  };
  return {
    currentFiles,
    updateCurrentFiles,
    inputRef,
    disabled,
    multiple,
    accept,
    acceptStr,
    openFileExplorer,
    handleInputFileChange
  };
};

export { useInputFile };
