/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-12-28 20:32:45
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-03-08 15:10:59
 * @FilePath: /CostAccountingSys/src/components/ProgressModal/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useEffect, useState } from 'react';
import { Modal, Progress } from 'antd';
import { getPercentData, stopGetPercentData } from './service';

interface ProgressModalProps {
  type: string;
  onComplete: () => void;
  visible: boolean;
  title: string;
}

const ProgressModal: React.FC<ProgressModalProps> = ({
  type,
  onComplete,
  visible,
  title,
}) => {
  const [progressPercent, setProgressPercent] = useState(0);
  const [processStr, set_processStr] = useState('');

  const fetchProgressData = async () => {
    try {
      const response = await getPercentData(type); // 替换为你的API端点
      if (response) {
        if (type == 'ITEM_BATCH_MATCH') {
          const [cur, total] = response.split('/');
          setProgressPercent(Math.floor((cur / total) * 100));
          set_processStr(response);
        } else {
          setProgressPercent(response);
        }

        if (response >= 100) {
          onComplete(); // 当进度达到100%时，触发完成回调
        }
      }
    } catch (error) {
      console.error('Error fetching progress data:', error);
    }
  };

  const stopHandle = async () => {
    const resp = await stopGetPercentData(type);
    if (resp) {
      onComplete();
    }
  };

  useEffect(() => {
    let pollingInterval: NodeJS.Timeout | null = null;
    if (visible) {
      setProgressPercent(0); // 重置进度
      pollingInterval = setInterval(fetchProgressData, 1000); // 开始轮询
    } else {
      progressPercent > 0 && stopHandle();
    }

    return () => {
      if (pollingInterval) {
        clearInterval(pollingInterval); // 清理轮询
      }
    };
  }, [visible, type]); // 依赖项包括 visible 和 type

  return (
    <Modal
      title={title}
      open={visible}
      footer={null}
      closable={false} // 如果不需要模态框的关闭按钮，可以设置为 false
    >
      <Progress percent={progressPercent} />
      {type == 'ITEM_BATCH_MATCH' && (
        <>
          <div
            style={{
              fontSize: 14,
              color: '#525866',
              marginTop: 3,
              marginBottom: 24,
            }}
          >
            已完成{processStr}
          </div>
          <div
            onClick={() => stopHandle()}
            style={{
              width: 56,
              height: 24,
              textAlign: 'center',
              fontSize: 14,
              marginLeft: 430,
              color: '#17181A',
              cursor: 'pointer',
              background: '#FAFCFF',
              borderRadius: 4,
              border: '1px solid #DAE2F2',
            }}
          >
            取消
          </div>
        </>
      )}
    </Modal>
  );
};

export default ProgressModal;
