import BreadTit from "@/components/BreadTit";
import { RootState } from "@/store";
import {
  delUserAPI,
  getUserListAPI,
  userEditStatusAPI,
} from "@/store/action/system";
import { Button, Input, message, 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 "./index.css";
import UserModal from "./UserModal";
function System1() {
  const dispatch = useDispatch();

  const pageNumRef = useRef(1);
  const pagePageRef = useRef(10);
  // 筛选和分页
  const [tableSelect, setTableSelect] = useState({
    searchKey: "",
    pageSize: 10,
    pageNum: 1,
  });

  // 账号的输入
  const nameTime = useRef(-1);
  const nameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    clearTimeout(nameTime.current);
    nameTime.current = window.setTimeout(() => {
      setTableSelect({ ...tableSelect, searchKey: e.target.value, pageNum: 1 });
    }, 500);
  };

  useEffect(() => {
    pageNumRef.current = tableSelect.pageNum;
    pagePageRef.current = tableSelect.pageSize;
    dispatch(getUserListAPI(tableSelect));
  }, [dispatch, tableSelect]);

  // 点击新增或者编辑按钮
  const addSystem = (id?: any) => {
    if (id) idRef.current = id;
    else idRef.current = null;
    setOpen(true);
  };

  // 点击删除按钮
  const delOne = useCallback(
    async (id: number) => {
      const res: any = await delUserAPI(id);
      if (res.code === 0) {
        message.success("删除成功!");
        // 重新发请求更新页面
        dispatch(getUserListAPI(tableSelect));
      }
    },
    [dispatch, tableSelect]
  );

  // ---------关于表格

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

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

  const results = useSelector(
    (state: RootState) => state.systemStore.tableList
  );

  const columns = useMemo(() => {
    return [
      {
        title: "序号",
        render: (text: any, record: any, index: any) =>
          index + 1 + (pageNumRef.current - 1) * pagePageRef.current,
      },
      {
        title: "账号",
        dataIndex: "userName",
      },
      {
        title: "角色",
        dataIndex: "creatorName",
      },
      {
        title: "真实姓名",
        dataIndex: "realName",
      },
      {
        title: "手机号",
        render: (item: any) => (item.isAdmin === 1 ? "-" : item.phone),
      },

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

      {
        title: "操作",
        render: (item: any) => (
          <>
            {item.isAdmin === 1 ? (
              "-"
            ) : (
              <>
                <Button type="text" danger onClick={() => addSystem(item.id)}>
                  编辑
                </Button>
                <Popconfirm
                  title="确定删除吗?"
                  okText="确定"
                  cancelText="取消"
                  onConfirm={() => delOne(item.id)}
                >
                  <Button type="text" danger>
                    删除
                  </Button>
                </Popconfirm>
              </>
            )}
          </>
        ),
      },
    ];
  }, [delOne, isEnabledClickFu]);

  // 关于弹窗
  const [open, setOpen] = useState(false);
  const idRef = useRef<any>(null);

  // 在弹窗里面点击提交成功之后
  const btnOkSuccFu = useCallback(() => {
    dispatch(getUserListAPI(tableSelect));
    setOpen(false);
  }, [dispatch, tableSelect]);

  return (
    <div className={styles.System1}>
      <div className="breadTit">
        <BreadTit>
          <div className="breadTitRow active">用户管理</div>
        </BreadTit>
      </div>
      <div className="objectSonMain">
        <div className="tableSelectBox">
          <div className="row">
            <span>账号：</span>
            <Input
              maxLength={10}
              style={{ width: 150 }}
              placeholder="请输入"
              allowClear
              onChange={(e) => nameChange(e)}
            />
          </div>
          <div className="row">
            <Button type="primary" onClick={() => addSystem()}>
              新增用户
            </Button>
          </div>
        </div>
        {/* 表格主体 */}
        <div className="tableMain">
          <Table
            scroll={{ y: 480 }}
            dataSource={results.list}
            columns={columns}
            rowKey="id"
            pagination={{
              showQuickJumper: true,
              position: ["bottomCenter"],
              showSizeChanger: true,
              current: tableSelect.pageNum,
              pageSize: tableSelect.pageSize,
              total: results.total,
              onChange: paginationChange,
            }}
          />
        </div>
      </div>

      {/* 点击新增或者编辑出来的弹窗 */}
      {open ? (
        <UserModal
          btnOkSuccFu={btnOkSuccFu}
          id={idRef.current}
          closeFu={() => setOpen(false)}
        />
      ) : null}
    </div>
  );
}

const MemoSystem1 = React.memo(System1);

export default MemoSystem1;
