import { useAjax } from "@/Hook/useAjax"
import { addAccountUserApi, cutPutApi } from "@/services/operating/accountyyb"
import { Form, message, Modal, Select } from "antd"
import React, { useEffect, useState } from "react"


interface Props {
    allOfMember: any
    onChange?: () => void
    onClose?: () => void
    visible?: boolean,
    value?: any[]
}

/**
 * 指派
 * @param props 
 * @returns 
 */
const AppointPut: React.FC<Props> = (props) => {
    /*******************************/
    const { onChange, onClose, visible, allOfMember, value = [] } = props
    const [userAll, setUserAll] = useState([])

    const [form] = Form.useForm();
    const addAccountUser = useAjax((params) => addAccountUserApi(params))
    /*******************************/

    useEffect(() => {
        if (value.length === 1) {
            console.log('value--->', value[0].accountUsers?.map((item: any) => item.putUserId));
        
            form.setFieldsValue({ putUserIds: value[0].accountUsers?.map((item: any) => item.putUserId) })
        }
    }, [value])

    /** 获取组员 */
    useEffect(() => {
        (async function () {
            let res = allOfMember?.data || await allOfMember.run()
            if (res?.data) {
                let useAll: any = []
                res?.data?.forEach((item: any) => {
                    let obj = {
                        key: item.userId,
                        label: item.nickname
                    }
                    useAll.push(obj)
                })
                setUserAll(useAll)
            }
        })()
    }, [])

    const handleOk = () => {
        form.validateFields().then(values => {
            addAccountUser.run({ ...values, accountIds: value.map((item: { accountId: number }) => item.accountId) }).then(res => {
                message.success('指派成功')
                onChange?.()
            })
        })
    }

    return <Modal
        title="指派投放助理"
        open={visible}
        onOk={handleOk}
        onCancel={() => onClose?.()}
        confirmLoading={addAccountUser.loading}
    >
        <Form
            form={form}
            labelCol={{ span: 4 }}
            colon={false}
            initialValues={{}}
        >
            <Form.Item label={<strong>组员</strong>} name='putUserIds' rules={[{ required: true, message: '请选择分组' }]}>
                <Select
                    placeholder='请选择组员'
                    showSearch
                    mode="multiple"
                    filterOption={(input: string, option: any) => {
                        return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }}
                >
                    {userAll?.map((item: { key: string, label: number }) => <Select.Option value={item.key} key={item.key}>{item.label}</Select.Option>)}
                </Select>
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(AppointPut)