import { useAjax } from "@/Hook/useAjax"
import { UsergroupAddOutlined } from "@ant-design/icons"
import { Button, Checkbox, Popover, Spin, Tooltip } from "antd"
import React, { useEffect, useState } from "react"
import { addAccountToGroupApi, delAccountToGroupApi, getGroupListApi } from "../../API/corpUserManage"
import { getArrDifference } from "@/utils/utils"
import './global.less'

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

    /********************************/
    const { groupIds = [], corpUserList, onRefresh } = props

    const [visible, setVisible] = useState<boolean>(false);

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

    useEffect(() => {
        if (visible)
            getGroupList.run()
    }, [visible])

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

    return <Popover
        content={<Spin spinning={delAccountToGroup.loading || addAccountToGroup.loading}>
            <Checkbox.Group style={{ width: '100%' }} value={groupIds} onChange={onChange}>
                <ul className="dig_ul">
                    {getGroupList?.data?.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}
        classNames={{ body: 'dig' }}
        onOpenChange={handleVisibleChange}
    >
        <Tooltip title="分组">
            <Button size="small" style={{ color: '#eb2f96' }} onClick={() => setVisible(true)}><UsergroupAddOutlined /></Button>
        </Tooltip>
    </Popover>
}


export default React.memo(DivideIntoGroups)