import { RootState } from "@/store";
import {
  getUserListAPI,
  userPassResetAPI,
  userRemoveAPI,
} from "@/store/action/Z1user";
import { UserTableAPIType, UserTableListType } from "@/types";
import { MessageFu } from "@/utils/message";
import { Input, Button } from "antd";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useDispatch, useSelector } from "react-redux";
import styles from "./index.module.scss";
import UserAdd from "./UserAdd";
import MyTable from "@/components/MyTable";
import { Z1tableC } from "@/utils/tableData";
import MyPopconfirm from "@/components/MyPopconfirm";

function Z1user() {
  const dispatch = useDispatch();

  // 顶部筛选
  const [fromData, setFromData] = useState<UserTableAPIType>({
    pageNum: 1,
    pageSize: 10,
    searchKey: "",
  });

  // 封装发送请求的函数

  const getList = useCallback(async () => {
    dispatch(getUserListAPI(fromData));
  }, [dispatch, fromData]);

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

  const timeRef = useRef(-1);
  // 用户名
  const txtChangeFu = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>, key: "searchKey") => {
      clearTimeout(timeRef.current);
      timeRef.current = window.setTimeout(() => {
        setFromData({
          ...fromData,
          [key]: e.target.value,
          pageNum: 1,
        });
      }, 500);
    },
    [fromData]
  );

  // 点击重置
  const [inputKey, setInputKey] = useState(1);
  const resetSelectFu = useCallback(() => {
    // 把2个输入框和时间选择器清空
    setInputKey(Date.now());
    setFromData({
      pageNum: 1,
      pageSize: 10,
      searchKey: "",
    });
  }, []);

  // 从仓库中获取表格数据
  const tableInfo = useSelector((state: RootState) => state.Z1user.tableInfo);

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

  // 点击重置密码
  const resetPassFu = useCallback(async (id: number) => {
    const res: any = await userPassResetAPI(id);
    if (res.code === 0) MessageFu.success("重置成功!");
  }, []);

  // 0------------点击新增或者编辑出来的页面
  const [editPageShow, setEditPageShow] = useState(false);
  const editId = useRef(0);

  const openEditPageFu = useCallback(
    (id: number) => {
      if (id === 0 && tableInfo.list.length >= 20)
        return MessageFu.warning("最多支持20个用户！");

      editId.current = id;
      setEditPageShow(true);
    },
    [tableInfo.list.length]
  );

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: "操作",
        render: (item: UserTableListType) => {
          return item.isAdmin === 1 ? (
            "-"
          ) : (
            <>
              <MyPopconfirm
                txtK="重置密码"
                onConfirm={() => resetPassFu(item.id)}
                Dom={
                  <Button size="small" type="text">
                    重置密码
                  </Button>
                }
              />

              <Button
                size="small"
                type="text"
                onClick={() => openEditPageFu(item.id!)}
              >
                编辑
              </Button>
              <MyPopconfirm txtK="删除" onConfirm={() => delTableFu(item.id)} />
            </>
          );
        },
      },
    ];
  }, [delTableFu, openEditPageFu, resetPassFu]);

  return (
    <div className={styles.Z1user}>
      <div className="pageTitle">用户管理</div>
      <div className="userTop">
        <div className="selectBox">
          <div className="selectBoxRow">
            <span>搜索项：</span>
            <Input
              key={inputKey}
              maxLength={10}
              showCount
              style={{ width: 300 }}
              placeholder="请输入用户名"
              allowClear
              onChange={(e) => txtChangeFu(e, "searchKey")}
            />
          </div>

          <div className="selectBoxRow">
            &emsp;&emsp;<Button onClick={resetSelectFu}>重置</Button>
            &emsp;&emsp;
            <Button type="primary" onClick={() => openEditPageFu(0)}>
              新增
            </Button>
          </div>
        </div>
      </div>
      {/* 表格主体 */}
      <div className="tableBox">
        <MyTable
          yHeight={630}
          list={tableInfo.list}
          columnsTemp={Z1tableC}
          lastBtn={tableLastBtn}
          pageNum={fromData.pageNum}
          pageSize={fromData.pageSize}
          total={tableInfo.total}
          onChange={(pageNum, pageSize) =>
            setFromData({ ...fromData, pageNum, pageSize })
          }
        />
      </div>

      {/* 点击新增或者编辑 */}
      {editPageShow ? (
        <UserAdd
          id={editId.current}
          closePage={() => setEditPageShow(false)}
          upTableList={getList}
          addTableList={resetSelectFu}
        />
      ) : null}
    </div>
  );
}

const MemoZ1user = React.memo(Z1user);

export default MemoZ1user;
