import { RootState } from "@/store";
import {
  getRoleListAPI,
  roleDisplayAPI,
  roleRemoveAPI,
} from "@/store/action/C2Role";
import { RoleTableType } from "@/types";
import { MessageFu } from "@/utils/message";
import { Button, Input, Popconfirm, Switch, Table } from "antd";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useDispatch, useSelector } from "react-redux";
import styles from "./index.module.scss";
import RoleAdd from "./RoleAdd";
function Role() {
  const dispatch = useDispatch();

  // 顶部筛选

  type TableListType = {
    pageNum: number;
    pageSize: number;
    searchKey: string;
  };

  const [tableSelect, setTableSelect] = useState<TableListType>({
    pageNum: 1,
    pageSize: 10,
    searchKey: "",
  });

  useEffect(() => {
    dispatch(getRoleListAPI(tableSelect));
  }, [dispatch, 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(() => {
    // 把2个输入框和时间选择器清空
    setInputKey(Date.now());
    setTableSelect({
      pageNum: 1,
      pageSize: 10,
      searchKey: "",
    });
  }, []);

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

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

  // 点击新增和编辑
  const [editPageShow, setEditPageShow] = useState(false);
  const editId = useRef(0);
  const openEditPageFu = useCallback((id: number) => {
    editId.current = id;
    setEditPageShow(true);
  }, []);

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

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

  const columns = useMemo(() => {
    return [
      // {
      //   width: 80,
      //   title: "序号",
      //   render: (text: any, record: any, index: any) =>
      //     index + 1 + (pageNumRef.current - 1) * pagePageRef.current,
      // },
      {
        title: "角色名称",
        dataIndex: "roleName",
      },
      {
        title: "角色描述",
        render: (item: RoleTableType) =>
          item.roleDesc ? item.roleDesc : "（空）",
      },
      {
        title: "成员数量",
        dataIndex: "count",
      },
      {
        title: "最后编辑时间",
        dataIndex: "updateTime",
      },

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

      {
        title: "操作",
        render: (item: RoleTableType) => {
          return (
            <>
              <Button
                size="small"
                type="text"
                onClick={() => openEditPageFu(item.id!)}
              >
                {item.roleKey === "sys_admin" ? "查看" : "编辑"}
              </Button>
              {item.roleKey !== "sys_admin" ? (
                <Popconfirm
                  title="删除后无法恢复，是否删除?"
                  okText="删除"
                  cancelText="取消"
                  onConfirm={() => delTableFu(item.id!)}
                >
                  <Button size="small" type="text" danger>
                    删除
                  </Button>
                </Popconfirm>
              ) : null}
            </>
          );
        },
      },
    ];
  }, [delTableFu, isEnabledClickFu, openEditPageFu]);

  return (
    <div className={styles.Role}>
      <div className="pageTitlt">角色管理</div>
      <div className="searchTop">
        <div className="searchTopRow">
          <span>角色名：</span>
          <Input
            key={inputKey}
            maxLength={8}
            style={{ width: 200 }}
            placeholder="请输入"
            allowClear
            onChange={(e) => nameChange(e)}
          />
        </div>
        <div className="searchTopRow">
          &emsp;&emsp;
          <Button type="primary" onClick={() => openEditPageFu(0)}>
            新增
          </Button>
        </div>
      </div>

      <div className="tableBox">
        <Table
          scroll={{ y: 620 }}
          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 ? (
        <RoleAdd
          id={editId.current}
          closePage={() => setEditPageShow(false)}
          upTableList={() => dispatch(getRoleListAPI(tableSelect))}
          addTableList={resetSelectFu}
        />
      ) : null}
    </div>
  );
}

const MemoRole = React.memo(Role);

export default MemoRole;
