import { userApi } from "@/api";
import { IRoleItem } from "@/types";
import { Button, Table } from "antd";
import { DageTableActions } from "@dage/pc-components";
import { useEffect, useState } from "react";
import { PageContainer } from "@/components";
import { PlusOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";

export default function RolePage() {
  const [list, setList] = useState<IRoleItem[]>([]);
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const getList = async () => {
    setLoading(true);
    try {
      const data = await userApi.getRoleList();
      setList(data);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: number) => {
    await userApi.deleteRole(id);
    getList();
  };

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

  return (
    <PageContainer
      title="角色管理"
      headerSlot={
        <Button
          type="primary"
          icon={<PlusOutlined />}
          size="large"
          onClick={() => navigate("/setting/role/create")}
        >
          新增
        </Button>
      }
    >
      <Table
        loading={loading}
        className="page-table"
        dataSource={list}
        columns={[
          {
            title: "角色名称",
            dataIndex: "roleName",
            align: "center",
          },
          {
            title: "角色说明",
            dataIndex: "roleDesc",
            align: "center",
          },
          {
            title: "操作",
            align: "center",
            render: (val) => (
              <DageTableActions
                onEdit={() => navigate(`/setting/role/edit/${val.id}`)}
                onDelete={handleDelete.bind(undefined, val.id)}
              />
            ),
          },
        ]}
        rowKey="id"
        pagination={false}
      />
    </PageContainer>
  );
}
