import { Button, Input, message, Modal, Space, Table } from "antd"
import React, { useEffect, useState } from "react"
import '../../tencentAdPutIn/index.less'
import { PlusOutlined, SearchOutlined } from "@ant-design/icons"
import { useAjax } from "@/Hook/useAjax"
import { getAccountAssetsGroupAccountListApi, revokeAuthAccountAssetsGroupApi } from "@/services/adqV3/global"
import AddSubAccount from "./addSubAccount"
import columns from "./tableConfigSub"

interface Props {
    data?: any
    visible?: boolean
    onClose?: () => void
}

/**
 * 授权子账户
 * @param param0 
 * @returns 
 */
const SubAccount: React.FC<Props> = ({ data, visible, onClose }) => {

    /********************************************/
    const [queryForm, setQueryForm] = useState<{ accountids?: string[] }>()
    const [visibleS, setVisibleS] = useState<boolean>(false)
    const [dataSource, setDataSource] = useState<any[]>([])

    const getAccountAssetsGroupAccountList = useAjax((params) => getAccountAssetsGroupAccountListApi(params))
    const revokeAuthAccountAssetsGroup = useAjax((params) => revokeAuthAccountAssetsGroupApi(params))
    /********************************************/

    useEffect(() => {
        getList()
    }, [data])

    const getList = () => {
        getAccountAssetsGroupAccountList.run({ groupId: data.id }).then(res => {
            handleSearch(res || [])
        })
    }


    const handleSearch = (data: any) => {
        let accountids = queryForm?.accountids || []
        if (accountids?.length) {
            setDataSource(data?.filter((item: { accountId: number }) => accountids?.some(val => item.accountId?.toString().toLowerCase()?.includes(val))))
        } else {
            setDataSource(data)
        }
    }

    const del = (accountId: number[], assetId?: number) => {
        const hide = message.loading('取消授权中。。。')
        revokeAuthAccountAssetsGroup.run({ accountAssetsGroupId: data.id, accountId, assetId }).then(res => {
            hide()
            if (res) {
                message.success('取消成功')
                getList()
            }
        }).catch(() => hide())
    }

    return <Modal
        title={<span><strong>{data.authMainAccountId} 授权子账户</strong><span style={{ fontSize: 12 }}>（主体：{data.corporationName}）</span></span>}
        open={visible}
        className="modalResetCss"
        width={660}
        onCancel={onClose}
        footer={null}
    >
        <Space style={{ width: '100%' }} direction="vertical">
            <div className="flexStart" style={{ gap: 8 }}>
                <Input.TextArea
                    style={{ width: 300 }}
                    placeholder="请输入主账户ID列表（多个逗号隔开）"
                    allowClear
                    rows={1}
                    onChange={(e) => {
                        let value = e.target.value
                        let arr: any[] = []
                        if (value) {
                            value = value.replace(/[,，\s]/g, ',')
                            arr = value.split(',').filter((a: any) => a)
                        }
                        setQueryForm({ ...queryForm, accountids: arr })
                    }}
                />
                <Button type="primary" icon={<SearchOutlined />} onClick={() => getList()}>搜索</Button>
                <Button type="primary" icon={<PlusOutlined />} onClick={() => { setVisibleS(true) }}>子账户授权</Button>
            </div>

            <Table
                columns={columns(del)}
                dataSource={dataSource}
                size="small"
                loading={getAccountAssetsGroupAccountList?.loading}
                scroll={{ y: 600 }}
                bordered
                rowKey={'id'}
            />
        </Space>

        {visibleS && <AddSubAccount
            authType={data.authType}
            corporationName={data.corporationName}
            corporationLicence={data.corporationLicence}
            authMainAccountId={data.authMainAccountId}
            accountAssetsGroupId={data.id}
            selectedAccountIdList={getAccountAssetsGroupAccountList?.data || []}
            visible={visibleS}
            onClose={() => {
                setVisibleS(false)
            }}
            onChange={() => {
                setVisibleS(false)
                getList()
            }}
        />}
    </Modal>
}

export default React.memo(SubAccount)