import React, { useCallback, useRef } from "react";
import styles from "./index.module.scss";
import ImageLazy from "@/components/ImageLazy";
import {
  PlusOutlined,
  EyeOutlined,
  CloseOutlined,
  DownloadOutlined,
} from "@ant-design/icons";
import store from "@/store";
import { baseURL } from "@/utils/http";
import classNames from "classnames";
import { Popconfirm } from "antd";
import { MessageFu } from "@/utils/message";
import { fileDomInitialFu } from "@/utils/domShow";
import { API_upFile } from "@/store/action/layout";

type Props = {
  cover: string; //封面图
  setCover: (val: string) => void; //设置封面图
  isLook: boolean; //是不是查看
  coverCheck: boolean; //有没有点击过确定
  size: number; //上传图片大小（M）
  dirCode: string; //文件的code码
  myUrl: string;
  format?: string[]; //上传图片格式
  formatTxt?: string; //上传图片提示
  sizeTxt?: string; //后面的建议尺寸信息
  fromData?: any;
  checkTxt?: string;
};

function Z_upFileOne({
  cover,
  setCover,
  isLook,
  coverCheck,
  size,
  dirCode,
  myUrl,
  format = ["image/jpeg", "image/png"],
  formatTxt = "png、jpg和jpeg",
  checkTxt = "请上传封面图!",
  sizeTxt,
  fromData,
}: Props) {
  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", "thumb");
        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("上传成功!");
            setCover(res.data.filePath);
          }
          fileDomInitialFu();
        } catch (error) {
          fileDomInitialFu();
        }
      }
    },
    [dirCode, format, formatTxt, fromData, myUrl, setCover, size]
  );

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

      <div
        hidden={cover !== ""}
        className="file_upIcon"
        onClick={() => myInput.current?.click()}
      >
        <PlusOutlined />
      </div>

      <div className="file_img" hidden={cover === ""}>
        {cover ? (
          <ImageLazy width={100} height={100} src={cover} noLook />
        ) : null}

        {/* 删除 */}
        <div className="file_closeBox" hidden={isLook}>
          <Popconfirm
            title="删除后无法恢复，是否删除?"
            okText="删除"
            cancelText="取消"
            onConfirm={() => setCover("")}
          >
            <CloseOutlined />
          </Popconfirm>
        </div>

        {/* 预览 下载 */}
        <div className="file_lookBox">
          <EyeOutlined
            onClick={() =>
              store.dispatch({
                type: "layout/lookBigImg",
                payload: { url: baseURL + cover, show: true },
              })
            }
          />
          <a href={baseURL + cover} download target="_blank" rel="noreferrer">
            <DownloadOutlined />
          </a>
        </div>
      </div>
      <div className="fileBoxRow_r_tit" hidden={isLook}>
        支持{formatTxt}的图片格式；最大支持{size}M。
        {sizeTxt ? `建议尺寸${sizeTxt}` : null}
        <br />
        <div
          className={classNames(
            "noUpThumb",
            !cover && coverCheck ? "noUpThumbAc" : ""
          )}
        >
          {checkTxt}
        </div>
      </div>
    </div>
  );
}

const MemoZ_upFileOne = React.memo(Z_upFileOne);

export default MemoZ_upFileOne;
