import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { Button, Input, Popconfirm, Table } from "antd";
import { A1_APIUdel, A1_APIUgeiList } from "@/store/action/A1Project";
import { A1UtableType } from "@/types";
import A1UserAdd from "./A1UserAdd";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import { MessageFu } from "@/utils/message";
import AuthCom from "@/components/AuthCom";

type Props = {
  projectId: number;
};

function A1User({ projectId }: Props) {
  const [searchKey, setSearchKey] = useState("");

  const getListFu = useCallback(
    async (val: string) => {
      const res = await A1_APIUgeiList(projectId, val);
      if (res.code === 0) setData(res.data);
    },
    [projectId]
  );

  useEffect(() => {
    getListFu(searchKey);
  }, [getListFu, searchKey]);

  const [data, setData] = useState<A1UtableType[]>([]);

  // 搜索项的输入
  const searchKeyTime = useRef(-1);
  const searchKeyChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      clearTimeout(searchKeyTime.current);
      searchKeyTime.current = window.setTimeout(() => {
        setSearchKey(e.target.value);
      }, 500);
    },
    []
  );

  // 新增 和 编辑 成功
  const addSuFu = useCallback(() => {
    if (searchKey.trim() === "") getListFu("");
    else setSearchKey("");
  }, [getListFu, searchKey]);

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

  // 权限
  const authArr = useSelector((state: RootState) => state.A4Role.A4RoleAll);

  const columns = useMemo(() => {
    const arr: any = [
      {
        title: "项目职能",
        dataIndex: "jobName",
      },
      {
        title: "姓名",
        dataIndex: "name",
      },
    ];

    if (authArr.includes("1112") || authArr.includes("1113"))
      arr.push({
        title: "操作",
        render: (item: A1UtableType) => (
          <>
            <AuthCom aId="1112">
              <Button size="small" type="text" onClick={() => setAddInfo(item)}>
                编辑
              </Button>
            </AuthCom>
            <AuthCom aId="1113">
              <Popconfirm
                title="删除后无法恢复，是否删除?"
                okText="删除"
                cancelText="取消"
                onConfirm={() => delById(item.id)}
                okButtonProps={{ loading: false }}
              >
                <Button size="small" type="text" danger>
                  删除
                </Button>
              </Popconfirm>
            </AuthCom>
          </>
        ),
      });

    return arr;
  }, [authArr, delById]);

  // 编辑 新增 的数据
  const [addInfo, setAddInfo] = useState({} as A1UtableType);

  return (
    <div className={styles.A1User}>
      {/* 顶部 */}
      <div className="A1Utop">
        <div className="A1Utop1">
          <span>搜索项：</span>
          <Input
            maxLength={30}
            style={{ width: 300 }}
            placeholder="请输入成员姓名"
            allowClear
            onChange={(e) => searchKeyChange(e)}
          />
        </div>
        <div className="A1Utop2">
          <AuthCom aId="1115">
            <Button
              type="primary"
              onClick={() => setAddInfo({ id: -1, projectId } as A1UtableType)}
            >
              新增
            </Button>
          </AuthCom>
        </div>
      </div>

      {/* 表格主体 */}
      <div className="A1UTableBox">
        <Table
          scroll={{ y: 610 }}
          dataSource={data}
          columns={columns}
          rowKey="id"
          pagination={false}
        />
      </div>

      {/* 编辑和新增出来的弹窗 */}
      {addInfo.id ? (
        <A1UserAdd
          info={addInfo}
          closeFu={() => setAddInfo({ id: 0 } as A1UtableType)}
          editFu={() => getListFu(searchKey)}
          addFu={() => addSuFu()}
        />
      ) : null}
    </div>
  );
}

const MemoA1User = React.memo(A1User);

export default MemoA1User;
