import React, { useCallback, useEffect, useState } from "react";
import styles from "./index.module.scss";
import { Button, Input, Modal } from "antd";
import { Z0EditInfoType } from "./data";
import MyPopconfirm from "@/components/MyPopconfirm";
import TextArea from "antd/es/input/TextArea";
import { MessageFu } from "@/utils/message";
import { Z0_APIadd } from "@/store/action/Z0column";

type Props = {
  editInfo: Z0EditInfoType;
  closeFu: () => void;
  upTableFu: () => void;
};

function Z0edit({ editInfo, closeFu, upTableFu }: Props) {
  const [name, setName] = useState("");
  const [rtf, setRtf] = useState("");

  useEffect(() => {
    if (editInfo.id > 0) {
      setName(editInfo.name);
      setRtf(editInfo.rtf);
    }
  }, [editInfo]);

  const btnOkFu = useCallback(async () => {
    if (name.length <= 0) return MessageFu.warning("请输入栏目名称!");

    const flag = editInfo.id > 0;

    const obj = {
      id: flag ? editInfo.id : null,
      name,
      rtf,
      type: editInfo.type,
    };

    const res = await Z0_APIadd(obj);
    if (res.code === 0) {
      MessageFu.success(flag ? "编辑成功!" : "新增成功!");
      upTableFu();
      closeFu();
    }
  }, [closeFu, editInfo.id, editInfo.type, name, rtf, upTableFu]);

  return (
    <Modal
      wrapClassName={styles.Z0edit}
      open={true}
      title={editInfo.tit + (editInfo.id > 0 ? "编辑" : "新增")}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className="Z0Emain">
        <div className="Z0Erow">
          <div className="Z0Erow1">
            <span>* </span>栏目名称：
          </div>
          <div className="Z0Erow2">
            <Input
              value={name}
              onChange={(e) => setName(e.target.value.replace(/\s+/g, ""))}
              placeholder="请输入名称"
              showCount
              maxLength={20}
            />
          </div>
        </div>
        <div className="Z0Erow">
          <div className="Z0Erow1">
            <span> </span>说明：
          </div>
          <div className="Z0Erow2">
            <TextArea
              value={rtf}
              onChange={(e) => setRtf(e.target.value.replace(/\s+/g, ""))}
              placeholder="请输入说明"
              showCount
              maxLength={100}
            />
          </div>
        </div>
        <div className="Z0Ebtn">
          <Button type="primary" onClick={btnOkFu}>
            提交
          </Button>
          &emsp;
          <MyPopconfirm txtK="取消" onConfirm={closeFu} />
        </div>
      </div>
    </Modal>
  );
}

const MemoZ0edit = React.memo(Z0edit);

export default MemoZ0edit;
