/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-12-26 17:29:47
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-01-21 22:37:13
 * @FilePath: /CostAccountingSys/src/pages/reportExport/report/ProgressModal.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 } 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);

  useEffect(() => {
    const fetchPageData = async () => {
      if (!isFetchingRef.current) {
        isFetchingRef.current = true;
        const data = await fetchData();
        const currentProgress = Math.round((data.currentCount / data.totalCount) * 100);
        console.log({currentProgress,data});
        setProgress(currentProgress);
        if (currentProgress >= 100||progress >= 100) {
          onCompletion();
          setProgress(0);
        } else {
          setTimeout(fetchPageData, 1000); // 计划下一次请求
        }

        isFetchingRef.current = false;

      }
    };

    if (visible) {
      fetchPageData();
    }


    return () => {
      isFetchingRef.current = false; // 在组件卸载时重置标志
    };
  }, [visible, fetchData]);

  return (
    <Modal title="导出进度" open={visible} footer={null} onCancel={onCancel}>
      <Progress percent={progress} />
    </Modal>
  );
};

export default ExportProgressModal;
