import { useRequest } from 'ahooks';
import { Empty, Spin } from 'antd';
import classNames from 'classnames';
import React, { useEffect, useState } from 'react';
import Icon, { IconImg } from '../../../components/Icon';
import Truly from '../../../components/Truly';
import { FileController } from '../../../services';
import styles from './index.less';

interface FileImageSelectProps {
  onSelect: (pick: FileController.FileFields) => void;
  picType: string;
}

const FileImageSelect: React.FC<FileImageSelectProps> = ({
  onSelect,
  picType,
}) => {
  const [type] = useState('0');
  const {
    data: fileList,
    loading: getFileListLoading,
    run: getFileListRun,
  } = useRequest(FileController.getListApi, {
    manual: true,
  });

  useEffect(() => {
    getFileListRun({ type, picType });
  }, [picType, type, getFileListRun]);

  return (
    <div>
      <div>
        <div className={styles.imagePanel}>
          <Truly truly={getFileListLoading}>
            <div className={styles.imageLoading}>
              <Spin></Spin>
            </div>
          </Truly>
          <Truly
            truly={(fileList || []).length > 0}
            falsyRender={<Empty description=""></Empty>}
          >
            <div className={styles.imageItems}>
              {(fileList || []).map((item) => {
                return (
                  <div
                    className={classNames({
                      [styles.imageItem]: true,
                    })}
                    style={{
                      width: item.picType === '1' ? 64 : 160,
                      height: item.picType === '1' ? 64 : 160,
                    }}
                    key={item.fileId}
                    onClick={() => {
                      onSelect(item);
                    }}
                  >
                    <Truly
                      truly={item.isSvg === '1'}
                      falsyRender={
                        <IconImg
                          url={item.filePath || ''}
                          width={item.picType === '1' ? 32 : 80}
                        ></IconImg>
                      }
                    >
                      <Icon svg={item.fileContent} size={32}></Icon>
                      <span className={styles.imageItemTitle}>svg</span>
                    </Truly>
                  </div>
                );
              })}
            </div>
          </Truly>
        </div>
      </div>
    </div>
  );
};

export default FileImageSelect;
