import { useState, useRef } from 'react';
import { useGetOssGetofficepreviewurl } from '../../generated/api';
import { FilePreviewModelProps } from './interface';
import { getFileType } from '../common/utils';

const supportType = [
  'doc',
  'dot',
  'wps',
  'wpt',
  'docx',
  'dotx',
  'docm',
  'dotm',
  'pptx',
  'ppt',
  'pot',
  'potx',
  'pps',
  'ppsx',
  'dps',
  'dpt',
  'pptm',
  'potm',
  'ppsm',
  'xls',
  'xlt',
  'et',
  'ett',
  'xlsx',
  'xltx',
  'csv',
  'xlsb',
  'xlsm',
  'xltm',
  'pdf',
  'lrc',
  'c',
  'cpp',
  'h',
  'asm',
  's',
  'java',
  'asp',
  'bat',
  'bas',
  'prg',
  'cmd',
  'rtf',
  'txt',
  'log',
  'xml',
  'htm',
  'html',
];

const basePreview = {
  previewURL: '',
  accessToken: '',
  accessTokenExpiredTime: '',
  refreshNum: 0,
};

export const useModel = (props: FilePreviewModelProps) => {
  const {
    projectId,
    securityType = 'private',
    setIsRefreshFilePreview,
  } = props;
  const { getOssGetofficepreviewurlData } = useGetOssGetofficepreviewurl();
  const [previewData, setPreviewData] = useState({ ...basePreview });
  const [filePreviewStatus, setFilePreviewStatus] = useState(0); // 文件预览状态
  const [noData, setNoData] = useState(false); // 文件预览状态
  const refreshRef = useRef({
    previewFileUrl: '',
    ossFile: '',
  });
  // 链接检查
  const checkUrl = (previewFileUrl: string, ossFile?: string) => {
    const oldOssFile = refreshRef.current.ossFile;
    const isRefresh = ossFile !== oldOssFile;
    setPreviewData({
      ...(!isRefresh ? previewData : basePreview),
      refreshNum: previewData.refreshNum + 1,
    });
    setNoData(false);
    refreshRef.current = { previewFileUrl, ossFile: ossFile || '' };

    const fileType = getFileType(ossFile || '');
    if (ossFile && supportType.indexOf(fileType) > -1 && projectId) {
      setFilePreviewStatus(1);
      setIsRefreshFilePreview && setIsRefreshFilePreview(true);
      getOSSPreviewAPI(ossFile, isRefresh);
    } else if (previewFileUrl && typeof window !== 'undefined') {
      window.open(previewFileUrl, '_blank');
    } else {
      setNoData(true);
    }
  };
  // 获取预览接口
  const getOSSPreviewAPI = async (ossFile: string, isRefresh: boolean) => {
    let firstIndex =
      ossFile.indexOf('.com/') > -1 ? ossFile.indexOf('.com/') + 5 : 0;
    firstIndex =
      ossFile.indexOf('.com//') > -1
        ? ossFile.indexOf('.com/') + 6
        : firstIndex;
    firstIndex = securityType === 'private' ? 0 : firstIndex;

    const nowTime = new Date().valueOf() + 3 * 1000;
    if (
      !isRefresh &&
      previewData.accessTokenExpiredTime &&
      nowTime < new Date(previewData.accessTokenExpiredTime).valueOf()
    ) {
      // 链接未过期
      setFilePreviewStatus(3);
      setIsRefreshFilePreview && setIsRefreshFilePreview(false);
      return;
    }

    try {
      const previewInfo: any = await getOssGetofficepreviewurlData({
        securityType,
        projectId: projectId || '',
        ossFile: ossFile.substr(firstIndex, ossFile.length),
      });
      if (
        !previewInfo ||
        !previewInfo?.previewURL ||
        !previewInfo?.accessToken
      ) {
        setFilePreviewStatus(2);
        setIsRefreshFilePreview && setIsRefreshFilePreview(false);
        return;
      }
      setIsRefreshFilePreview && setIsRefreshFilePreview(false);
      setFilePreviewStatus(3);
      setPreviewData({ ...previewInfo, refreshNum: previewData.refreshNum });
    } catch (_error) {
      setFilePreviewStatus(2);
      setIsRefreshFilePreview && setIsRefreshFilePreview(false);
    }
  };
  // 隐藏
  const hide = () => {
    setFilePreviewStatus(0);
  };
  // 刷新
  const refresh = () => {
    const { previewFileUrl, ossFile } = refreshRef.current;
    checkUrl(previewFileUrl, ossFile);
  };

  return {
    noData,
    filePreviewStatus,
    previewData,
    refresh,
    hide,
    show: checkUrl,
    setFilePreviewStatus,
  };
};
