import { useAjax } from "@/Hook/useAjax"
import { addAccountToGroupApi, delAccountToGroupApi } from "@/services/launchAdq/subgroup"
import { getArrDifference } from "@/utils/utils"
import { UsergroupAddOutlined } from "@ant-design/icons"
import { Button, Checkbox, message, Popover, Spin, Tooltip } from "antd"
import React, { useEffect, useState } from "react"
import { useModel } from "umi"


interface Props {
    groupIds: number[],
    accountId: number,
    getAdAccountList?: any
}
/**
 * 账号分组至xxx
 * @param props 
 */
const DivideIntoGroups: React.FC<Props> = (props) => {

    /********************************/
    const { groupIds = [], accountId, getAdAccountList } = props
    const { getGroupList } = useModel('useLaunchAdq.useAdAuthorize')
    const [visible, setVisible] = useState<boolean>(false);

    const addAccountToGroup = useAjax((params) => addAccountToGroupApi(params))
    const delAccountToGroup = useAjax((params) => delAccountToGroupApi(params))
    /********************************/

    const handleVisibleChange = (newOpen: boolean) => {
        setVisible(newOpen)
    }
    const onChange = (checkedValues: any[]) => {
        let newGroupid = getArrDifference(checkedValues, groupIds)
        if (newGroupid.length > 0) {
            if (checkedValues.length > groupIds.length) {  // 新增
                addAccountToGroup.run({ currGroupId: newGroupid[0], accountIds: [accountId] }).then(res => {
                    getAdAccountList.refresh()
                })
            } else {  // 删除
                delAccountToGroup.run({ currGroupId: newGroupid[0], accountIds: [accountId] }).then(res => {
                    getAdAccountList.refresh()
                })
            }
        }
    }

    return <Popover
        content={<Spin spinning={delAccountToGroup.loading || addAccountToGroup.loading}>
            <Checkbox.Group style={{ width: '100%' }} value={groupIds} onChange={onChange}>
                <ul className="dig_ul">
                    {getGroupList?.data?.map((item: { groupName: string, groupId: number }) => <li className="dig_ul__li" key={item.groupId}>
                        <Checkbox value={item.groupId}>{item.groupName}</Checkbox>
                    </li>)}
                </ul>
            </Checkbox.Group>
        </Spin>}
        title="选择分组"
        trigger="click"
        open={visible}
        overlayClassName="dig"
        onOpenChange={handleVisibleChange}
    >
        <Tooltip title="分组">
            <Button size="small" style={{ color: '#eb2f96' }} onClick={() => setVisible(true)}><UsergroupAddOutlined /></Button>
        </Tooltip>
    </Popover>
}


export default React.memo(DivideIntoGroups)