import React, { useCallback, useEffect, useMemo, useState } from "react";
import styles from "./index.module.scss";
import { Button, Input, Modal, Popconfirm } from "antd";
import { MessageFu } from "@/utils/message";

type Props = {
  closeFu: () => void;
  fileInfo: {
    id: number;
    fileName: string;
    type: string;
  };
};

function A1ORenFile({ closeFu, fileInfo }: Props) {
  const [value, setValue] = useState("");

  useEffect(() => {
    if (fileInfo.id > 0 && fileInfo.type === "文件") {
      const arr = fileInfo.fileName.split(".");
      const val = "." + arr[arr.length - 1];
      const val2 = fileInfo.fileName.replace(val, "");
      setValue(val2);
    } else setValue(fileInfo.fileName);
  }, [fileInfo]);

  const onChangeFu = useCallback((val: string) => {
    setValue(val.replace(/\s+/g, ""));
  }, []);

  const isFileType = useMemo(() => {
    let val = "";
    if (fileInfo.type === "文件" && fileInfo.fileName) {
      const arr = fileInfo.fileName.split(".");
      val = arr[arr.length - 1];
    }
    return val;
  }, [fileInfo]);

  // 点击确定
  const btnOkFu = useCallback(() => {
    if (!value) return MessageFu.warning("名称不能为空!");

    console.log("--------点击确定", value);
  }, [value]);

  return (
    <Modal
      wrapClassName={styles.A1ORenFile}
      destroyOnClose
      open={true}
      title={
        fileInfo.id === -1
          ? "新建文件夹"
          : fileInfo.type === "文件夹"
          ? "文件夹重命名"
          : "文件重命名"
      }
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className="A1ORMain">
        <div className="A1ORMainInput">
          {isFileType ? (
            <div className="A1ORMainInputTit">文件后缀：.{isFileType}</div>
          ) : null}

          <Input
            value={value}
            onChange={(e) => onChangeFu(e.target.value)}
            maxLength={30}
            showCount
            placeholder="请输入名称"
          />
        </div>

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

const MemoA1ORenFile = React.memo(A1ORenFile);

export default MemoA1ORenFile;
