import { AjaxPromise, useAjax } from '@/Hook/useAjax';
import { App, Form, Modal, Select } from 'antd';
import React, { useEffect } from 'react';
import { configCorpUsersApi } from '../../API/corpUserAssign';


interface OperZsProps {
    data: { [x: string]: any }[]
    corpId: string,
    visible?: boolean,
    onClose?: () => void,
    onChange?: () => void
    getUserAllList?: AjaxPromise
}

const OperZs: React.FC<OperZsProps> = ({ data, corpId, visible, onClose, onChange, getUserAllList }) => {

    /*******************************************/
    const [form] = Form.useForm()
    const { message } = App.useApp()

    const configCorpUsers = useAjax((params) => configCorpUsersApi(params))
    /*******************************************/

    useEffect(() => {
        if (data?.length === 1) {
            form.setFieldsValue(data[0])
        }
    }, [data])

    const handleOk = async () => {
        const values = await form.validateFields()
        console.log(values)
        const params = {
            corpId,
            corpUserRelations: data?.map(item => {
                return {
                    corpUserId: item.corpUserId,
                    userIds: values.userIds
                }
            })
        }
        configCorpUsers.run(params).then(res => {
            if (res?.data) {
                message.success('指派成功')
                onChange?.()
            }
        })
    }

    return <Modal
        title='指派运营助手'
        open={visible}
        onCancel={onClose}
        onOk={handleOk}
        confirmLoading={configCorpUsers.loading}
    >
        <Form
            name="basic_oper_zs"
            form={form}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            autoComplete="off"
            labelAlign="left"
            colon={false}
        >
            <Form.Item label="运营助理" name="userIds" rules={[{ required: true, message: '请选择运营助理!' }]}>
                <Select
                    showSearch
                    style={{ minWidth: 180 }}
                    allowClear
                    placeholder="选择运营"
                    mode="multiple"
                    filterOption={(input, option) =>
                        (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                >
                    {getUserAllList?.data?.data?.map((item: any) => <Select.Option value={item.userId} key={item.userId}>{item.nickname}</Select.Option>)}
                </Select>
            </Form.Item>
        </Form>
    </Modal>
};

export default OperZs;