import { useState, useRef } from 'react';
import { useGetOssGetgeneratepresignedurl } from '../../generated/api';
import { YModal } from '../../modal';
import { YUploadFile } from '../common/interface';
import { isExpire } from '../common/utils';
import { ChangeType } from '../upload.interface';
import { PreviewItemProps, PreviewListProps } from './interface';

export const useModel = (props: PreviewItemProps) => {
  const { fileListRef, file, projectId, expire, setFileList } = props;
  const {
    getOssGetgeneratepresignedurlData,
  } = useGetOssGetgeneratepresignedurl();
  const [loadingStatus, setLoadingStatus] = useState(0); // 0: 成功 1: 进行中 2: 失败
  const [previewUrl, setPreviewUrl] = useState('');

  // 获取预览接口
  const getNewUrl = async (allIndex?: number) => {
    if (loadingStatus === 1) return;
    const { ossFile } = file;
    setLoadingStatus(1);

    const params: { [name: string]: any } = {
      projectId: projectId || '',
      ossFile,
    };
    if (expire) params.expire = expire;

    try {
      const res: any = await getOssGetgeneratepresignedurlData(params as any);
      if (!res || !res.url) {
        setLoadingStatus(2);
        return null;
      }
      setLoadingStatus(0);
      setPreviewUrl(res.url);

      const newFile = {
        ...file,
        ossFile: params.ossFile,
        url: res.url,
      };

      if (allIndex) {
        const list = [...fileListRef.current];
        list[allIndex] = newFile;
        setFileList(list, [newFile], ChangeType.PREVIEW);
        return;
      }

      return newFile;
    } catch {
      setLoadingStatus(2);
      return null;
    }
  };

  return {
    previewUrl,
    loadingStatus,
    getNewUrl,
  };
};

export const useListModel = (props: PreviewListProps, itemRef: any) => {
  const {
    fileModalRef,
    itemProps,
    imgModalRef,
    showFileModel,
    fileList,
  } = props;
  const { securityType, fileDisabled, fileListRef, setFileList } = itemProps;
  const refreshRef = useRef({
    isLoading: false,
  });

  // 链接初始化检测
  const urlCheck = async () => {
    refreshRef.current.isLoading = true;
    const newFileList = [];
    const errorUidList = [];
    const list = [...fileListRef.current];
    for (let i = 0; i < list.length; i++) {
      const { url, ossFile, uid } = fileList[i];
      // 链接过期判断
      if (!isExpire(url, ossFile, securityType)) continue;
      try {
        const newFile = await itemRef.current[uid].getNewUrl();
        if (newFile) {
          newFileList.push(newFile);
          list[i] = { ...newFile };
        } else {
          errorUidList.push(uid);
        }
      } catch (_error) {
        errorUidList.push(uid);
      }
    }
    refreshRef.current.isLoading = false;
    if (newFileList.length) {
      setFileList(list, newFileList, ChangeType.PREVIEW);
    }
    return errorUidList;
  };

  // 删除
  const onRemove = (file: YUploadFile) => {
    const { uid, disabled } = file;
    if (
      fileDisabled ||
      fileModalRef.current?.filePreviewStatus === 1 ||
      refreshRef.current.isLoading ||
      itemRef.current[uid].loadingStatus === 1 ||
      disabled
    ) {
      return;
    }

    YModal.confirm({
      title: '提示',
      content: '确定要删除此文件?',
      onOk: () => {
        const list = fileList.filter((item: any) => item.uid !== uid);
        setFileList(list, [file], ChangeType.REMOVE);
      },
      onCancel: () => {},
    });
  };
  // 预览
  const onPreview = async (file: YUploadFile, imgIndex: number) => {
    if (
      fileModalRef.current?.filePreviewStatus === 1 ||
      refreshRef.current.isLoading ||
      itemRef.current[file.uid].loadingStatus === 1
    ) {
      return;
    }
    // 链接过期检测
    const errorUidList = await urlCheck();
    // 当前预览的文件获取失败
    if (errorUidList.indexOf(file.uid) > -1) {
      return;
    }

    if (file.fileType === 'image') {
      imgModalRef.current?.show(imgIndex);
    } else if (file.fileType !== 'image' && typeof window !== 'undefined') {
      const lastOssFile =
        file.ossFile || (securityType === 'public' ? file.url : '');
      fileModalRef.current?.show(file.url, showFileModel ? lastOssFile : '');
    }
  };

  return {
    isLoading: refreshRef.current.isLoading,
    urlCheck,
    onRemove,
    onPreview,
  };
};
