import {BaseResultContent} from '@models';
import {userStore} from '@stores';
import {NETWORK_URL} from '@utils';
import {useBoolean} from 'ahooks';
import {UploadProps, message} from 'antd';
import {useMemo} from 'react';
import {useStore} from 'zustand';

export function useUpload(url: string, onFetch: () => void) {
  const {id, token} = useStore(userStore);
  const [isUploading, {set}] = useBoolean();
  const props = useMemo<UploadProps<BaseResultContent<unknown>>>(
    function () {
      return {
        name: 'file',
        action: `${NETWORK_URL}${url}`,
        headers: {
          token,
          userId: String(id),
        },
        showUploadList: false,
        onChange(info) {
          set(info.file.status === 'uploading');

          if (info.file.status === 'error') {
            message.error('上传失败，请稍后再试');
          }

          if (info.file.status === 'done') {
            if (info.file.response) {
              const {msg} = info.file.response;

              if (msg === '200') {
                message.success('上传成功');
                onFetch();
              } else {
                message.error(info.file.response.errMsg);
              }
            } else {
              message.error('上传失败');
            }
          }
        },
      };
    },
    [id, onFetch, set, token, url],
  );

  return {uploadProps: props, isUploading};
}
