import { RootState } from "@/store";
import {
  A9API_getUserListAPI,
  A9API_userDisplayAPI,
  A9API_userPassResetAPI,
  A9API_userRemoveAPI,
} from "@/store/action/A9User";
import { UserTableAPIType, UserTableListType } from "@/types";
import { MessageFu } from "@/utils/message";
import { Input, Button, Table, Switch, Popconfirm } 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";

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

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

  // 封装发送请求的函数

  const getList = useCallback(async () => {
    dispatch(A9API_getUserListAPI(tableSelect));
  }, [dispatch, tableSelect]);

  // 防止发送了2次请求来对应页码

  const getListRef = useRef(-1);

  useEffect(() => {
    clearTimeout(getListRef.current);
    getListRef.current = window.setTimeout(() => {
      getList();
    }, 100);
  }, [getList, tableSelect]);

  // 真实姓名的输入
  const realNameTime = useRef(-1);
  const realNameChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      clearTimeout(realNameTime.current);
      realNameTime.current = window.setTimeout(() => {
        setTableSelect({
          ...tableSelect,
          realName: e.target.value,
          pageNum: 1,
        });
      }, 500);
    },
    [tableSelect]
  );

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

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

  // 页码变化
  const paginationChange = useCallback(
    () => (pageNum: number, pageSize: number) => {
      setTableSelect({ ...tableSelect, pageNum, pageSize });
    },
    [tableSelect]
  );

  // 切换表格中的启用停用状态
  const isEnabledClickFu = useCallback(
    async (val: boolean, id: number) => {
      const isDisable = val ? 1 : 0;
      const res: any = await A9API_userDisplayAPI(id, isDisable);
      if (res.code === 0) getList();
    },
    [getList]
  );

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

  // 点击重置密码
  const resetPassFu = useCallback(async (id: number) => {
    const res: any = await A9API_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 >= 30)
        return MessageFu.warning("最多支持30个用户！");

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

  const columns = useMemo(() => {
    return [
      // {
      //   width: 80,
      //   title: "序号",
      //   render: (text: any, record: any, index: any) =>
      //     index + 1 + (pageNumRef.current - 1) * pagePageRef.current,
      // },
      {
        title: "用户名",
        dataIndex: "userName",
      },
      // {
      //   title: "用户角色",
      //   render: (item: UserTableListType) =>
      //     item.isAdmin === 1 ? "超级管理员" : "管理员",
      // },
      {
        title: "真实姓名",
        dataIndex: "realName",
      },
      {
        title: "手机号",
        dataIndex: "phone",
      },
      {
        title: "注册时间",
        dataIndex: "createTime",
      },

      {
        title: "启用状态",
        render: (item: UserTableListType) => (
          <Switch
            disabled={item.isAdmin === 1}
            checkedChildren="启用"
            unCheckedChildren="停用"
            checked={item.isEnabled === 1}
            onChange={(val) => isEnabledClickFu(val, item.id!)}
          />
        ),
      },

      {
        title: "操作",
        render: (item: UserTableListType) => {
          return item.isAdmin === 1 ? (
            "-"
          ) : (
            <>
              <Popconfirm
                title="密码重制后为123456，是否重置?"
                okText="重置"
                cancelText="取消"
                okButtonProps={{ loading: false }}
                onConfirm={() => resetPassFu(item.id!)}
              >
                <Button size="small" type="text">
                  重置密码
                </Button>
              </Popconfirm>

              <Button
                size="small"
                type="text"
                onClick={() => openEditPageFu(item.id!)}
              >
                编辑
              </Button>
              <Popconfirm
                title="删除后无法恢复，是否删除?"
                okText="删除"
                cancelText="取消"
                okButtonProps={{ loading: false }}
                onConfirm={() => delTableFu(item.id!)}
              >
                <Button size="small" type="text" danger>
                  删除
                </Button>
              </Popconfirm>
            </>
          );
        },
      },
    ];
  }, [delTableFu, isEnabledClickFu, openEditPageFu, resetPassFu]);

  return (
    <div className={styles.A9User}>
      <div className="pageTitle">用户管理</div>
      <div className="userTop">
        <div className="selectBox">
          <div className="selectBoxL">
            <div className="row">
              <span>真实姓名：</span>
              <Input
                key={inputKey}
                maxLength={8}
                style={{ width: 200 }}
                placeholder="请输入"
                allowClear
                onChange={(e) => realNameChange(e)}
              />
            </div>
          </div>
          <div className="selectBoxR">
            <Button type="primary" onClick={() => openEditPageFu(0)}>
              新增
            </Button>
          </div>
        </div>
      </div>
      {/* 表格主体 */}
      <div className="tableBox">
        <Table
          scroll={{ y: 605 }}
          dataSource={tableInfo.list}
          columns={columns}
          rowKey="id"
          pagination={{
            showQuickJumper: true,
            position: ["bottomCenter"],
            // showSizeChanger: true,
            current: tableSelect.pageNum,
            pageSize: tableSelect.pageSize,
            total: tableInfo.total,
            onChange: paginationChange(),
          }}
        />
      </div>

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

const MemoA9User = React.memo(A9User);

export default MemoA9User;
