import Tables from "@/components/Tables"
import { useAjax } from "@/Hook/useAjax"
import { getCrowdPackApi, sysCrowdPackApi } from "@/services/launchAdq/createAd"
import { CheckOutlined, QuestionCircleOutlined, SyncOutlined } from "@ant-design/icons"
import { Button, Input, message, Modal, Space, Tooltip } from "antd"
import React, { useEffect, useState } from "react"
import style from '../goodsModal/index.less'
import columns from "./tableConfig"


const crowdpackData = [
    {
        id: 1,
        name: '定向用户群'
    },
    {
        id: 2,
        name: '排除用户群'
    }
]

/**
 * 获取人群包列表
 * @returns 
 */
interface Props {
    visible?: boolean,
    onClose?: () => void,
    onChange?: (data: any) => void,
    data: any
}
const CrowdPackModal: React.FC<Props> = (props) => {

    /*****************/
    const { visible, onClose, data: data1, onChange } = props
    const [data, setData] = useState<any>(data1)
    const [tableData, setTableData] = useState<any[]>([])//table数据
    const [selectAdz, setSelectAdz] = useState<number>(1)   // 选择账户
    const [selectCp, setSelectCp] = useState<number>(1)   // 选择自定义
    const [name, setName] = useState<string>('')

    const getCrowdPack = useAjax((params) => getCrowdPackApi(params))
    const sysCrowdPack = useAjax((params) => sysCrowdPackApi(params))
    /*****************/

    useEffect(() => {
        // customAudienceList?: any, excludedCustomAudienceList?: any
        if (data?.length > 0) {
            getList([data[selectAdz - 1].adAccountId])
        } else {
            setTableData([])
        }
    }, [selectAdz])

    const getKey = (index: number, reverse?: boolean) => {
        if (reverse) {
            if (index === 1) return 'excludedCustomAudienceList'
            return 'customAudienceList'
        } else {
            if (index === 1) return 'customAudienceList'
            return 'excludedCustomAudienceList'
        }
    }

    // 获取人群包列表
    const getList = (accountIds: number[]) => {
        getCrowdPack.run({ accountIds }).then(res => {
            console.log('res===>', res)
            if (res && Object.keys(res)?.indexOf(accountIds[0].toString()) !== -1) {
                setTableData(res[accountIds[0]]?.map((item: { audienceId: string }) => ({ ...item, id: item.audienceId })))
            } else {
                setTableData([])
            }
        })
    }

    const handleOk = () => {
        onChange && onChange(data)
    }

    // 同步人群包
    const synGoodsList = () => {
        sysCrowdPack.run(data?.map((item: { adAccountId: number }) => item?.adAccountId)).then(res => {
            getList([data[selectAdz - 1].adAccountId])
        })
    }

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

    const handleSelectCp = (value: number) => {
        if (value === selectCp) {
            return
        }
        setSelectCp(value)
    }

    /** 表格选折 */
    const onChangeTable = (selectedRowKeys: React.Key[], selectedRows: any) => {
        let newData = JSON.parse(JSON.stringify(data))
        newData[selectAdz - 1][getKey(selectCp)] = selectedRows
        setData([...newData])
    }

    /** 一键设置 */
    const setOnekey = () => {
        // selectCp 人或目标场景 1 customAudienceList 2 excludedCustomAudienceList  selectAdz 媒体账户  控制
        let crowdPackNames: string[] = data[selectAdz - 1][getKey(selectCp)]?.map((item: { name: string }) => item.name)
        let newData = JSON.parse(JSON.stringify(data))
        const hide = message.loading(`正在设置...`, 0, () => {
            message.success('设置成功');
        });
        getCrowdPack.run({ accountIds: newData?.filter((item: { adAccountId: number }) => item.adAccountId !== data[selectAdz - 1].adAccountId)?.map((item: { adAccountId: number }) => item?.adAccountId) }).then(res => {
            if (res && typeof res === 'object') {
                Object.keys(res).forEach((key: string) => {
                    let values = crowdPackNames.map(name => {
                        let value = res[key]?.find((item: { name: string }) => item.name === name)
                        if (value) {
                            return { ...value, id: value.audienceId }
                        }
                        return undefined
                    }).filter(item => item)
                    if (values.length > 0) {
                        newData = newData.map((item: { adAccountId: string }) => {
                            if (item.adAccountId.toString() === key.toString()) {
                                if (selectCp === 1) {
                                    return { ...item, customAudienceList: values }
                                } else {
                                    return { ...item, excludedCustomAudienceList: values }
                                }
                            }
                            return item
                        })
                    }
                })
                console.log('111111->', newData);
                
                setData(newData)
            }
            message.success('设置完成');
            hide()
        })
    }

    return <Modal
        title={<Space>
            <span>人群包</span>
            <Button size="small" onClick={() => { synGoodsList() }} type="link" loading={sysCrowdPack.loading}>同步人群包</Button>
        </Space>}
        open={visible}
        onCancel={() => { onClose && onClose() }}
        onOk={handleOk}
        width={1100}
        className={style.SelectPackage}
        bodyStyle={{ padding: '0 10px 0 10px' }}
    >
        <div className={style.content}>
            <div className={style.left} style={{ width: 140 }}>
                <h4 className={style.title}>人或目标场景</h4>
                {crowdpackData.map((item: { id: number, name: string }, index: number) => (
                    <div key={index} onClick={() => { handleSelectCp(index + 1) }} className={`${style.accItem} ${selectCp === index + 1 && style.select} `}>
                        {item?.name}
                        {data?.some((item: any) => item[getKey(index + 1)]?.length > 0) && <CheckOutlined style={{ color: '#1890ff' }} />}
                    </div>))
                }
            </div>
            <div className={style.left}>
                <h4 className={style.title}>媒体账户</h4>
                {data?.map((item: { adAccountId: number, id: number }, index: number) => (
                    <div key={index} onClick={() => { handleSelectAdz(index + 1, item) }} className={`${style.accItem} ${selectAdz === index + 1 && style.select} `}>
                        {item?.adAccountId}
                        {data[index][getKey(selectCp)]?.length > 0 && <CheckOutlined style={{ color: '#1890ff' }} />}
                    </div>
                ))}
            </div>
            <div className={style.right}>
                <Space style={{ marginBottom: 10 }}>
                    <Input placeholder="请输入用户群名称" allowClear value={name} onChange={(e) => setName(e.target.value)} />
                    <Button icon={<SyncOutlined />} type='link' loading={getCrowdPack?.loading} onClick={() => { getList([data[selectAdz - 1].adAccountId]) }}></Button>
                    {data?.length > 1 && <Button size="small" disabled={!data[selectAdz - 1][getKey(selectCp)]?.length} onClick={setOnekey} type="link" loading={sysCrowdPack.loading}>
                        <Space>
                            <span>一键设置</span>
                            <Tooltip color="#FFF" overlayInnerStyle={{ color: '#000' }} title="设置其它账号下的人群包与当前账号选中的人群包名一模一样的配置（注意需要人群包名相同，否则不设置）">
                                <QuestionCircleOutlined />
                            </Tooltip>
                        </Space>
                    </Button>}
                </Space>
                <Tables
                    columns={columns()}
                    dataSource={tableData?.filter((item: { name: string }) => name ? item.name.indexOf(name) !== -1 : true)}
                    size="small"
                    loading={getCrowdPack?.loading}
                    scroll={{ y: 300 }}
                    bordered
                    defaultPageSize={100}
                    rowSelection={{
                        type: 'checkbox',
                        selectedRowKeys: data[selectAdz - 1][getKey(selectCp)]?.map((item: any) => item?.id?.toString()),
                        onChange: onChangeTable,
                        getCheckboxProps: (record: any) => ({
                            disabled: data[selectAdz - 1][getKey(selectCp, true)]?.map((item: any) => item?.id)?.includes(record.id),
                            id: record.id,
                        })
                    }}
                />
            </div>
        </div>
    </Modal>
}


export default React.memo(CrowdPackModal)