import { App, Form, Modal, Transfer } from 'antd';
import React, { useEffect, useState } from 'react';
import { useAjax } from '@/Hook/useAjax';
import { updateMembersApi } from '../../API/groupManage';
import { getUserAllListApi } from '@/pages/login/API';
import { TransferItem } from 'antd/es/transfer';

interface UpdateUserProps {
    data: any
    visible?: boolean
    onChange?: () => void
    onClose?: () => void
}


const UpdateUser: React.FC<UpdateUserProps> = ({ data, visible, onChange, onClose }) => {

    /****************************************/
    const { message } = App.useApp()
    const [form] = Form.useForm();
    const [userList, setUserList] = useState<TransferItem[]>([])

    const updateMembers = useAjax((params) => updateMembersApi(params))
    const getUserAllList = useAjax(() => getUserAllListApi())
    /****************************************/

    useEffect(() => {
        getUserAllList.run().then(res => {
            if (res?.data) {
                setUserList(res.data.map(item => {
                    return {
                        key: item.userId,
                        title: item.nickname
                    }
                }))
            }
        })
    }, [visible])

    const handleOk = () => {
        form.validateFields().then((values) => {
            updateMembers.run({ ...values, groupId: data.id }).then((res) => {
                if (res?.data) {
                    message.success('更新成功')
                    onChange?.()
                }
            })
        }).catch((err) => {
            console.log('err', err)
            form.submit()
        });
    }

    return <Modal
        title={<strong>{data?.name} 项目组成员更新</strong>}
        open={visible}
        onCancel={onClose}
        width={500}
        onOk={handleOk}
        confirmLoading={updateMembers.loading}
    >
        <Form
            form={form}
            name="updateGRoup"
            layout='vertical'
            colon={false}
            scrollToFirstError={{
                behavior: 'smooth',
                block: 'center'
            }}
            onFinishFailed={({ errorFields }) => {
                message.error(errorFields?.[0]?.errors?.[0])
            }}
            preserve={true}
            initialValues={{ userIds: data?.userList?.map(item => item.userId) || [] }}
        >
            <Form.Item label={<strong>成员</strong>} name="userIds" rules={[{ required: true, message: '请选择成员!' }]} valuePropName='targetKeys'>
                <Transfer
                    dataSource={userList}
                    titles={['未选', '已选']}
                    showSearch
                    render={(item) => item.title}
                    oneWay
                    listStyle={{
                        width: 'calc(50% - 8px)', // 减去间距
                        height: 360,
                    }}
                />
            </Form.Item>
        </Form>
    </Modal>
};

export default React.memo(UpdateUser);