import EasyvButton from 'components/EasyvButton';
import FileCard from 'components/FileCard';
import React, { memo, useState } from 'react';
import styles from './ScreenItem.less';

function ScreenItem({ screenName, deletedAt, expiredAt, thumb, onRestore }) {
  const [loading, setLoading] = useState(false);

  const handleClick = throttle(async () => {
    setLoading(true);
    await onRestore();
    setLoading(false);
  }, 1000);
  return (
    <FileCard
      appPreviewImgUrl={thumb}
      hoverRenderNode={
        <div className={styles.screenItemTrash}>
          <span style={{ width: 150, textAlign: 'center' }}>{deletedAt}</span>
          <EasyvButton theme="primary" onClick={loading ? undefined : handleClick}>
            恢复
          </EasyvButton>
        </div>
      }
      renderFooter={
        <div className={styles.screenItemContent}>
          <p title={screenName} className={styles.screenItemContentTrashTitle}>
            {screenName}
          </p>

          <span className={styles.screenItemContentScreenStatus} style={{ fontSize: '12px', color: '#B4B7C1' }}>
            {calcInternalTime(new Date(expiredAt), new Date())}天后清空
          </span>
        </div>
      }
    />
  );
}

const calcInternalTime = (t1, t2) => {
  return Math.ceil((t1.getTime() - t2.getTime()) / (1000 * 60 * 60 * 24));
};

const throttle = (fn, delay) => {
  let preTime = Date.now();

  return () => {
    let doTime = Date.now();
    if (doTime - preTime >= delay) {
      fn();
      preTime = Date.now();
    }
  };
};

export default memo(ScreenItem);
