import React, { useCallback, useEffect, useState } from "react";
import styles from "./index.module.scss";
import { Button, Input, Modal } from "antd";
import { A2sTableType } from ".";
import MyPopconfirm from "@/components/MyPopconfirm";
import { MessageFu } from "@/utils/message";
import { API_A2save } from "@/store/action/all";

type Props = {
  closeFu: () => void;
  editFu: () => void;
  editObj: A2sTableType;
};

function A2sAdd({ editObj, closeFu, editFu }: Props) {
  const [name, setName] = useState("");

  const [dept, setDept] = useState("");

  useEffect(() => {
    setName(editObj.name);
    setDept(editObj.dept);
  }, [editObj]);

  const btnOk = useCallback(async () => {
    if (!name) return MessageFu.warning("姓名不能为空!");
    if (!dept) return MessageFu.warning("部门不能为空!");

    const obj = {
      id: editObj.id > 0 ? editObj.id : null,
      name,
      dept,
    };
    const res = await API_A2save(obj);
    if (res.code === 0) {
      MessageFu.success(editObj.id > 0 ? "编辑成功" : "新增成功");
      editFu();
      closeFu();
    }
  }, [closeFu, dept, editFu, editObj.id, name]);

  return (
    <Modal
      wrapClassName={styles.A2sAdd}
      open={true}
      title={editObj.id > 0 ? "编辑" : "新增"}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className="A2sRow">
        <span className="A2sRowB">*</span>姓名：
        <Input
          placeholder="请输入名称"
          value={name}
          onChange={(e) => setName(e.target.value.trim())}
          maxLength={10}
          showCount
        />
      </div>

      <div className="A2sRow">
        <span className="A2sRowB">*</span>部门：
        <Input
          placeholder="请输入部门"
          value={dept}
          onChange={(e) => setDept(e.target.value.trim())}
          maxLength={10}
          showCount
        />
      </div>

      <div className="A2sbtn">
        <MyPopconfirm txtK="取消" onConfirm={closeFu} />
        &emsp;
        <Button type="primary" onClick={btnOk}>
          提交
        </Button>
      </div>
    </Modal>
  );
}

const MemoA2sAdd = React.memo(A2sAdd);

export default MemoA2sAdd;
