import { userApi } from "@/api";
import { GetLogListParams, HistoryItem, UserTableListType } from "@/types";
import {
  Button,
  Form,
  FormInstance,
  Input,
  Popconfirm,
  Switch,
  Table,
  message,
} from "antd";
import { debounce } from "lodash";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import UserAdd from "./components/UserAdd";

const DEFAULT_PARAMS: GetLogListParams = {
  pageNum: 1,
  pageSize: 20,
  startTime: "",
  endTime: "",
};

export default function IndustrialMeta() {
  const formRef = useRef<FormInstance>(null);
  const [list, setList] = useState<HistoryItem[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [editPageShow, setEditPageShow] = useState(false);
  const editId = useRef(0);
  const [params, setParams] = useState<GetLogListParams>({
    ...DEFAULT_PARAMS,
  });

  const getList = useCallback(async () => {
    setLoading(true);
    try {
      const { data } = await userApi.getList(params);
      setList(data.records);
      setTotal(data.total);
    } finally {
      setLoading(false);
    }
  }, [params]);

  useEffect(() => {
    getList();
  }, [getList, params]);

  const debounceSearch = useMemo(
    () =>
      debounce((changedVal: unknown, vals: GetLogListParams) => {
        setParams({ ...params, ...vals });
      }, 500),
    [params]
  );

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

  const paginationChange = useCallback(
    () => (pageNum: number, pageSize: number) => {
      setParams({ ...params, pageNum, pageSize });
    },
    [params]
  );

  const handleReset = useCallback(() => {
    setParams({ ...DEFAULT_PARAMS });
    formRef.current?.resetFields();
  }, [formRef]);

  // 点击删除
  const delTableFu = useCallback(
    async (id: number) => {
      await userApi.del(id);
      message.open({
        type: "success",
        content: "操作成功",
      });
      getList();
    },
    [getList]
  );

  // 点击重置密码
  const resetPassFu = useCallback(async (id: number) => {
    await userApi.resetPwd(id);
    message.open({
      type: "success",
      content: "操作成功",
    });
  }, []);

  const openEditPageFu = useCallback(
    (id: number) => {
      if (id === 0 && total >= 50)
        return message.open({
          type: "warning",
          content: "最多支持50个用户！",
        });

      editId.current = id;
      setEditPageShow(true);
    },
    [total]
  );

  const COLUMNS = useMemo(() => {
    return [
      {
        title: "账号名",
        dataIndex: "userName",
      },
      {
        title: "用户昵称",
        dataIndex: "nickName",
      },
      {
        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, resetPassFu, openEditPageFu]);

  return (
    <div className="user">
      <Form ref={formRef} layout="inline" onValuesChange={debounceSearch}>
        <Form.Item label="账号" name="searchKey">
          <Input
            className="w220"
            placeholder="请输入关键字"
            maxLength={30}
            showCount
            allowClear
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" onClick={openEditPageFu.bind(undefined, 0)}>
            新增
          </Button>
        </Form.Item>
        <Form.Item>
          <Button onClick={handleReset}>重置</Button>
        </Form.Item>
      </Form>

      <Table
        loading={loading}
        className="c-table"
        dataSource={list}
        columns={COLUMNS}
        rowKey="id"
        pagination={{
          showQuickJumper: true,
          position: ["bottomCenter"],
          showSizeChanger: true,
          current: params.pageNum,
          pageSize: params.pageSize,
          total,
          onChange: paginationChange(),
        }}
      />

      {/* 点击新增或者编辑 */}
      {editPageShow ? (
        <UserAdd
          id={editId.current}
          closePage={() => setEditPageShow(false)}
          upTableList={getList}
          addTableList={handleReset}
        />
      ) : null}
    </div>
  );
}
