import { useCallback, useRef, useState } from "react";
import styles from "./index.module.scss";

import { InboxOutlined } from "@ant-design/icons";
import {
  Button,
  message,
  Modal,
  Popconfirm,
  Upload,
  UploadFile,
  UploadProps,
} from "antd";

import { EyeOutlined, DownloadOutlined } from "@ant-design/icons";

import history from "@/utils/history";
import React from "react";
import { getTokenFu } from "@/utils/storage";
import { MessageFu } from "@/utils/message";
import { A1_APIOupFileIds, A1_APIremoveOut } from "@/store/action/A1Project";
import { authFilesLookFu, urlChangeFu } from "@/utils/authFilesLook";

const { Dragger } = Upload;

const A1OtopBtnArr = [
  { id: 1, name: "上传文件夹" },
  { id: 2, name: "上传文件" },
];

type props = {
  myUrl: string;
  fromData: any;
  nowLoc: string;
  upFileFu: () => void;
  closeFu: () => void;
};

function A1OupFile({ myUrl, fromData, nowLoc, closeFu, upFileFu }: props) {
  // 文件夹和文件的选择
  const [isFiles, setIsFiles] = useState(1);

  const [modal, contextHolder] = Modal.useModal();

  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const timeRef = useRef(-1);

  const FileProps: UploadProps = {
    name: "file",
    multiple: true,
    action: myUrl,
    headers: {
      token: getTokenFu(),
    },
    // 支持上传文件夹
    directory: isFiles === 1,
    data: fromData,
    fileList,
    //不要前面的图标
    // iconRender: () => false,
    // 文件上传之前 -- 这里不用校验
    // beforeUpload(file, fileList) {
    //   // console.log("文件上传之前-用于校验", file);
    //   // if (file.name.includes("4dage")) {
    //   //   // console.log("校验不通过，不上传");
    //   //   message.error(`${file.name}不符合上传需求`);
    //   //   return Upload.LIST_IGNORE;
    //   // }
    // },
    onChange(info) {
      setFileList([...info.fileList]);

      const { status } = info.file;
      if (status !== "uploading") {
        // 检查请求状态
        const response = info.file.response || {};

        if (response.code !== 0) {
          setFileList(info.fileList.filter((v) => v.uid !== info.file.uid));
          clearTimeout(timeRef.current);

          timeRef.current = window.setTimeout(() => {
            MessageFu.warning(response.msg);
          }, 200);
        }
        if (response.code === 5001 || response.code === 5002) {
          message.warning("登录失效!");
          history.push("/login");
          return false;
        }

        // console.log(info.file, info.fileList);
      }
      if (status === "done") {
        // message.success(`${info.file.name} 上传成功.`);
      } else if (status === "error") {
        message.error(`${info.file.name} 上传失败.`);
        // 去掉列表中的失败状态文件
        setFileList(info.fileList.filter((v) => v.uid !== info.file.uid));
      }
    },
    // onDrop(e) {
    //   // console.log("拖动文件到上传区域", e.dataTransfer.files);
    // },
    // 点击删除
    async onRemove(info) {
      const promiseFu = new Promise((resolve: (value: boolean) => void) => {
        modal.confirm({
          title: "删除确认",
          content: "删除后无法恢复，是否删除?",
          okText: "删除",
          cancelText: "取消",
          async onOk() {
            if (info.percent === 100) {
              // console.log("-----还没有发请求删除", info);
              const id = info.response.data.id;
              // 已经上传完成，发请求删除
              const res = await A1_APIremoveOut(id);

              if (res.code === 0) {
                resolve(true);
                MessageFu.success("删除成功!");
              }
            } else {
              resolve(true);
              MessageFu.success("删除成功!");
            }
          },
          onCancel() {
            resolve(false);
          },
        });
      });
      return await promiseFu;
    },
  };

  // 点击确定
  const btnOkFu = useCallback(async () => {
    if (fileList.some((v) => v.percent !== 100))
      return message.warning("有文件未上传完成.");

    // 拿到 id集合

    const ids: number[] = [];

    fileList.forEach((v) => {
      ids.push(v.response.data.id);
    });

    const res = await A1_APIOupFileIds(ids.join(","));

    if (res.code === 0) {
      MessageFu.success("保存成功!");
      upFileFu();
      closeFu();
    }
  }, [closeFu, fileList, upFileFu]);

  // 点击取消 删除所有文件
  const clickCloseFu = useCallback(async () => {
    const arr: string[] = [];

    fileList.forEach((v) => {
      if (v.response && v.response.data) {
        arr.push(v.response.data.id);
      }
    });

    if (arr.length > 0) {
      const res = await A1_APIremoveOut(arr.join(","));

      if (res.code === 0) closeFu();
    } else closeFu();
  }, [closeFu, fileList]);

  // 点击按钮切换上传 文件夹 和 文件
  const changeFileType = useCallback((id: number) => {
    setIsFiles(id);

    setTimeout(() => {
      const dom: any = document.querySelector(
        ".ant-upload-wrapper .ant-upload input"
      )!;

      dom.click();
    }, 100);
  }, []);

  return (
    <Modal
      wrapClassName={styles.A1OupFile}
      destroyOnClose
      open={true}
      title={"上传文件 - " + nowLoc}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className="A1OtopBtn">
        {A1OtopBtnArr.map((v) => (
          <div key={v.id}>
            <Button onClick={() => changeFileType(v.id)} type="primary">
              {v.name}
            </Button>
          </div>
        ))}
      </div>

      <div className="A1OMain">
        <Dragger {...FileProps}>
          <p className="ant-upload-drag-icon">
            <InboxOutlined rev={undefined} />
          </p>
          <br />
          <p className="ant-upload-text">
            点击上传整个文件夹，或拖动多个文件至此上传
          </p>
        </Dragger>
        {/* 自定义 预览 下载 删除 */}
        <div className="myIncoBox">
          {fileList.map((v) => (
            <div className="myIncoRow" key={v.uid}>
              {v.percent === 100 && v.response && v.response.data ? (
                <>
                  {authFilesLookFu(v.response.data.name,'') ? (
                    <>
                      {/* // 1.预览（name里面有常用的，浏览器能识别的 图片 音频 视频 模型） */}
                      <div title="预览文件">
                        <EyeOutlined
                          rev={undefined}
                          onClick={() =>
                            authFilesLookFu(
                              v.response.data.name,
                              v.response.data.filePath
                            )
                          }
                        />
                      </div>
                    </>
                  ) : null}
                  {/* // 2.下载 */}
                  <div
                    title="下载文件"
                    onClick={() =>
                      urlChangeFu(
                        v.response.data.filePath,
                        true,
                        undefined,
                        v.response.data.name
                      )
                    }
                  >
                    <DownloadOutlined rev={undefined} />
                  </div>
                </>
              ) : (
                ""
              )}

              {/* 3.前面的序号 */}
              {/* <div className="mySortQ" hidden={fileList.length <= 1}>
                {i + 1}.
              </div> */}
            </div>
          ))}
        </div>
      </div>

      <div className="A1OUpBtn">
        <Popconfirm
          title="放弃编辑后，信息将不会保存!"
          okText="放弃"
          cancelText="取消"
          onConfirm={clickCloseFu}
          okButtonProps={{ loading: false }}
        >
          <Button>取消</Button>
        </Popconfirm>
        &emsp;
        <Button
          type="primary"
          onClick={btnOkFu}
          disabled={fileList.length <= 0}
        >
          确定
        </Button>
      </div>

      {contextHolder}
    </Modal>
  );
}

const MemoA1OupFile = React.memo(A1OupFile);
export default MemoA1OupFile;
