import { RootState } from "@/store";
import {
  A3_APIgetRole,
  getUserListAPI,
  userPassResetAPI,
  userRemoveAPI,
} from "@/store/action/A3User";
import { UserTableAPIType, UserTableListType } from "@/types";
import { MessageFu } from "@/utils/message";
import { Input, Button, Table, Popconfirm, Select, Cascader } 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 A3User() {
  const dispatch = useDispatch();

  useEffect(() => {
    // 获取角色 列表 信息（给 下拉框 页面使用）
    dispatch(A3_APIgetRole());
  }, [dispatch]);

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

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

  // 获取 部门(树形) 列表下拉框数据
  const selectData1 = useSelector(
    (state: RootState) => state.A5Section.tableList
  );

  // 部门树型选中的数组
  const [treeDept, setTreeDept] = useState<any>([undefined]);

  const setTreeDeptFu = useCallback(
    (e: any) => {
      setTreeDept(e);

      const txt = e[e.length - 1];

      setTableSelect({ ...tableSelect, deptId: txt ? Number(txt) : "" });
    },
    [tableSelect]
  );

  // 获取 角色 列表下拉框数据
  const selectData2 = useSelector((state: RootState) => state.A3User.roleList);

  // 封装发送请求的函数
  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,
          searchKey: e.target.value,
          pageNum: 1,
        });
      }, 500);
    },
    [tableSelect]
  );

  // 点击重置
  const [inputKey, setInputKey] = useState(1);
  const resetSelectFu = useCallback(() => {
    // 级联筛选 恢复 初始
    setTreeDept([undefined]);

    // 把2个输入框和时间选择器清空
    setInputKey(Date.now());
    setTableSelect({
      deptId: "",
      pageNum: 1,
      pageSize: 10,
      roleId: "",
      searchKey: "",
    });
  }, []);

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

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

  // 点击删除
  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 >= 50)
        return MessageFu.warning("最多支持50个用户！");

      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: "deptName",
      },
      {
        title: "角色",
        dataIndex: "roleName",
      },
      {
        title: "真实姓名",
        dataIndex: "realName",
      },
      {
        title: "创建日期",
        dataIndex: "createTime",
      },

      {
        title: "操作",
        render: (item: UserTableListType) => {
          return item.isAdmin === 1 ? (
            "-"
          ) : (
            <>
              <Popconfirm
                title="密码重制后为用户名+4dage，是否重置?"
                okText="重置"
                cancelText="取消"
                onConfirm={() => resetPassFu(item.id!)}
                okButtonProps={{ loading: false }}
              >
                <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!)}
                okButtonProps={{ loading: false }}
              >
                <Button size="small" type="text" danger>
                  删除
                </Button>
              </Popconfirm>
            </>
          );
        },
      },
    ];
  }, [delTableFu, openEditPageFu, resetPassFu]);

  return (
    <div className={styles.A3User}>
      <div className="pageTitle">用户管理</div>
      <div className="userTop">
        <div className="selectBox">
          <div className="selectBoxRow">
            <span>搜索项：</span>
            <Input
              key={inputKey}
              maxLength={15}
              style={{ width: 240 }}
              placeholder="请输入用户名/真实姓名"
              allowClear
              onChange={(e) => nameChange(e)}
            />
          </div>

          <div className="selectBoxRow">
            <span>所属部门：</span>

            <Cascader
              style={{ width: 300 }}
              value={treeDept}
              onChange={(e) => setTreeDeptFu(e)}
              options={[{ value: undefined, name: "全部" }, ...selectData1]}
              fieldNames={{ label: "name", value: "id" }}
              placeholder="请选择"
              allowClear={false}
            />

            {/* <Select
              style={{ width: 220 }}
              placeholder="请选择"
              value={tableSelect.deptId}
              onChange={(e) => setTableSelect({ ...tableSelect, deptId: e })}
              options={[
                { value: "", label: "全部" },
                ...selectData1.map((v) => ({ value: v.id, label: v.name })),
              ]}
            /> */}
          </div>

          <div className="selectBoxRow">
            <span>角色：</span>
            <Select
              style={{ width: 220 }}
              placeholder="请选择"
              value={tableSelect.roleId}
              onChange={(e) => setTableSelect({ ...tableSelect, roleId: e })}
              options={[{ value: "", label: "全部" }, ...selectData2]}
            />
          </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">
        <Table
          scroll={{ y: 617 }}
          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 MemoA3User = React.memo(A3User);

export default MemoA3User;
