import React, { useCallback, useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";
import { FileImgListType } from "@/types";
import { API_upFile } from "@/store/action/layout";
import { MessageFu } from "@/utils/message";
import { fileDomInitialFu } from "@/utils/domShow";
import { forwardRef, useImperativeHandle } from "react";
import { Button, Popconfirm } from "antd";
import {
  EyeOutlined,
  UploadOutlined,
  CloseOutlined,
  DownloadOutlined,
} from "@ant-design/icons";
import classNames from "classnames";
import { baseURL } from "@/utils/http";
import filesLookFu from "@/utils/filesLook";
import { A1_APIremoveSure } from "@/store/action/A1Project";

type Props = {
  max: number; //最多传多少个文件
  isLook: boolean; //是否是查看
  ref: any; //当前自己的ref，给父组件调用
  fileCheck: boolean;
  dirCode: string; //文件的code码
  myUrl: string;
  fromData?: any;
  lookData: FileImgListType[]; //编辑或者 查看 回显
  accept?: string;
  // result:成果 | list:清单
  type?: string;
};

function Z3upFiles(
  { max, isLook, type="doc", fileCheck, dirCode, myUrl, fromData, lookData, accept=".zip" }: Props,
  ref: any
) {
  const [fileList, setFileList] = useState<FileImgListType[]>([]);

  useEffect(() => {
    if (lookData && lookData.length > 0) setFileList(lookData);
  }, [lookData]);

  const myInput = useRef<HTMLInputElement>(null);

  // 上传文件
  const handeUpPhoto = useCallback(
    async (e: React.ChangeEvent<HTMLInputElement>) => {
      if (e.target.files) {
        // 拿到files信息
        const filesInfo = e.target.files[0];

        // 校验格式
        if (!filesInfo.name.includes(".zip") && accept !== '*') {
          e.target.value = "";
          return MessageFu.warning(`只支持zip格式!`);
        }

        // 创建FormData对象
        const fd = new FormData();
        // 把files添加进FormData对象（‘photo’为后端需要的字段）
        fd.append("type", type);
        fd.append("dirCode", dirCode);
        fd.append("file", filesInfo);

        if (fromData) {
          for (const k in fromData) {
            if (fromData[k]) fd.append(k, fromData[k]);
          }
        }

        e.target.value = "";

        try {
          const res = await API_upFile(fd, myUrl);
          if (res.code === 0) {
            MessageFu.success("上传成功!");
            setFileList([...fileList, res.data]);
          }
          fileDomInitialFu();
        } catch (error) {
          fileDomInitialFu();
        }
      }
    },
    [dirCode, fileList, fromData, myUrl]
  );

  // 列表删除某一个文件
  const delImgListFu = useCallback(
    async (id: number) => {
      const res = await A1_APIremoveSure([id + ""]);

      if (res.code === 0) {
        const newItems = fileList.filter((v) => v.id !== id);
        setFileList(newItems);
      }
    },
    [fileList, setFileList]
  );

  // 让父组件调用，拿到 附件信息
  const filesIdRes = useCallback(() => {
    return fileList.map((v) => v.id);
  }, [fileList]);

  // 可以让父组件调用子组件的方法
  useImperativeHandle(ref, () => ({
    filesIdRes,
  }));

  return (
    <div className={styles.Z3upFiles}>
      <input
        id="upInput"
        type="file"
        accept={accept}
        ref={myInput}
        onChange={(e) => handeUpPhoto(e)}
      />
      <div className="Z3Btn">
        {fileList.length < max && !isLook ? (
          <Button
            onClick={() => myInput.current?.click()}
            icon={<UploadOutlined rev={undefined} />}
          >
            上传
          </Button>
        ) : null}

        <div className="Z3files">
          {fileList.map((v) => (
            <div className="Z3filesRow" key={v.id}>
              <div className="Z3files1" title={v.fileName}>
                {v.fileName}
              </div>
              <div className="Z3files2">
                {filesLookFu(v.fileName) ? (
                  <>
                    <EyeOutlined
                      rev={undefined}
                      title="查看"
                      onClick={() => filesLookFu(v.fileName, v.filePath)}
                    />
                    &emsp;
                  </>
                ) : null}
                <a
                  title="下载"
                  href={baseURL + v.filePath}
                  download={v.fileName}
                  target="_blank"
                  rel="noreferrer"
                >
                  <DownloadOutlined rev={undefined} />
                </a>
                &emsp;
                <Popconfirm
                  title="删除后无法恢复，是否删除?"
                  okText="删除"
                  cancelText="取消"
                  onConfirm={() => delImgListFu(v.id)}
                  okButtonProps={{ loading: false }}
                >
                  <CloseOutlined rev={undefined} title="删除" hidden={isLook} />
                </Popconfirm>
              </div>
            </div>
          ))}
        </div>

        <div className="fileTit" hidden={isLook}>
          此处的附件为对外的项目成果文件，仅支持zip格式，最多10个
          <br />
          <div
            className={classNames(
              "noUpThumb",
              fileList.length <= 0 && fileCheck ? "noUpThumbAc" : ""
            )}
          >
            请上传视频!
          </div>
        </div>
      </div>
      {isLook && fileList.length <= 0 ? (
        <div className="lookNone">（空）</div>
      ) : null}
    </div>
  );
}

export default forwardRef(Z3upFiles);
