import { App, Button, Card, Form, Modal } from 'antd';
import React from 'react';
import SelectCorpUser from '../corpUserManage/selectCorpUser';
import { useAjax } from '@/Hook/useAjax';
import { bindCorpUserChatApi } from '../../API/groupLeaderManage';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import SelectGDUser from './selectGDUser';

interface AddGLProps {
    bindType: 1 | 2
    data: { [x: string]: any }
    visible?: boolean
    onChange?: () => void
    onClose?: () => void
}


const BindUser: React.FC<AddGLProps> = ({ bindType, data, visible, onChange, onClose }) => {

    /****************************************/
    const { message } = App.useApp()
    const [form] = Form.useForm();
    const corpUserList = Form.useWatch('corpUserList', form)
    const bindCorpUserChat = useAjax((params) => bindCorpUserChatApi(params))
    /****************************************/

    const handleOk = () => {
        form.validateFields().then((values) => {
            bindCorpUserChat.run({
                bindType,
                corpUserChatId: data.id,
                corpUserList: values.corpUserList.map(item => {
                    const { corpId, corpUserId } = item.corpUser[0]
                    const { externalUserId } = item.transferExternalUser[0]
                    return { corpId, corpUserId, transferExternalUserId: externalUserId }
                })
            }).then((res) => {
                if (res?.data) {
                    message.success('绑定成功')
                    onChange?.()
                }
            })
        }).catch((err) => {
            console.log('err', err)
            form.submit()
        });
    }

    return <Modal
        title={<strong>绑定{bindType === 1 ? '客服号' : '机器人号'}</strong>}
        open={visible}
        onCancel={onClose}
        width={500}
        onOk={handleOk}
        confirmLoading={bindCorpUserChat.loading}
    >
        <Form
            form={form}
            name="newGL"
            labelAlign='left'
            labelCol={{ span: 5 }}
            colon={false}
            scrollToFirstError={{
                behavior: 'smooth',
                block: 'center'
            }}
            onFinishFailed={({ errorFields }) => {
                message.error(errorFields?.[0]?.errors?.[0])
            }}
            preserve={true}
            initialValues={{ corpUserList: [{}] }}
        >
            <Form.List name='corpUserList'>
                {(fields, { add, remove }) => (
                    <>
                        {fields.map(({ key, name, ...restField }, i) => {
                            return <Card
                                key={i}
                                title={<strong>{bindType === 1 ? '客服号' : '机器人号'}</strong>}
                                style={{ background: '#fff', marginBottom: 10 }}
                                extra={corpUserList?.length > 1 ? <Button icon={<DeleteOutlined />} type='link' style={{ color: 'red' }} onClick={() => remove(name)}></Button> : null}
                            >
                                <Form.Item
                                    {...restField}
                                    label={<strong>{bindType === 1 ? '客服号' : '机器人号'}</strong>}
                                    name={[name, 'corpUser']}
                                    rules={[{ required: true, message: `请选择${bindType === 1 ? '客服号' : '机器人号'}` }]}
                                >
                                    <SelectCorpUser type='radio' placeholder={`请选择${bindType === 1 ? '客服号' : '机器人号'}`} />
                                </Form.Item>
                                <Form.Item
                                    {...restField}
                                    label={<strong>外部联系人</strong>}
                                    name={[name, 'transferExternalUser']}
                                    rules={[{ required: true, message: '请选择外部联系人!' }]}
                                >
                                    <SelectGDUser corpId={data.corpId} corpUserIds={[data.corpUserId]} />
                                </Form.Item>
                            </Card>
                        })}
                        <Form.Item>
                            <Button type="dashed" onClick={() => add({ externalUserType: 'all', id: Date.now() })} block icon={<PlusOutlined />}>
                                新增{bindType === 1 ? '客服号' : '机器人号'}
                            </Button>
                        </Form.Item>
                    </>
                )}
            </Form.List>
        </Form>
    </Modal>
};

export default React.memo(BindUser);