import { useAjax } from "@/Hook/useAjax"
import { CheckOutlined, QuestionCircleOutlined, SyncOutlined } from "@ant-design/icons"
import { Button, message, Modal, Radio, Space, Table, Tooltip } from "antd"
import React, { useEffect, useState } from "react"
import style from '../GoodsModal/index.less'
import columns from './tableConfig'
import { getBatchUnionPositionPackagesApi, getWechatOfficialAccountApi, getWechatOfficialAccountsApi } from "@/services/adqV3/global"

/**
 * 优量汇流量包
 * @returns 
 */
interface Props {
    visible?: boolean,
    onClose?: () => void,
    onChange?: (data: PULLIN.AccountCreateLogsProps[]) => void,
    data: PULLIN.AccountCreateLogsProps[]
}
const PositionPackage: React.FC<Props> = (props) => {

    /************************/
    const { visible, onClose, data: data1, onChange } = props
    const [tableData, setTableData] = useState<any[]>([])//table数据
    const [selectAdz, setSelectAdz] = useState<number>(1)   // 选择广告主
    const [data, setData] = useState<PULLIN.AccountCreateLogsProps[]>(data1)
    const [loading, setLoading] = useState<boolean>(false)
    const [positionPackageType, setPositionPackageType] = useState<'unionPositionPackage' | 'excludeUnionPositionPackage'>('unionPositionPackage')

    const getBatchUnionPositionPackages = useAjax((params) => getBatchUnionPositionPackagesApi(params))
    const getBatchUnionPositionPackagesS = useAjax((params) => getBatchUnionPositionPackagesApi(params))
    /************************/

    useEffect(() => {
        if (data?.length > 0) {
            getList(data[selectAdz - 1].accountId, positionPackageType)
        } else {
            setTableData([])
        }
    }, [selectAdz, positionPackageType])

    // 获取流量包列表
    const getList = (accountId: number, positionPackageType: 'unionPositionPackage' | 'excludeUnionPositionPackage') => {
        getBatchUnionPositionPackages.run({ accountIds: [accountId], unionPackageType: positionPackageType === 'unionPositionPackage' ? 'UNION_PACKAGE_TYPE_INCLUDE' : 'UNION_PACKAGE_TYPE_EXCLUDE' }).then(res => {
            if (res?.length) {
                let data = res.find((item: { accountId: number }) => item.accountId === accountId)?.result || []
                setTableData(data)
            } else {
                setTableData([])
            }
        })
    }

    const handleOk = () => {
        onChange?.(data)
    }

    /** 设置选中广告主 */
    const handleSelectAdz = (value: number) => {
        if (value === selectAdz) {
            return
        }
        setSelectAdz(value)
    }

    /** 表格选折 */
    const onChangeTable = (_: React.Key[], selectedRows: any) => {
        let newData = JSON.parse(JSON.stringify(data))
        newData[selectAdz - 1][positionPackageType] = selectedRows?.length > 5 ? selectedRows.slice(0, 5) : selectedRows
        setData([...newData])
    }

    // 清空已选
    const clearGoods = () => {
        let newData = JSON.parse(JSON.stringify(data))
        newData[selectAdz - 1][positionPackageType] = []
        setData([...newData])
    }

    /** 一键设置 */
    const setOnekey = () => {
        let newData: PULLIN.AccountCreateLogsProps[] = JSON.parse(JSON.stringify(data))
        const hide = message.loading(`正在设置...`, 0, () => {
            message.success('设置成功');
        });
        let unionPackageNames: string[] = data[selectAdz - 1][positionPackageType]?.map((item: { unionPackageName: string }) => item.unionPackageName) || []
            getBatchUnionPositionPackagesS.run({ accountIds: newData?.filter(item => item.accountId !== data[selectAdz - 1].accountId)?.map(item => item?.accountId), unionPackageType: positionPackageType === 'unionPositionPackage' ? 'UNION_PACKAGE_TYPE_INCLUDE' : 'UNION_PACKAGE_TYPE_EXCLUDE' }).then(res => {
                if (res?.length > 0) {
                    res.forEach((i: { accountId: number, result: any[] }) => {
                        newData = newData.map(item => {
                            let searchData =i?.result?.filter(item => unionPackageNames.includes(item.unionPackageName))
                            if (item.accountId.toString() === i.accountId.toString() && searchData.length) {
                                return { ...item, [positionPackageType]: searchData }
                            }
                            return item
                        })
                    })
                    setData(newData)
                }
                message.success('设置完成');
                hide()
            })
    }


    return <Modal
        title={<strong>选择优量汇流量包</strong>}
        open={visible}
        onCancel={() => { onClose && onClose() }}
        onOk={handleOk}
        width={900}
        className={`${style.SelectPackage} modalResetCss`}
        bodyStyle={{ padding: '0 10px 0 10px' }}
    >
        <div className={style.content}>
            <div className={style.left}>
                <h4 className={style.title}>媒体账户</h4>
                <div className={style.accountIdList}>
                    {data?.map((item, index) => {
                        let positionPackage = data[index]?.[positionPackageType] || []
                        return <div key={index} onClick={() => { handleSelectAdz(index + 1) }} className={`${style.accItem} ${selectAdz === index + 1 && style.select} `}>
                            {item?.accountId}
                            {positionPackage?.length > 0 && <CheckOutlined style={{ color: '#1890ff' }} />}
                        </div>
                    })}
                </div>
            </div>
            <div className={style.right}>
                <Space style={{ marginBottom: 10 }} align="center">
                    <Radio.Group value={positionPackageType} onChange={(e) => setPositionPackageType(e.target.value)} buttonStyle="solid">
                        <Radio.Button value="unionPositionPackage">定投流量包</Radio.Button>
                        <Radio.Button value="excludeUnionPositionPackage">屏蔽流量包</Radio.Button>
                    </Radio.Group>
                    <Button icon={<SyncOutlined />} type='link' style={{ padding: 0 }} loading={getBatchUnionPositionPackages?.loading || getBatchUnionPositionPackagesS.loading} onClick={() => { getList(data[selectAdz - 1].accountId, positionPackageType) }}>刷新</Button>
                    {data?.length > 1 && <Button style={{ padding: 0 }} disabled={!data[selectAdz - 1][positionPackageType]?.length} onClick={() => setOnekey()} type="link" loading={getBatchUnionPositionPackages.loading || getBatchUnionPositionPackagesS.loading}>
                        <Space>
                            <span>一键设置</span>
                            <Tooltip color="#FFF" overlayInnerStyle={{ color: '#000' }} title="设置其它账号有相同名称的商品为那个账号的商品（注意需要用户商品称相同，否则不设置）">
                                <QuestionCircleOutlined />
                            </Tooltip>
                        </Space>
                    </Button>}
                    {(data[selectAdz - 1]?.[positionPackageType] || [])?.length > 0 && <Button style={{ padding: 0 }} type='link' danger onClick={() => { clearGoods() }}>清空{positionPackageType === 'unionPositionPackage' ? '定投流量包' : '屏蔽流量包'}</Button>}
                </Space>
                <Table
                    columns={columns()}
                    dataSource={tableData}
                    size="small"
                    loading={getBatchUnionPositionPackages?.loading}
                    scroll={{ y: 400 }}
                    rowKey={'unionPackageId'}
                    rowSelection={{
                        selectedRowKeys: data[selectAdz - 1]?.[positionPackageType]?.map((item: any) => item?.unionPackageId),
                        getCheckboxProps: (record: any) => {
                            let selectData = data?.[selectAdz - 1]?.[positionPackageType];
                            return {
                                disabled: selectData && selectData?.length >= 5 ? selectData.map(item => item.unionPackageId).includes(record.unionPackageId) ? false : true : false
                            }
                        },
                        onChange: onChangeTable
                    }}
                    onRow={(record) => ({
                        onClick: () => {
                            let newDatas = JSON.parse(JSON.stringify(data))
                            let oldData = newDatas[selectAdz - 1]?.[positionPackageType] || []
                            const selected = oldData?.some((item: any) => item?.unionPackageId === record.unionPackageId);
                            const newSelectedRows = selected
                                ? oldData?.filter((item: any) => item?.unionPackageId !== record.unionPackageId)
                                : [...oldData, record];
                            newDatas[selectAdz - 1][positionPackageType] = newSelectedRows;
                            setData([...newDatas])
                        },
                    })}
                />
            </div>
        </div>
    </Modal>
}

export default React.memo(PositionPackage)