import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { Button, Input, Popconfirm, Select, Table } from "antd";
import { C1TopType, C1openInfoType, C1options } from "./data";
import { useDispatch, useSelector } from "react-redux";
import {
  C1_APIgetlist,
  C1_APIpassReset,
  C1_APIremoves,
} from "@/store/action/C1User";
import { RootState } from "@/store";
import { C1ListType } from "@/types";
import { MessageFu } from "@/utils/message";
import AddUser from "./AddUser";
function C1User() {
  const dispatch = useDispatch();
  // 筛选和分页
  const [tableSelect, setTableSelect] = useState<C1TopType>({
    roleId: "全部",
    searchKey: "",
    pageSize: 10,
    pageNum: 1,
  });

  // 发送接口的函数
  const getListFu = useCallback(() => {
    const obj = {
      ...tableSelect,
      roleId: tableSelect.roleId === "全部" ? "" : tableSelect.roleId,
    };
    dispatch(C1_APIgetlist(obj));
  }, [dispatch, tableSelect]);

  useEffect(() => {
    getListFu();
  }, [getListFu]);

  // 输入框的改变
  const txtTimeRef = useRef(-1);
  const txtChangeFu = useCallback(
    (txt: string, key: "searchKey") => {
      clearTimeout(txtTimeRef.current);
      txtTimeRef.current = window.setTimeout(() => {
        setTableSelect({ ...tableSelect, [key]: txt, pageNum: 1 });
      }, 500);
    },
    [tableSelect]
  );

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

  // 从仓库获取列表
  const C1TableList = useSelector(
    (state: RootState) => state.C1User.C1TableList
  );
  // 页码变化
  const paginationChange = useCallback(
    () => (pageNum: number, pageSize: number) => {
      setTableSelect({ ...tableSelect, pageNum, pageSize });
    },
    [tableSelect]
  );

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

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

  const columns = useMemo(() => {
    return [
      {
        title: "用户名",
        dataIndex: "userName",
      },
      {
        title: "角色",
        render: (item: C1ListType) =>
          item.isAdmin === 1
            ? "管理员"
            : item.roleId === 3
            ? "项目经理"
            : item.roleId === 4
            ? "铁塔审核员"
            : "-",
      },
      {
        title: "真实姓名",
        render: (item: C1ListType) =>
          item.realName ? item.realName : "（空）",
      },
      {
        title: "联系方式",
        render: (item: C1ListType) => (item.phone ? item.phone : "（空）"),
      },
      {
        title: "创建日期",
        dataIndex: "createTime",
      },

      {
        title: "操作",
        render: (item: C1ListType) =>
          item.isAdmin === 1 ? (
            "-"
          ) : (
            <>
              <Popconfirm
                title="密码重制后为123456?"
                okText="重置"
                cancelText="取消"
                onConfirm={() => resetPassFu(item.id!)}
                okButtonProps={{ loading: false }}
              >
                <Button size="small" type="text">
                  重置密码
                </Button>
              </Popconfirm>
              <Button
                size="small"
                type="text"
                onClick={() => setOpenInfo({ id: item.id, txt: "编辑用户" })}
              >
                编辑
              </Button>
              <Popconfirm
                title="删除后无法恢复，是否删除?"
                okText="删除"
                cancelText="取消"
                onConfirm={() => delByIdFu(item.id)}
                okButtonProps={{ loading: false }}
              >
                <Button size="small" type="text" danger>
                  删除
                </Button>
              </Popconfirm>
            </>
          ),
      },
    ];
  }, [delByIdFu, resetPassFu]);

  // 点击 新增/编辑 出来的信息
  const [openInfo, setOpenInfo] = useState<C1openInfoType>({ id: 0, txt: "" });

  return (
    <div className={styles.C1User}>
      <div className="pageTitle">
        {openInfo.txt ? openInfo.txt : "用户管理"}
      </div>
      {/* 顶部筛选 */}
      <div className="C1top">
        {/* 左侧输入框 */}
        <div className="C1top1">
          <div className="C1topRow">
            <span>搜索项：</span>
            <Input
              key={inputKey}
              maxLength={15}
              style={{ width: 200 }}
              placeholder="请输入用户名/真实姓名"
              allowClear
              onChange={(e) => txtChangeFu(e.target.value, "searchKey")}
            />
          </div>

          <div className="C1topRow">
            <span>角色：</span>
            <Select
              style={{ width: 150 }}
              value={tableSelect.roleId}
              onChange={(e) =>
                setTableSelect({ ...tableSelect, roleId: e, pageNum: 1 })
              }
              options={C1options}
            />
          </div>
        </div>
        {/* 右侧按钮 */}
        <div className="C1top2">
          <Button onClick={resetSelectFu}>重置</Button>&emsp;
          <Button
            type="primary"
            onClick={() => setOpenInfo({ id: -1, txt: "新增用户" })}
          >
            新增
          </Button>
        </div>
      </div>
      {/* 表格主体 */}
      <div className="tableMain">
        <Table
          scroll={{ y: 625 }}
          dataSource={C1TableList.list}
          columns={columns}
          rowKey="id"
          pagination={{
            showQuickJumper: true,
            position: ["bottomCenter"],
            showSizeChanger: true,
            current: tableSelect.pageNum,
            pageSize: tableSelect.pageSize,
            total: C1TableList.total,
            onChange: paginationChange(),
          }}
        />
      </div>

      {openInfo.id ? (
        <AddUser
          openInfo={openInfo}
          closeFu={() => setOpenInfo({ id: 0, txt: "" })}
          upTableFu={getListFu}
          addTableFu={resetSelectFu}
        />
      ) : null}
      {/*  右下角的列表数量 */}
      <div className="tableNumBox">
        共 <span>{C1TableList.total}</span> 条数据
      </div>
    </div>
  );
}

const MemoC1User = React.memo(C1User);

export default MemoC1User;
