import React, { FC, useEffect, useState } from 'react';
import styles from './index.less';
import { LoadingOutlined } from '@ant-design/icons';
import { Spin } from 'antd';

interface PageProps {
  type?: string; // 按钮类型
  text?: string; // 按钮文字
  disabled?: boolean; // 按钮禁用
  style?: any; //样式
  loading?: boolean; // 加载中
  onClick?: () => void;
}

// 按钮类型有以下几种：confirm（确认）, cancel（取消）, delete(删除), special(特殊) 
const ButtonComp: FC<PageProps> = ({
  type = 'confirm',
  text = '确定',
  disabled = false,
  style = {},
  loading = false,
  onClick = () => {},
}) => {
  const [isLoading, setIsLoading] = useState(loading);

  useEffect(() => {
    setIsLoading(loading);
  }, [loading]);

  const click = () => {
    if (disabled || isLoading) return;

    const timerId = setTimeout(() => {
      onClick();
    }, 300);

    return () => clearTimeout(timerId);
  };

  const buttonStyle = {
    opacity: isLoading ? 0.8 : 1,
    ...style,
  };

  return (
    <div style={{ display: 'flex' }}>
      <div
        style={buttonStyle}
        className={`${styles.btn} ${styles[type + '_btn']} ${disabled ? styles.disabled : ''}`}
        onClick={click}
      >
        {isLoading ? (
          <>
            <Spin size="small" style={{ color: '#fff', marginRight: 10 }} indicator={<LoadingOutlined spin />} />
            <span>{`${text}中`}</span>
          </>
        ) : (
          text
        )}
      </div>
    </div>
  );
};

export default ButtonComp;
