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

/**
 * 自动扩量设置
 * @returns 
 */
interface Props {
    visible?: boolean,
    onClose?: () => void,
    onChange?: (data: any, expandData: { expandEnabled: boolean, expandTargeting: string[] }) => void,
    data: any,
    sysTargeting: any,
    expandData?: { expandEnabled: boolean, expandTargeting: string[] }
}
const ExpandModal: React.FC<Props> = (props) => {

    /******************************/
    const { visible, onClose, data: data1, onChange, sysTargeting, expandData } = props
    const [data, setData] = useState<any>(data1)
    const [tableData, setTableData] = useState<any[]>([])//table数据
    const [selectAdz, setSelectAdz] = useState<number>(1)   // 选择账户
    const [name, setName] = useState<string>('')
    const [disabledList, setDisabledList] = useState<boolean[]>([true, true, true, true])
    const [queryForm, setQueryForm] = useState<{ expandEnabled: boolean, expandTargeting: string[] }>(expandData || { expandEnabled: false, expandTargeting: [] })

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

    useEffect(() => {
        if (sysTargeting && sysTargeting?.targeting) {
            let newDisabledList: boolean[] = [true, true, true, true]
            Object.keys(sysTargeting?.targeting)?.forEach((item: any) => {
                switch (item) {
                    case 'geoLocation': // 地域
                        if (sysTargeting?.targeting[item]?.regions && sysTargeting?.targeting[item]?.regions?.length > 0) {
                            newDisabledList[0] = false
                        }
                        break
                    case 'age':
                        newDisabledList[1] = false
                        break
                    case 'gender':
                        newDisabledList[2] = false
                        break
                    case 'education':
                        newDisabledList[3] = false
                        break
                }
            })
            setDisabledList(newDisabledList)
        }
    }, [sysTargeting])

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

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

    // 获取人群包列表
    const getList = (accountIds: number[]) => {
        getCrowdPack.run({ accountIds, source: 'ADVERTISER_OWN_DATA' }).then(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, queryForm)
    }

    /** 表格选折 */
    const onChangeTable = (selectedRowKeys: React.Key[], selectedRows: any[]) => {
        if (selectedRows?.length > 10) {
            message.error('扩量种子人群最多选择10个')
            return
        }
        let newData = JSON.parse(JSON.stringify(data))
        newData[selectAdz - 1]['coldStartAudienceList'] = selectedRows
        setData([...newData])
    }

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

    /** 一键设置 */
    const setOnekey = () => {
        let expandNames: string[] = data[selectAdz - 1]['coldStartAudienceList']?.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), source: 'ADVERTISER_OWN_DATA' }).then(res => {
            if (res && typeof res === 'object') {
                Object.keys(res).forEach((key: string) => {
                    let values = expandNames.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 === key) {
                                return { ...item, coldStartAudienceList: values }
                            }
                            return item
                        })
                    }
                })
                setData(newData)
            }
            message.success('设置完成');
            hide()
        })
    }

    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.topContent} style={{ paddingBottom: queryForm.expandEnabled ? 4 : 20 }}>
            <Space direction='vertical'>
                <Space>
                    <strong className={style.title}>自动扩量:</strong>
                    <Switch onChange={(e) => {
                        setQueryForm({ ...queryForm, expandEnabled: e, expandTargeting: [] });
                        if (!e) {
                            let newData = JSON.parse(JSON.stringify(data))
                            newData = newData?.map((item: { coldStartAudienceList: any }) => {
                                return { ...item, coldStartAudienceList: [] }
                            })
                            setData([...newData])
                        }
                    }} checked={queryForm.expandEnabled} checkedChildren="开启" unCheckedChildren="关闭" />
                </Space>
                {queryForm.expandEnabled && <>
                    <Space>
                        <strong className={style.title}>不可突破定向:</strong>
                        <Checkbox.Group style={{ width: '100%' }} onChange={(e) => { setQueryForm({ ...queryForm, expandTargeting: e as string[] }) }} value={queryForm.expandTargeting} >
                            <Checkbox value="geo_location" disabled={disabledList[0]}>地域</Checkbox>
                            <Checkbox value="age" disabled={disabledList[1]}>年龄</Checkbox>
                            <Checkbox value="gender" disabled={disabledList[2]}>性别</Checkbox>
                            <Checkbox value="education" disabled={disabledList[3]}>学历</Checkbox>
                        </Checkbox.Group>
                    </Space>
                    <Space>
                        <strong className={style.title}>扩量种子人群(选填):</strong>
                    </Space>
                </>}
            </Space>
        </div>
        {queryForm.expandEnabled && <div className={style.content} style={{ borderTop: '1px solid #f0f0f0' }}>
            <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]['coldStartAudienceList']?.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 disabled={!data[selectAdz - 1]['coldStartAudienceList']?.length} onClick={setOnekey} type="link" loading={getCrowdPack.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]['coldStartAudienceList']?.map((item: any) => item?.id?.toString()),
                        onChange: onChangeTable,
                        getCheckboxProps: (record: any) => ({
                            id: record.id,
                        })
                    }}
                />
            </div>
        </div>}
    </Modal>
}


export default React.memo(ExpandModal)