import React, { useEffect, useRef, useState } from "react";
import { ConfigProvider, Spin, Upload } from "antd";
import Icon from "../icon";
import { Button } from "../index";
import Radio from "../radio";
import styles from "./index.less";
import NineImg from "./NineImg";

export default function CustomUpload({
  onCustomEvents,
  loading,
  value,
  type,
  accept,
  showDownload = true,
  content,
  disabled,
  onChange,
  maxSize,
  customRequest,
  url,
  config,
}) {
  const [_checked, setChecked] = useState(false);
  const r = useRef();
  const handleDownload = (e) => {
    e.stopPropagation();
    window.open(value);
  };

  const onRadioChange = (e) => {
    const { checked } = e.target;
    setChecked(checked);
    checked &&
      onCustomEvents &&
      onCustomEvents({
        data: {
          value,
          accept,
        },
        type: "save",
      });
  };

  const handleClear = (e) => {
    e.stopPropagation();
    onChange("");
  };

  useEffect(() => {
    setChecked(false);
  }, [value]);

  useEffect(() => {
    r.current.addEventListener("mouseenter", onMouseEnter);
    r.current.addEventListener("mouseleave", onMouseLeave);
    return () => {
      r.current.removeEventListener("mouseenter", onMouseEnter);
      r.current.removeEventListener("mouseleave", onMouseLeave);
      document.removeEventListener("paste", handPaste);
    };
  }, [customRequest]);

  const onMouseLeave = (e) => {
    e.stopPropagation();
    document.removeEventListener("paste", handPaste);
  };
  const onMouseEnter = (e) => {
    e.stopPropagation();
    document.addEventListener("paste", handPaste);
  };

  const handPaste = (e) => {
    e.stopPropagation();
    if (!(e.clipboardData && e.clipboardData.items)) {
      return;
    }
    const item = e.clipboardData.items[e.clipboardData.items.length - 1];
    const pasteFile = item.getAsFile();
    pasteFile && customRequest({ file: pasteFile });
  };

  const dragEnter = (event) => {
    // 进入当前
    event.stopPropagation();
    r.current.style.cssText = "border-color:var(--easyv-primary-color)";
  };

  const drop = (event) => {
    // 松手
    event.preventDefault();
    const file = event.dataTransfer.files[0];
    if (file && (accept ? accept.includes(file.type.split("/")[0]) : true)) {
      customRequest({ file });
    }
    dragLeave();
  };

  const dragLeave = () => {
    r.current.style.cssText = "border-color:#181b24";
  };
  const dragOver = (event) => {
    event.preventDefault();
    dragEnter(event);
  };

  const is_video_or_picture = ["image", "uploadImage", "video", "pointNineImage"].includes(type);

  const isShowChange = (is_video_or_picture || ["uploadModel"].includes(type)) && onCustomEvents;
  const upControl = {
    accept,
    maxSize,
    customRequest,
    disabled,
  };
  return (
    <div className={styles.upload}>
      <div
        className={styles.uploadBox}
        ref={r}
        onDragEnter={dragEnter}
        onDrop={drop}
        onDragLeave={dragLeave}
        onDragOver={dragOver}
      >
        {value && <div className={styles.center}>{content}</div>}
        {!loading && (
          <div className={styles.uploadFile}>
            <Upload
              accept={accept}
              maxSize={maxSize}
              showUploadList={false}
              withCredentials={true}
              customRequest={customRequest}
              disabled={disabled}
            >
              <ConfigProvider autoInsertSpaceInButton={false}>
                <Button type="primary" size="small">
                  上传
                </Button>
              </ConfigProvider>
            </Upload>

            {isShowChange && (
              <div className={styles.uploadChange}>
                <ConfigProvider autoInsertSpaceInButton={false}>
                  <Button
                    type="primary"
                    onClick={() => {
                      onCustomEvents &&
                        onCustomEvents({
                          data: {
                            type,
                            accept: accept ? accept : "image/*",
                          },
                          type: "change",
                        });
                    }}
                    ghost
                    size="small"
                  >
                    更改
                  </Button>
                </ConfigProvider>
              </div>
            )}
          </div>
        )}
        {value && (
          <div>
            {showDownload && (
              <Icon
                title="下载"
                type="download"
                onClick={handleDownload}
                style={{ cursor: "pointer", fontSize: "14px", transform: "translate(9px,-8px)" }}
              />
            )}
            <Icon
              title="删除"
              type="btn_delete"
              onClick={handleClear}
              style={{ cursor: "pointer", fontSize: "14px", transform: "translate(8px,-8px)" }}
            />
            {type === "pointNineImage" ? (
              <NineImg
                upControl={upControl}
                ulAfter={url}
                url={value}
                config={config}
                onChange={onChange}
              />
            ) : null}
          </div>
        )}
        {loading && (
          <div
            style={{
              position: "absolute",
              left: 0,
              right: 0,
              top: 0,
              bottom: 0,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <Spin />
          </div>
        )}
      </div>
      {is_video_or_picture && onCustomEvents && value && (
        <div className={styles.radio}>
          <Radio value={_checked} onChange={onRadioChange} checked={_checked}>
            保存为素材
          </Radio>
        </div>
      )}
    </div>
  );
}
