/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-12-26 17:29:47
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-11-14 15:40:58
 * @FilePath: /CostAccountingSys/src/pages/reportExport/report/ExportProgressModal.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useState, useEffect, useRef } from 'react';
import { Modal, Progress, message } from 'antd';

interface ExportProgressModalProps {
  visible: boolean;
  onCancel: () => void;
  fetchData: () => Promise<{ currentCount: number; totalCount: number }>;
  onCompletion: () => void;
}

const ExportProgressModal: React.FC<ExportProgressModalProps> = ({
  visible,
  onCancel,
  fetchData,
  onCompletion,
}) => {
  const [progress, setProgress] = useState<number>(0); // 进度百分比
  const isFetchingRef = useRef<boolean>(false); // 是否正在获取数据的标志，防止重复请求
  const intervalIdRef = useRef<NodeJS.Timeout | null>(null); // 定时器 ID
  const maxRetries = 3; // 最大重试次数
  const retryCountRef = useRef<number>(0); // 记录重试次数

  const fetchProgressData = async () => {
    if (isFetchingRef.current) return;

    isFetchingRef.current = true;
    try {
      const data = await fetchData();
      const { currentCount, totalCount } = data;

      // 严格比较导出的实际进度
      if (currentCount >= totalCount) {
        setProgress(100); // 设置最终进度为100%
        clearInterval(intervalIdRef.current!);
        intervalIdRef.current = null;
        message.success('导出完成！');
        onCompletion();
      } else {
        // 如果未完成，更新进度条并重置重试次数
        const currentProgress = Math.round((currentCount / totalCount) * 100);
        setProgress(currentProgress);
        retryCountRef.current = 0;
      }
    } catch (error) {
      console.error('获取进度数据出错:', error);
      retryCountRef.current += 1;

      if (retryCountRef.current > maxRetries) {
        clearInterval(intervalIdRef.current!);
        intervalIdRef.current = null;
        message.error('导出失败，请稍后重试！');
      }
    } finally {
      isFetchingRef.current = false;
    }
  };

  useEffect(() => {
    if (visible) {
      // 每秒调用 fetchProgressData
      intervalIdRef.current = setInterval(fetchProgressData, 1000);
    } else {
      setProgress(0); // 重置进度
      if (intervalIdRef.current) {
        clearInterval(intervalIdRef.current);
        intervalIdRef.current = null;
      }
    }

    return () => {
      if (intervalIdRef.current) {
        clearInterval(intervalIdRef.current);
        intervalIdRef.current = null;
      }
    };
  }, [visible]);

  return (
    <Modal
      title="导出进度"
      open={visible}
      footer={null}
      onCancel={() => {
        setProgress(0); // 关闭对话框时重置进度
        if (intervalIdRef.current) {
          clearInterval(intervalIdRef.current); // 清除定时器
          intervalIdRef.current = null;
        }
        onCancel();
      }}
    >
      <Progress percent={progress} />
    </Modal>
  );
};

export default ExportProgressModal;
