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 [selectedRows, setSelectedRows] = 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('取消成功')
                setSelectedRows([])
                getList()
            }
        }).catch(() => hide())
    }

    return <Modal
        title={<span><strong>{data.authMainAccountId} 授权子账户</strong><span style={{ fontSize: 12 }}>（主体：{data.corporationName}）</span></span>}
        open={visible}
        className="modalResetCss"
        width={720}
        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>
                <Button type="primary" danger disabled={selectedRows.length === 0} onClick={() => { del(selectedRows.map(item => item.accountId)) }}>取消授权</Button>
            </div>

            <Table
                columns={columns(del)}
                dataSource={dataSource}
                size="small"
                loading={getAccountAssetsGroupAccountList?.loading}
                scroll={{ y: 600 }}
                bordered
                rowKey={'id'}
                rowSelection={data.authType !== 'conversion' ? {
                    selectedRowKeys: selectedRows.map(item => item.id),
                    onSelect: (record: { id: number }, selected: boolean) => {
                        if (selected) {
                            selectedRows.push({ ...record })
                            setSelectedRows([...selectedRows])
                        } else {
                            let newSelectAccData = selectedRows.filter((item: { id: number }) => item.id !== record.id)
                            setSelectedRows([...newSelectAccData])
                        }
                    },
                    onSelectAll: (selected: boolean, selectedRowss: { id: number }[], changeRows: { id: number }[]) => {
                        if (selected) {
                            let newSelectAccData = [...selectedRows]
                            changeRows.forEach((item: { id: number }) => {
                                let index = newSelectAccData.findIndex((ite: { id: number }) => ite.id === item.id)
                                if (index === -1) {
                                    let data: any = { ...item }
                                    newSelectAccData.push(data)
                                }
                            })
                            setSelectedRows([...newSelectAccData])
                        } else {
                            let newSelectAccData = selectedRows.filter((item: { id: number }) => {
                                let index = changeRows.findIndex((ite: { id: number }) => ite.id === item.id)
                                if (index !== -1) {
                                    return false
                                } else {
                                    return true
                                }
                            })
                            setSelectedRows([...newSelectAccData])
                        }
                    }
                } : undefined}
            />
        </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)