import { RootState } from "@/store";
import {
  getUserListAPI,
  getUserRoleAPI,
  userDisplayAPI,
  userPassResetAPI,
  userRemoveAPI,
} from "@/store/action/user";
import { UserTableAPIType, UserTableListType } from "@/types";
import {
  Input,
  DatePicker,
  Button,
  Table,
  Switch,
  Popconfirm,
  message,
} 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";
const { RangePicker } = DatePicker;

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

  const pageNumRef = useRef(1);
  const pagePageRef = useRef(10);

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

  // 进来用户管理页面获取角色的下拉列表
  useEffect(() => {
    dispatch(getUserRoleAPI());
  }, [dispatch]);

  // 封装发送请求的函数

  const getList = useCallback(async () => {
    const data = {
      ...tableSelect,
      pageNum: pageNumRef.current,
    };
    dispatch(getUserListAPI(data));
  }, [dispatch, tableSelect]);

  // 当前页码统一
  useEffect(() => {
    pageNumRef.current = tableSelect.pageNum;
    pagePageRef.current = tableSelect.pageSize;
  }, [tableSelect.pageNum, tableSelect.pageSize]);

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

  const getListRef = useRef(-1);

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

  // 用户昵称的输入
  const nameTime = useRef(-1);
  const nameChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      clearTimeout(nameTime.current);
      nameTime.current = window.setTimeout(() => {
        setTableSelect({
          ...tableSelect,
          nickName: e.target.value,
          pageNum: 1,
        });
      }, 500);
    },
    [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 timeChange = (date: any, dateString: any) => {
    let startTime = "";
    let endTime = "";
    if (dateString[0] && dateString[1]) {
      startTime = dateString[0] + " 00:00:00";
      endTime = dateString[1] + " 23:59:59";
    }
    setTableSelect({ ...tableSelect, startTime, endTime, pageNum: 1 });
  };

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

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

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

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

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

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

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

  const openEditPageFu = useCallback(
    (id: number) => {
      if (id === 0 && tableInfo.list.length >= 30)
        return message.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: "用户昵称",
        dataIndex: "nickName",
      },
      {
        title: "用户角色",
        dataIndex: "roleName",
      },
      {
        title: "真实姓名",
        dataIndex: "realName",
      },
      {
        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="取消"
                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="取消"
                onConfirm={() => delTableFu(item.id!)}
              >
                <Button size="small" type="text" danger>
                  删除
                </Button>
              </Popconfirm>
            </>
          );
        },
      },
    ];
  }, [delTableFu, isEnabledClickFu, openEditPageFu, resetPassFu]);

  return (
    <div className={styles.User}>
      <div className="userTop">
        <div className="pageTitlt">用户管理</div>
        <div className="selectBox">
          <div className="selectBoxL">
            <div className="row">
              <span>用户昵称：</span>
              <Input
                key={inputKey}
                maxLength={8}
                style={{ width: 150 }}
                placeholder="请输入"
                allowClear
                onChange={(e) => nameChange(e)}
              />
            </div>

            <div className="row">
              <span>真实姓名：</span>
              <Input
                key={inputKey}
                maxLength={8}
                style={{ width: 150 }}
                placeholder="请输入"
                allowClear
                onChange={(e) => realNameChange(e)}
              />
            </div>

            <div className="row">
              <span>注册日期：</span>
              <RangePicker key={inputKey} onChange={timeChange} />
            </div>
          </div>
          <div className="selectBoxR">
            <Button onClick={resetSelectFu}>重置</Button>&emsp;&emsp;
            <Button type="primary" onClick={() => openEditPageFu(0)}>
              新增
            </Button>
          </div>
        </div>
      </div>
      {/* 表格主体 */}
      <div className="tableBox">
        <Table
          scroll={{ y: 575 }}
          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 MemoUser = React.memo(User);

export default MemoUser;
