import React, { useCallback, useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";
import {
  PlusOutlined,
  EyeOutlined,
  CloseOutlined,
  DownloadOutlined,
} from "@ant-design/icons";
import { ReactSortable } from "react-sortablejs";
import ImageLazy from "@/components/ImageLazy";

import { Popconfirm } from "antd";
import store from "@/store";
import { baseURL } from "@/utils/http";
import { MessageFu } from "@/utils/message";
import { fileDomInitialFu } from "@/utils/domShow";
import classNames from "classnames";
import { API_upFile } from "@/store/action/layout";
import { FileImgListType } from "@/types";
import { forwardRef, useImperativeHandle } from "react";
import { A1_APIremoveSure } from "@/store/action/A1Project";

type Props = {
  max: number; //最多传多少张图片
  isLook: boolean; //是否是查看
  ref: any; //当前自己的ref，给父组件调用
  fileCheck: boolean;
  size: number; //上传图片大小（M）
  dirCode: string; //文件的code码
  myUrl: string;
  isCoverShow?: boolean; //是否显示第一张为封面
  format?: string[]; //上传图片格式
  formatTxt?: string; //上传图片提示
  sizeTxt?: string; //后面的建议尺寸信息
  fromData?: any;
  lookData: FileImgListType[]; //编辑或者 查看 回显
};

function Z1upImgs(
  {
    max,
    isLook,
    fileCheck,
    size,
    dirCode,
    myUrl,
    isCoverShow = false,
    format = ["image/jpeg", "image/png"],
    formatTxt = "png、jpg和jpeg",
    sizeTxt,
    fromData,
    lookData,
  }: 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];
        // 校验格式
        const type = format;
        if (!type.includes(filesInfo.type)) {
          e.target.value = "";
          return MessageFu.warning(`只支持${formatTxt}格式!`);
        }
        // 校验大小
        if (filesInfo.size > size * 1024 * 1024) {
          e.target.value = "";
          return MessageFu.warning(`最大支持${size}M!`);
        }
        // 创建FormData对象
        const fd = new FormData();
        // 把files添加进FormData对象（‘photo’为后端需要的字段）
        fd.append("type", "img");
        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, format, formatTxt, fromData, myUrl, setFileList, size]
  );

  // 列表删除某一张图片
  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 imgIdsRes = useCallback(() => {
    return fileList.map((v) => v.id);
  }, [fileList]);

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

  return (
    <div className={styles.Z1upImgs}>
      <input
        id="upInput"
        type="file"
        accept=".png,.jpg,.jpeg"
        ref={myInput}
        onChange={(e) => handeUpPhoto(e)}
      />

      <div
        hidden={(fileList.length && fileList.length >= max) || isLook}
        className="fileBoxRow_up"
        onClick={() => myInput.current?.click()}
      >
        <PlusOutlined rev={undefined} />
      </div>

      <ReactSortable
        disabled={isLook}
        className={classNames(
          "fileImgListBox",
          isLook ? "fileImgListBoxNo" : ""
        )}
        list={fileList}
        setList={setFileList}
      >
        {fileList.map((v, i) => (
          <div className="fileBoxRow_r_img" key={v.id}>
            {v.filePath ? (
              <ImageLazy noLook width={100} height={100} src={v.filePath} />
            ) : null}

            <Popconfirm
              title="删除后无法恢复，是否删除?"
              okText="删除"
              cancelText="取消"
              onConfirm={() => delImgListFu(v.id!)}
              okButtonProps={{ loading: false }}
            >
              <div className="clearCover" hidden={isLook}>
                <CloseOutlined rev={undefined} />
              </div>
            </Popconfirm>

            {/* 第一张为封面 */}
            {/* {isCoverShow && i === 0 ? (
              <div className="isCoverShow">封 面</div>
            ) : null} */}

            {/* 下面的预览和下载 */}
            <div className="fileImgListLDBox">
              <EyeOutlined
                rev={undefined}
                onClick={() =>
                  store.dispatch({
                    type: "layout/lookBigImg",
                    payload: {
                      url: baseURL + v.filePath,
                      show: true,
                    },
                  })
                }
              />
              <a
                href={baseURL + v.filePath}
                download={v.fileName}
                target="_blank"
                rel="noreferrer"
              >
                <DownloadOutlined rev={undefined} />
              </a>
            </div>
          </div>
        ))}
      </ReactSortable>
      <div className="fileTit" hidden={isLook}>
        {fileList.length && fileList.length >= 2 ? (
          <>
            按住鼠标可拖动图片调整顺序。
            <br />
          </>
        ) : null}
        支持{formatTxt}的图片格式；最大支持{size}M；最多支持{max}
        张；第一张将作为封面
        {sizeTxt ? `建议尺寸${sizeTxt}` : null}
        <br />
        <div
          className={classNames(
            "noUpThumb",
            fileList.length <= 0 && fileCheck ? "noUpThumbAc" : ""
          )}
        >
          请上传图片!
        </div>
      </div>

      {isLook && fileList.length <= 0 ? (
        <div className="lookNone">（空）</div>
      ) : null}
    </div>
  );
}

export default forwardRef(Z1upImgs);
