import { useState, useEffect, useRef } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { YUploadFile } from './common/interface';
import { ChangeType, YUploadProps } from './upload.interface';
import { getStringFile, getObjFile } from './common/utils';

export const useModel = (props: YUploadProps) => {
  const { quantity = 1, value: dataSource, onChange, setFileParams } = props;
  const fileListRef = useRef<YUploadFile[]>([]);
  const refreshValueRef = useRef<number>(0);
  const [refreshValue, setRefreshValue] = useState<number>(0);
  const [fileList, setFileList] = useState<YUploadFile[]>([]);
  const changeFileList = (
    list: YUploadFile[],
    changeFileList?: YUploadFile[],
    type?: ChangeType,
  ) => {
    let isTrigger = !!(changeFileList && type);

    fileListRef.current =
      (isTrigger && setFileParams && setFileParams(list)) || list;
    setFileList(fileListRef.current);

    if (isTrigger) {
      onChange &&
        onChange(
          fileListRef.current,
          changeFileList as YUploadFile[],
          type as ChangeType,
        );
    }
  };

  // 初始化
  const initFileList = () => {
    if (dataSource) {
      let list: YUploadFile[] = [];
      let file = {
        url: '',
        size: 100,
        name: '',
        type: '',
        uid: uuidv4(),
        originalName: '',
      };
      const originalList = !(
        typeof dataSource === 'object' && dataSource instanceof Array
      )
        ? [dataSource]
        : dataSource;
      // 默认值为数组
      originalList.length &&
        originalList.forEach((item) => {
          list.push({
            ...file,
            ...(typeof item === 'string'
              ? getStringFile(item)
              : getObjFile(item)),
            uid: uuidv4(),
          });
        });
      // 过滤地址为空的元素
      list = list.filter((item) => item.url);
      // 默认值过多
      let deleteList: YUploadFile[] = [];
      if (list.length > quantity) {
        deleteList = list.slice(quantity, list.length);
        list = list.slice(0, quantity);
      }

      refreshValueRef.current = refreshValueRef.current + 1;
      setRefreshValue(refreshValueRef.current);
      changeFileList(
        list,
        deleteList,
        deleteList.length ? ChangeType.INIT_DELETE : ChangeType.INIT,
      );
    }
  };

  useEffect(() => {
    if (
      !(
        Array.isArray(dataSource) &&
        JSON.stringify(dataSource) == JSON.stringify(fileList)
      )
    ) {
      initFileList();
    }
  }, [quantity, dataSource]);

  return {
    fileList,
    fileListRef,
    refreshValue,
    setFileList: changeFileList,
  };
};
