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

import { InboxOutlined } from "@ant-design/icons";
import {
  Button,
  message,
  Modal,
  Popconfirm,
  Select,
  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_APIIupBtnOk, A1_APIremoveInn } from "@/store/action/A1Project";
import { authFilesLookFu, urlChangeFu } from "@/utils/authFilesLook";
import { A2Tab2Type } from "@/types/api/A2Dict";

const { Dragger } = Upload;

// type SelectType = {
//   id: number;
//   value: number | undefined;
//   txt: string;
//   tit: string;
//   fileName: string;
//   resName:string
// };

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

type props = {
  myUrl: string;
  upFileFu: () => void;
  closeFu: () => void;
  myTitle: string;
  projectId: number;
  typeData: A2Tab2Type[];
};

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

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

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

  const timeRef = useRef(-1);

  // 下拉框改变
  const selectChangeFu = useCallback(
    (val: number, uid: string, id: number) => {
      const info = typeData.find((v) => v.id === val)!;

      const tit = info.suffix ? info.suffix : "all";

      const idName = info.name;

      // 如果已经有相同的重命名
      const resName = myTitle + "_" + idName;

      setFileList(
        fileList.map((v) => ({
          ...v,
          mySelect:
            v.uid === uid
              ? {
                  ...v.mySelect,
                  value: v.mySelect.id === id ? val : v.mySelect.value,
                  txt: v.mySelect.id === id ? info.description : v.mySelect.txt,
                  tit: v.mySelect.id === id ? tit : v.mySelect.tit,
                  resName,
                }
              : v.mySelect,
        }))
      );
    },
    [fileList, myTitle, typeData]
  );

  // 重命名的文件后缀
  const houzuiFu = useCallback((name: string) => {
    const arr = name.split(".") || [""];
    return "." + arr[arr.length - 1];
  }, []);

  // 校验指定格式
  const typeGeShiFlag = useCallback((val: string, name: string) => {
    if (val === "all") return false;
    else {
      let flag = true;

      const arr = val.split(",");

      arr.forEach((v) => {
        if (name.includes("." + v)) flag = false;
      });

      return flag;
    }
  }, []);

  // 确定按钮的格式校验(指定文件类型，没有对应上)
  const disBtnOkRes1 = useMemo(() => {
    let flag = false;

    const resArr = fileList.map((v) => v.mySelect || {});

    resArr.forEach((v) => {
      if (v.tit && v.tit !== "all") {
        const arr = v.tit.split(","); //['pdf','gif']

        const arr2 = v.fileName.split(".");

        const str = arr2[arr2.length - 1]; //66666.pdf  =>pdf

        if (arr.every((v2:any) => v2 !== str)) flag = true;
      }
    });
    return flag;
  }, [fileList]);

  //  确定按钮的格式校验（有下拉框没有选择）
  const disBtnOkRes2 = useMemo(() => {
    let flag = false;

    fileList.forEach((v) => {
      if (v.mySelect) {
        if (!v.mySelect.value) flag = true;
      } else flag = true;
    });

    return flag;
  }, [fileList]);

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

      const { status } = info.file;

      // 检查请求状态
      const response = info.file.response || {};

      if (status !== "uploading") {
        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" && response.code === 0) {
        // console.log("-----", info);
        setFileList(
          info.fileList.map((v) => ({
            ...v,
            mySelect:
              info.file.uid === v.uid
                ? {
                    id: info.file.response.data.id,
                    value: undefined,
                    txt: "",
                    tit: "",
                    resName: "",
                    fileName: info.file.name,
                  }
                : v.mySelect,
          }))
        );
        // message.success(`${info.file.fileName} 上传成功.`);
      } else if (status === "error") {
        message.error(`${info.file.fileName} 上传失败.`);
        // 去掉列表中的失败状态文件
        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_APIremoveInn(id);

              if (res.code === 0) {
                MessageFu.success("删除成功!");
                resolve(true);
              }
            } 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 arr: any = [];

    fileList.forEach((v) => {
      arr.push({
        attributeId: v.mySelect.value,
        fileName: v.mySelect.resName + houzuiFu(v.mySelect.fileName),
        id: v.mySelect.id,
      });
    });

    const res = await A1_APIIupBtnOk(projectId, arr);

    if (res.code === 0) {
      MessageFu.success("保存成功!");
      upFileFu();
      closeFu();
    }
  }, [closeFu, fileList, houzuiFu, projectId, 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_APIremoveInn(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.A1IupFile}
      destroyOnClose
      open={true}
      title="内控文件上传"
      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" id="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, i) => (
            <div className="myIncoRow" key={v.uid}>
              {v.percent === 100 && v.response && v.response.data ? (
                <>
                  {authFilesLookFu(v.response.data.fileName,'') ? (
                    <>
                      {/* // 1.预览（fileName里面有常用的，浏览器能识别的 图片 音频 视频 模型） */}
                      <div title="预览文件">
                        <EyeOutlined
                          rev={undefined}
                          onClick={() =>
                            authFilesLookFu(
                              v.response.data.fileName,
                              v.response.data.filePath
                            )
                          }
                        />
                      </div>
                    </>
                  ) : null}
                  {/* // 2.下载 */}
                  <div
                    title="下载文件"
                    onClick={() =>
                      urlChangeFu(
                        v.response.data.filePath,
                        true,
                        undefined,
                        v.response.data.fileName
                      )
                    }
                  >
                    <DownloadOutlined rev={undefined} />
                  </div>

                  {/* 下拉框 */}
                  <div className="A1IUselect">
                    <Select
                      getPopupContainer={() =>
                        document.querySelector("#A1OMain")!
                      }
                      style={{ width: 200 }}
                      placeholder="请选择"
                      value={v.mySelect.value || undefined}
                      onChange={(e) => selectChangeFu(e, v.uid, v.mySelect.id)}
                      options={typeData.map((v) => ({
                        value: v.id,
                        label: v.name,
                      }))}
                    />

                    {/* 没选择的时候的提示 */}
                    <div className="A1IUselectTit">
                      {v.mySelect && v.mySelect.value ? (
                        <div className="A1IUselectTit2">
                          <div title={v.mySelect.txt}>{v.mySelect.txt}</div>

                          {typeGeShiFlag(
                            v.mySelect.tit,
                            v.mySelect.fileName
                          ) ? (
                            <div
                              className="A1IUselectTit2Tit"
                              title={`该文件类型只支持 ${v.mySelect.tit}`}
                            >
                              &emsp;该文件类型只支持 {v.mySelect.tit} 格式
                            </div>
                          ) : null}
                        </div>
                      ) : (
                        <div className="A1IUselectTit1">请选择文件类型</div>
                      )}
                    </div>
                  </div>

                  {/* 重命名 */}
                  {v.mySelect.resName ? (
                    <div className="A1IUselectName">
                      <div className="A1IUselectName1">重命名为：</div>
                      <div
                        className="A1IUselectName2"
                        title={
                          v.mySelect.resName + houzuiFu(v.mySelect.fileName)
                        }
                      >
                        {v.mySelect.resName + houzuiFu(v.mySelect.fileName)}
                      </div>
                    </div>
                  ) : null}
                </>
              ) : (
                ""
              )}

              {/* 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 || disBtnOkRes1 || disBtnOkRes2}
        >
          确定
        </Button>
      </div>

      {contextHolder}
    </Modal>
  );
}

const MemoA1IupFile = React.memo(A1IupFile);
export default MemoA1IupFile;
