import { MovableModal } from '@/components';
import SysRoleUserController from '@/services/apis/SysRoleUserController';
import { Spin, Transfer, message } from 'antd';
import type { TransferItem } from 'antd/lib/transfer';
import React, { useEffect, useState } from 'react';

export type RoleUserAddModalProps = {
    role: API.SysRoleOutput;
    onFinish: () => void;
    onClose: () => void;
};

const RoleUserAddModal: React.FC<RoleUserAddModalProps> = ({ role, onFinish, onClose }) => {
    const [userList, setUserList] = useState<TransferItem[]>([]);
    const [targetKeys, setTargetKeys] = useState<string[]>([]);
    const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
    const [loading, setLoading] = useState<boolean>(true);

    useEffect(() => {
        (async () => {
            const res = await SysRoleUserController.getNotInRoleUserList({ roleid: role.id ?? 0 });
            setLoading(false);
            const list = (res ?? []).map((t) => ({
                key: `${t.id}`,
                title: t.name,
                description: t.sysOrg?.name,
            }));
            setUserList(list);
        })();
    }, [role.id]);

    const handleSave = async () => {
        if (targetKeys.length === 0) {
            message.error('至少选择一个用户！');
            return;
        }

        const hide = message.loading('保存中...', 0);
        setConfirmLoading(true);
        try {
            await SysRoleUserController.addRoleUser({
                sysRoleId: role.id ?? '0',
                sysUserIdList: targetKeys.map(t => parseInt(t)),
            });
            message.success('保存成功！');
            onFinish();
            onClose();
        } catch {
        } finally {
            hide();
            setConfirmLoading(false);
        }
    };

    return (
        <MovableModal
            title={`添加角色成员 - ${role?.name}`}
            width={992}
            open={true}
            maskClosable={false}
            confirmLoading={confirmLoading}
            onOk={handleSave}
            onCancel={onClose}
            destroyOnClose={true}
        >
            <Spin spinning={loading}>
                <Transfer
                    style={{ width: 960, height: 600 }}
                    listStyle={{ height: '100%', flex: 1 }}
                    titles={['未选用户', '已选用户']}
                    operations={['加入', '移出']}
                    showSearch
                    filterOption={(inputValue: string, option: any) =>
                        option.title.indexOf(inputValue) > -1
                    }
                    dataSource={userList}
                    targetKeys={targetKeys}
                    render={(t) => (
                        <span>
                            {t.title}
                            <span style={{ color: '#999' }}> - {t.description}</span>
                        </span>
                    )}
                    onChange={(tks) => setTargetKeys(tks)}
                    pagination={false}
                />
            </Spin>
        </MovableModal>
    );
};

export default RoleUserAddModal;
