import React, { useState, useCallback, useRef } from 'react';
import cx from 'classnames';
import { Button, Checkbox, message } from 'antd';
import { importUsers } from './service';
import { useModel, history } from 'umi';
import iconExcel from './icon-excel.svg';
import iconErrorExcel from './icon-excel-error.svg';
import styles from './index.less';

const isExcel = (type) => {
  return (
    [
      'text/csv',
      '.csv',
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    ].indexOf(type) >= 0
  );
};

export default ({ onUploadDone }) => {
  const [draggingOver, setDraggingOver] = useState(false);

  const [fileInfo, setFileInfo] = useState({});
  const [autoSendActiveMsg, setAutoSendActiveMsg] = useState(true);
  const [errorInfo, setErrorInfo] = useState('');
  const [uploading, setUploading] = useState(false);
  const fileInputRef = useRef();
  /**
   * 0： 开始选择
   * 1： 文件选择之后，且符合规范
   * 2： 文件选择之后，不符合规范
   * 3： 文件上传失败
   */
  const [uploadState, setUploadState] = useState(0);
  const { initialState } = useModel('@@initialState');
  const handleFileSelected = useCallback((e) => {
    const file = e.target.files[0];

    if (!file) {
      setUploadState(3);
    }
    setFileInfo({
      file,
      name: file.name,
      size: `${Math.ceil(file.size / 1024)}K`,
    });
    if (!isExcel(file.type)) {
      setErrorInfo('不支持此类文件格式');
      setUploadState(2);
    } else if (file.size > 1024 * 1024 * 10) {
      setErrorInfo('文件大小不能超过 10MB');
      setUploadState(2);
    } else {
      setUploadState(1);
    }
    e.target.value = '';
  }, []);

  const beginUpload = useCallback(() => {
    setUploading(true);
    let params = {
      companyId: initialState?.currentUser?.companyId,
    };
    importUsers(fileInfo.file, params)
      .then((res) => {
        setUploading(false);
        if (res.key) {
          onUploadDone(res);
        } else {
          message.error(res.message);
          setUploadState(0);
        }
      })
      .catch(() => {
        // 文件上传失败
        setUploading(false);
        setUploadState(3);
      });
  }, [fileInfo, autoSendActiveMsg, onUploadDone]);

  return (
    <div
      className={cx(styles.c, {
        [styles.dragging]: draggingOver,
      })}
      onDragEnter={(e) => {
        e.preventDefault();
        e.stopPropagation();
        setDraggingOver(true);
      }}
      onDragOver={(e) => {
        setDraggingOver(true);
        e.preventDefault();
        e.stopPropagation();
        return false;
      }}
      onDragLeave={(e) => {
        e.preventDefault();
        e.stopPropagation();
        setDraggingOver(false);
      }}
      onDrop={(e) => {
        e.preventDefault();
        e.stopPropagation();
        setDraggingOver(false);
        handleFileSelected({
          target: {
            files: e.dataTransfer.files,
          },
        });
      }}
    >
      <input type="file" hidden ref={fileInputRef} onChange={(e) => handleFileSelected(e)} />
      <div className={styles.title}>
        <span>2&nbsp;/</span>
        上传填写完后的表格文件
      </div>

      {uploadState === 0 && (
        <div className={styles.fileTrigger}>
          <img src={iconExcel} />
          <div>
            <span onClick={() => fileInputRef.current.click()}>点击选择文件</span>
            ，或将文件拖拽到此处
          </div>
        </div>
      )}

      {uploadState === 1 && (
        <div className={styles.fileInfo}>
          <img src={iconExcel} />
          <div>
            {fileInfo.name} ({fileInfo.size})&nbsp;&nbsp;
            <span onClick={() => fileInputRef.current.click()}>重新选择文件</span>
          </div>
          <section>
            <Button
              type="primary"
              size="large"
              style={{ margin: '30px 0 20px' }}
              loading={uploading}
              onClick={() => {
                beginUpload();
              }}
            >
              开始上传
            </Button>
            <br />
            {/* <Checkbox checked={autoSendActiveMsg} onChange={e => setAutoSendActiveMsg(e.target.checked)}>导入后自动发送短信提醒其激活账号</Checkbox> */}
          </section>
        </div>
      )}

      {uploadState === 2 && (
        <div className={styles.fileError}>
          <img src={iconErrorExcel} />
          <div>
            {errorInfo}，<span onClick={() => fileInputRef.current.click()}>重新选择文件</span>
          </div>
        </div>
      )}

      {uploadState === 3 && (
        <div className={styles.fileError}>
          <img src={iconErrorExcel} />
          <div>
            {fileInfo.name} ({fileInfo.size})
          </div>
          <div>
            文件导入失败，请<span onClick={beginUpload}>再次上传</span>或
            <span onClick={() => fileInputRef.current.click()}>重新选择文件</span>
          </div>
        </div>
      )}
    </div>
  );
};
