import { useAjax } from "@/Hook/useAjax"
import { CheckOutlined, QuestionCircleOutlined, SyncOutlined } from "@ant-design/icons"
import { Button, Input, message, Modal, Space, Table, Tooltip } from "antd"
import React, { useEffect, useState } from "react"
import style from '../GoodsModal/index.less'
import columns from './tableConfig'
import { getConversionInfoApi } from "@/services/adqV3/global"
import { useUpdateEffect } from "ahooks"
import { SMART_DELIVERY_GOAL_ENUM } from "../../tencentAdPutIn/const"

/**
 * 转化归因
 * @returns 
 */
interface Props {
    adgroups: any
    putInType?: 'NOVEL' | 'GAME'
    visible?: boolean,
    onClose?: () => void,
    onChange?: (data: PULLIN.AccountCreateLogsProps[]) => void,
    data: PULLIN.AccountCreateLogsProps[]
}
const ConversionSelect: React.FC<Props> = (props) => {

    /************************/
    const { putInType, visible, onClose, data: data1, onChange, adgroups } = 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 [accountId, setAccountId] = useState<number>(data[selectAdz - 1].accountId)
    const [conversionName, setConversionName] = useState<string>()
    const [adOptimizationGoal, setAdOptimizationGoal] = useState<string>()

    const getConversionInfo = useAjax((params) => getConversionInfoApi(params))
    /************************/

    useUpdateEffect(() => {
        setAccountId(data[selectAdz - 1].accountId)
    }, [selectAdz])

    useEffect(() => {
        if (data?.length > 0 && accountId) {
            getList(accountId)
        } else {
            setTableData([])
        }
    }, [accountId, adgroups, conversionName, putInType])

    // 获取公众号列表
    const getList = (accountId: number) => {
        const { optimizationGoal, deepConversionSpec, siteSet, marketingSubGoal, marketingAssetOuterSpec, marketingCarrierType, marketingGoal, deliveryMethod, smartDeliverySceneSpec } = adgroups
        let params: { [x: string]: any } = {}
        if (deliveryMethod === 'SMART') {
            const optimizationGoalCombos = SMART_DELIVERY_GOAL_ENUM?.[smartDeliverySceneSpec?.smartDeliveryGoal as keyof typeof SMART_DELIVERY_GOAL_ENUM]
            setAdOptimizationGoal(optimizationGoalCombos?.optimizationGoal)
            params = {
                accountId, pageNum: 1, pageSize: 200, conversionName,
                createSourceType: 'SELF_CREATED',
                optimizationGoal: optimizationGoalCombos?.optimizationGoal,
                deepWorthOptimizationGoal: optimizationGoalCombos?.deepWorthOptimizationGoal,
                marketingSubGoal,
                marketingTargetType: marketingAssetOuterSpec?.marketingTargetType,
                marketingCarrierType,
                marketingGoal,
                promotedObjectType: 'PROMOTED_OBJECT_TYPE_ECOMMERCE',
                taskType: putInType
            }
        } else {
            if (putInType === 'NOVEL') {
                params = { accountId, pageNum: 1, pageSize: 200, conversionName, createSourceType: 'SELF_CREATED', optimizationGoal, deepWorthOptimizationGoal: deepConversionSpec?.deepConversionWorthSpec?.goal, siteSet, taskType: putInType }
            } else {
                params = { accountId, pageNum: 1, pageSize: 200, marketingGoal, marketingSubGoal, conversionName, createSourceType: 'SELF_CREATED', optimizationGoal, deepWorthOptimizationGoal: deepConversionSpec?.deepConversionWorthSpec?.goal, siteSet, taskType: putInType }
            }
        }
        getConversionInfo.run(params).then(res => {
            setTableData(res?.records || [])
        })
    }

    const handleOk = () => {
        if (data.every(item => item?.newConversionList?.length)) {
            onChange && onChange(data)
        } else {
            message.error('请完善所有账号转化归因')
        }
    }

    /** 设置选中广告主 */
    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]['newConversionList'] = selectedRows
        setData([...newData])
    }

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

    /** 一键设置 */
    const setOnekey = () => {
        let conversionData: number[] = data[selectAdz - 1]['newConversionList']?.map((item: { conversionId: number }) => item.conversionId) || []
        let newData: PULLIN.AccountCreateLogsProps[] = JSON.parse(JSON.stringify(data))
        const hide = message.loading(`正在设置...`, 0, () => {
            message.success('设置成功');
        });
        let dataAjax = newData?.filter(item => item.accountId !== data[selectAdz - 1].accountId)?.map(item => item?.accountId).map(accountId => {
            let { optimizationGoal, deepConversionSpec, siteSet, marketingSubGoal, marketingGoal } = adgroups
            let params: any = {}
            if (putInType === 'NOVEL') {
                params = { accountId, pageNum: 1, pageSize: 10, conversionName, createSourceType: 'SELF_CREATED', optimizationGoal, deepWorthOptimizationGoal: deepConversionSpec?.deepConversionWorthSpec?.goal, siteSet, taskType: putInType }
            } else {
                params = { accountId, pageNum: 1, pageSize: 10, marketingGoal, marketingSubGoal, conversionName, createSourceType: 'SELF_CREATED', optimizationGoal, deepWorthOptimizationGoal: deepConversionSpec?.deepConversionWorthSpec?.goal, siteSet, taskType: putInType }
            }
            return getConversionInfoApi({ ...params, conversionId: conversionData?.[0] }).then(res => {
                if (res.data?.records) {
                    let data = res.data?.records
                    if (data?.length > 0) {
                        newData = newData.map(item => {
                            if (item.accountId.toString() === params?.accountId.toString()) {
                                return { ...item, newConversionList: res.data?.records }
                            }
                            return item
                        })
                    }
                }
            })
        })
        Promise.all(dataAjax).then(() => {
            setData(newData)
            message.success('设置完成');
            hide()
        }).catch(() => {
            hide()
            message.error('设置失败')
        })
    }


    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 newConversionList = data[index].newConversionList || []
                        return <div key={index} onClick={() => { handleSelectAdz(index + 1) }} className={`${style.accItem} ${selectAdz === index + 1 && style.select} `}>
                            {item?.accountId}
                            {newConversionList?.length > 0 && <CheckOutlined style={{ color: '#1890ff' }} />}
                        </div>
                    })}
                </div>
            </div>
            <div className={style.right}>
                <Space style={{ marginBottom: 10 }} align="end" size={0}>
                    <Input.Search enterButton allowClear onSearch={(value) => setConversionName(value)} placeholder="搜索转化名称" />
                    <Button icon={<SyncOutlined />} type='link' loading={getConversionInfo?.loading} onClick={() => { getList(data[selectAdz - 1].accountId) }}>刷新</Button>
                    {data?.length > 1 && <Button disabled={!data[selectAdz - 1]['newConversionList']?.length} onClick={() => setOnekey()} type="link" loading={getConversionInfo.loading}>一键设置</Button>}
                    {(data[selectAdz - 1]?.newConversionList || [])?.length > 0 && <Button type='link' onClick={() => { clearGoods() }}>清空</Button>}
                </Space>
                <Table
                    columns={columns() as any}
                    dataSource={tableData}
                    size="small"
                    loading={getConversionInfo?.loading}
                    scroll={{ y: 400 }}
                    rowKey={'conversionId'}
                    rowSelection={{
                        type: 'radio',
                        selectedRowKeys: data[selectAdz - 1]?.newConversionList?.map((item: any) => item?.conversionId),
                        onChange: onChangeTable,
                        getCheckboxProps: (record: any) => {
                            const { deepConversionSpec, deliveryMethod } = adgroups
                            if (deliveryMethod === 'SMART') {
                                return {
                                    disabled: adOptimizationGoal !== record.optimizationGoal
                                }
                            }
                            return {
                                disabled: !deepConversionSpec ? (record?.deepWorthOptimizationGoal || record?.deepBehaviorOptimizationGoal) ? true : false : false
                            }
                        },
                    }}
                // onRow={(record) => ({
                //     onClick: () => {
                //         let newDatas = JSON.parse(JSON.stringify(data))
                //         let oldData = newDatas[selectAdz - 1]?.newConversionList || []
                //         const selected = oldData?.some((item: any) => item?.conversionId === record.conversionId);
                //         const newSelectedRows = selected
                //             ? oldData?.filter((item: any) => item?.conversionId !== record.conversionId)
                //             : [...oldData, record];
                //         newDatas[selectAdz - 1]['newConversionList'] = newSelectedRows;
                //         setData([...newDatas])
                //     },
                // })}
                />
            </div>
        </div>
    </Modal>
}

export default React.memo(ConversionSelect)