import { SuperTable } from '@/components';
import SysRoleUserController from '@/services/apis/SysRoleUserController';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Modal, message } from 'antd';
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';

export interface UserListHandles {
    /** 移出成员 */
    remove: (id?: number) => void;
    /** 重新加载成员列表 */
    reload: () => void;
}

export type UserListProps = {
    role: API.SysRoleOutput;
};

/** 角色成员列表 */
const UserList = forwardRef<UserListHandles, UserListProps>(({ role }, ref) => {
    const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
    const actionRef = useRef<ActionType>(null);

    useEffect(() => {
        actionRef.current?.reset?.();
    }, [role.id]);

    const handleRemove = (user_id?: number) => {
        if (!user_id && selectedRowKeys.length === 0) {
            message.warning('至少选择一个用户！');
            return;
        }
        Modal.confirm({
            title: '提示',
            content: '确定立即移出已选择的用户吗？',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                const hide = message.loading('移出中...', 0);
                await SysRoleUserController.removeRoleUser({
                    sysRoleId: role.id ?? 1,
                    sysUserIdList: user_id ? [user_id] : selectedRowKeys,
                });
                hide();
                setSelectedRowKeys([]);
                // loadData();
                actionRef.current?.reload();
            },
        });
    };

    useImperativeHandle(ref, () => ({
        remove: handleRemove,
        reload: () => actionRef.current?.reload()
    }));

    const columns: ProColumns<API.SysUserOutput>[] = [
        {
            title: '姓名',
            dataIndex: 'name',
            width: 120,
        },
        {
            title: '所属机构',
            dataIndex: 'sysOrgs',
            hideInSearch: true,
            render: (_, r) => {
                return r.sysOrg?.name;
            }
        },
        {
            dataIndex: 'roles',
            title: '拥有角色',
            hideInSearch: true,
            render: (_, r) => {
                return r.sysRoles?.map(t => t.name)?.join('、');
            }
        },
        {
            title: '操作',
            width: 100,
            align: 'center',
            valueType: 'option',
            render: (_, r) => {
                if (r.id === 1) {
                    return null;
                }
                return (
                    <a
                        onClick={() => {
                            handleRemove(r.id);
                        }}
                    >
                        移除
                    </a>
                );
            },
        },
    ];

    return (
        <SuperTable<API.SysUserOutput>
            actionRef={actionRef}
            columns={columns}
            search={false}
            toolBarRender={false}
            tableAlertRender={false}
            sticky={false}
            rowKey="id"
            virtual
            rowSelection={{
                columnWidth: 32,
                checkStrictly: false,
                fixed: true,
                selections: false,
                onSelect: (record, selected, selectedRows) => {
                    setSelectedRowKeys(selectedRows.map((t) => t.id) || []);
                },
                onSelectAll: (_, selectedRows) => {
                    setSelectedRowKeys(selectedRows.map((t) => t.id) || []);
                },
                selectedRowKeys: selectedRowKeys,
                getCheckboxProps: (record) => ({
                    disabled: record.id === 2,
                }),
            }}
            request={async (params, sort) => {
                try {
                    return SuperTable.requestPageAgent({ params, sort }, async (p) => {
                        const res = await SysRoleUserController.queryInRoleUserPageList({ ...p, sysRoleId: role.id });
                        return res;
                    });
                }
                catch (ex) { return {}; }
            }}
        />
    );
});

export default UserList;
