import { useAjax } from "@/Hook/useAjax"
import { getAllUserAccountApi } from "@/services/launchAdq/adAuthorize"
import { addNewAccountToGroupApi, getAccountListApi } from "@/services/launchAdq/subgroup"
import { PlusOutlined } from "@ant-design/icons"
import { Button, Form, message, Modal, Select, Transfer } from "antd"
import React, { useEffect, useState } from "react"
import { useModel } from "umi"


interface Props {
    onChange?: () => void
}
/**
 * 新增至分组
 * @param props 
 * @returns 
 */
const AddAccountToGroup: React.FC<Props> = (props) => {

    /*********************************/
    const { onChange } = props
    const [form] = Form.useForm();
    let currGroupId = Form.useWatch('currGroupId', form)
    const [visible, setVisible] = useState<boolean>(false)
    const [mockData, setMockData] = useState<{ key: string, title: string }[]>([])
    const { getGroupList } = useModel('useLaunchAdq.useAdAuthorize')

    const getAccountList = useAjax((params) => getAccountListApi(params))
    const addNewAccountToGroup = useAjax((params) => addNewAccountToGroupApi(params))
    const getAllUserAccount = useAjax(() => getAllUserAccountApi())
    /*********************************/

    useEffect(() => {
        if (currGroupId) {
            getAccountList.run(currGroupId).then(res => {
                console.log(res);
                form.setFieldsValue({ accountIds: res?.adAccountList?.map((item: { accountId: string }) => item.accountId.toString()) || [] })
            })
        }
    }, [currGroupId])

    const addAccountToGroupHandle = () => {
        setVisible(true)
        getAllUserAccount.run().then(res => {
            setMockData(res?.map((item: { accountId: string, remark: string }) => ({ key: item.accountId.toString(), title: `${item.accountId}${item.remark ? '_' + item.remark : ''}` })))
        })
    }

    const handleOk = () => {
        form.validateFields().then(values => {
            addNewAccountToGroup.run(values).then(res => {
                message.success('修改成功')
                closeHandle()
                onChange?.()
            })
        })
    }

    const closeHandle = () => {
        setVisible(false)
        form.setFieldsValue({ currGroupId: undefined, accountIds: undefined })
    }

    return <>
        <Button onClick={addAccountToGroupHandle} type='primary' icon={<PlusOutlined />}>修改分组中账户</Button>
        {visible && <Modal
            title='修改分组中账户'
            open={visible}
            onOk={handleOk}
            onCancel={closeHandle}
            confirmLoading={addNewAccountToGroup.loading}
        >
            <Form
                form={form}
                labelCol={{ span: 4 }}
                colon={false}
                initialValues={{}}
            >
                <Form.Item label={<strong>分组</strong>} name='currGroupId' rules={[{ required: true, message: '请选择分组' }]}>
                    <Select placeholder='请选择分组'>
                        {getGroupList?.data?.map((item: { groupName: string, groupId: number }) => <Select.Option value={item.groupId} key={item.groupId}>{item.groupName}</Select.Option>)}
                    </Select>
                </Form.Item>
                {currGroupId && <Form.Item label={<strong>账号</strong>} name='accountIds' valuePropName='targetKeys' rules={[{ required: true, message: '请选择账号' }]}>
                    <Transfer
                        dataSource={mockData}
                        showSearch
                        titles={['未选', '已选']}
                        oneWay
                        filterOption={(input: any, option: any) => {
                            let newInput: string[] = input ? input?.split(/[,，\n\s]+/ig).filter((item: any) => item) : []
                            return newInput?.some(val => option!.title?.toString().toLowerCase()?.includes(val))
                        }}
                        listStyle={{ minHeight: 320 }}
                        render={item => item.title}
                    />
                </Form.Item>}
            </Form>
        </Modal>}
    </>
}


export default React.memo(AddAccountToGroup)