import Tables from "@/components/Tables"
import { useAjax } from "@/Hook/useAjax"
import { getCrowdPackApi, sysCrowdPackApi } from "@/services/launchAdq/createAd"
import { CheckOutlined, SyncOutlined } from "@ant-design/icons"
import { Button, Input, Modal, Space } 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: { id: number }) => item?.id)).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])
    }

    return <Modal
        title={<Space>
            <span>人群包</span>
            <Button size="small" onClick={() => { synGoodsList() }} type="link" loading={sysCrowdPack.loading}>同步人群包</Button>
        </Space>}
        visible={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>
                </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)