import { App, Modal, Select } from 'antd';
import React, { useEffect, useState } from 'react';
import { addAccountToGroupApi, delAccountToGroupApi, getGroupListApi } from '../../API/corpUserManage';
import { useAjax } from '@/Hook/useAjax';

interface SettingsGroupProps {
    data: any[],
    type: 'add' | 'del',
    visible?: boolean,
    onClose?: () => void,
    onChange?: () => void
}

/**
 * 批量设置分组
 * @returns 
 */
const SettingsGroup: React.FC<SettingsGroupProps> = ({ data, type, visible, onClose, onChange }) => {

    /*******************************************/
    const { message } = App.useApp()
    const [groupId, setGroupId] = useState<number>();
    const getGroupList = useAjax(() => getGroupListApi())
    const addAccountToGroup = useAjax((params) => addAccountToGroupApi(params))
    const delAccountToGroup = useAjax((params) => delAccountToGroupApi(params))
    /*******************************************/

    useEffect(() => {
        getGroupList.run()
    }, [])

    const handleOk = () => {
        if (groupId) {
            if (type === 'add') {
                addAccountToGroup.run({ currGroupId: groupId, corpUserList: data.map(item => ({ corpId: item.corpId, corpUserId: item.corpUserId })) }).then(res => {
                    onChange?.();
                    message.success('设置分组成功')
                })
            } else {
                delAccountToGroup.run({ currGroupId: groupId, corpUserList: data.map(item => ({ corpId: item.corpId, corpUserId: item.corpUserId })) }).then(res => {
                    onChange?.();
                    message.success('移除分组成功')
                })
            }

        } else {
            message.error('请选择分组')
        }
    }

    return <Modal
        title={<strong>{type === 'add' ? '添加到分组' : '移除分组'}</strong>}
        open={visible}
        onCancel={onClose}
        onOk={handleOk}
        confirmLoading={addAccountToGroup.loading || delAccountToGroup.loading}
    >
        <Select
            value={groupId}
            onChange={(e) => setGroupId(e)}
            showSearch
            placeholder="请选择分组"
            filterOption={(input, option) =>
                ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
            }
            style={{ width: '100%' }}
            allowClear
            options={getGroupList?.data?.data?.map((item: { groupName: string, groupId: number }) => ({ label: item.groupName, value: item.groupId }))}
        />
    </Modal>
};

export default SettingsGroup;