import React from "react";
import { useNavigate } from "react-router-dom";
import { queryTable } from "@/utils/request";
import { ProTable } from "@ant-design/pro-components";
import { Button, message, Popconfirm } from "antd";
import { getUserList, updateUserStatus,deleteUser } from "@/services/user";

const queryUserList = queryTable(getUserList);

export default (props) => {
  const actionRef = React.useRef();
  const navigate = useNavigate();

  const updateStatus = (user) => {
    const status = user.status === 1 ? 0 : 1;
    const hide = message.loading("请稍候...", 0);
    updateUserStatus(user.id, status)
      .then((res) => {
        hide();
        actionRef.current.reload();
      })
      .catch(() => {
        hide();
      });
  };
  const handleDelete = (id) => {
    if (id) {
      deleteUser(id).then((res) => {
        actionRef.current.reload();
      });
    }
  };

  const columns = [
    {
      title: "id",
      dataIndex: "id",
      search: false,
    },
    {
      title: "姓名",
      dataIndex: "name",
    },
    {
      title: "部门",
      dataIndex: "dept",
    },
    {
      title: "手机号",
      dataIndex: "phone",
    },
    {
      title: "账号",
      dataIndex: "loginName",
      search: false,
    },
    {
      title: "状态",
      dataIndex: "status",
      search: false,
      valueEnum: {
        1: {
          text: "正常",
          status: "Processing",
        },
        0: {
          text: "禁用",
          status: "Error",
        },
      },
    },
    {
      title: "操作",
      valueType: "option",
      width: 200,
      render: (_, record) => [
        <Button
          key={1}
          style={{ padding: 0 }}
          type="link"
          onClick={() => {
            updateStatus(record);
          }}
        >
          {record.status === 1 ? "禁用" : "启用"}
        </Button>,
        <Button
          key={2}
          style={{ padding: 0 }}
          type="link"
          onClick={() => {
            console.log(record, "]]");
            navigate(`/system/user/edit?id=${record.id}`);
          }}
        >
          编辑
        </Button>,
        <Popconfirm
          key={3}
          title="您是否确认删除 ?"
          onConfirm={() => handleDelete(record.id)}
          okText="确定"
          cancelText="取消"
        >
          {/* manualPush */}
          <Button style={{ padding: 0 }} type="link">
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <ProTable
      actionRef={actionRef}
      rowKey="id"
      toolBarRender={() => [
        <Button
          key="1"
          type="primary"
          onClick={() => {
            navigate("/system/user/edit");
          }}
        >
          新增
        </Button>,
      ]}
      request={queryUserList}
      columns={columns}
    />
  );
};
