import React, { useCallback, useEffect, useMemo, useState } from "react";
import styles from "./index.module.scss";
import { API_A2del, API_A2getStaffList } from "@/store/action/all";
import { Button } from "antd";
import MyTable from "@/components/MyTable";
import MyPopconfirm from "@/components/MyPopconfirm";
import { MessageFu } from "@/utils/message";
import A2sAdd from "./A2sAdd";

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

export type A2sTableType = {
  name: string;
  dept: string;
  id: number;
};

function A2staff({ closeFu }: Props) {
  const [list, setList] = useState<A2sTableType[]>([]);

  const getList = useCallback(async () => {
    const res = await API_A2getStaffList({
      pageNum: 1,
      pageSize: 9999,
    });
    if (res.code === 0) {
      setList(res.data.records);
    }
  }, []);

  useEffect(() => {
    getList();
  }, [getList]);

  // 点击删除
  const delTableFu = useCallback(
    async (id: number) => {
      const res = await API_A2del(id);
      if (res.code === 0) {
        MessageFu.success("删除成功!");
        getList();
      }
    },
    [getList]
  );

  //新增和编辑
  const [editObj, setEditObj] = useState({} as A2sTableType);

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: "操作",
        render: (item: A2sTableType) => (
          <>
            <Button size="small" type="text" onClick={() => setEditObj(item)}>
              编辑
            </Button>

            <MyPopconfirm txtK="删除" onConfirm={() => delTableFu(item.id)} />
          </>
        ),
      },
    ];
  }, [delTableFu]);

  return (
    <div className={styles.A2staff}>
      <div className="A2sTit">
        <div className="A2sTitll">
          人员名单- <span>离职或其他原因也暂时需要统计工时的时候填</span>
        </div>
        <div>
          <Button
            type="primary"
            onClick={() => setEditObj({ id: -1 } as A2sTableType)}
          >
            新增
          </Button>
          &emsp;
          <Button onClick={closeFu}>关闭</Button>
        </div>
      </div>

      <MyTable
        classKey="A2staTale"
        yHeight={600}
        list={list}
        lastBtn={tableLastBtn}
        columnsTemp={[
          ["txt", "姓名", "name"],
          ["txt", "部门", "dept"],
        ]}
        pagingInfo={false}
      />

      {/* 点击新增和编辑 */}
      {editObj.id ? (
        <A2sAdd
          editObj={editObj}
          closeFu={() => setEditObj({} as A2sTableType)}
          editFu={getList}
        />
      ) : null}
    </div>
  );
}

const MemoA2staff = React.memo(A2staff);

export default MemoA2staff;
