
import { useAjax } from '@/Hook/useAjax'
import { AdStatusEnum, PromotedObjectType } from '@/services/launchAdq/enum'
import { Col, Row, Input, Select, message, Space, Button, Popconfirm, Switch, notification, Modal } from 'antd'
import React, { useEffect, useCallback, useState } from 'react'
import TableData from '../../components/TableData'
import tableConfig from './tableConfig'
import { putAdqAdgroupsSync, getAdqAdgroupsList, delListAdqAdgroupsApi, newEditAdqAdgroupsDataApi, editAdqAdgroupsDataApi, putAdqAdgroupsSyncBatch } from '@/services/launchAdq/adq'
import { CopyOutlined, DeleteOutlined, FieldTimeOutlined, PauseCircleOutlined, PlayCircleOutlined, SyncOutlined, TransactionOutlined } from '@ant-design/icons'
import UpdateAd from './updateAd'
import Copy from './copy'
import PlanDetail from '@/pages/adMonitor/adMonitorList/components/planDetail'
import { txAdConfig } from '../config'
import Log from '../log'

type Props = {
    accountId?: string,
    adAccountId?: string,
    userId: string,
    Ts?: any,
    queryParmas?: {
        accountId?: string,//账户ID
        campaignId?: string,//计划ID
        adgroupId?: string,//广告ID
        adcreativeId?: string,//创意ID
        pageId?: string,//落地页ID
        targetingId?: string,//定向ID}
    },
    tableIdClick?: (props: {
        activeKey: string, parma: {
            accountId?: string,//账户ID
            campaignId?: string,//计划ID
            adgroupId?: string,//广告ID
            adcreativeId?: string,//创意ID
            pageId?: string,//落地页ID
            targetingId?: string,//定向ID
        }
    }) => void
}

const Ad: React.FC<Props> = (props) => {

    /***********************/
    let { accountId, adAccountId, userId, tableIdClick, queryParmas, Ts } = props
    const [selectedRows, setSelectedRows] = useState<any[]>([])
    const [update, setUpdate] = useState<{ visible: boolean, title: string }>({ visible: false, title: '' })
    const [model, setModel] = useState(true)
    const [copyData, setCopyData] = useState<{ visible: boolean }>({ visible: false })
    const [detailShow, setDetailShow] = useState<boolean>(false)
    const [detailData, setDetailData] = useState<any>({})
    const [czjlShow, setCzjlShow] = useState(false)
    const [queryFrom, set_queryFrom] = useState<{
        pageNum: number;
        pageSize: number;
        accountIdList?: any[];
        adgroupName?: string;
        adgroupIdList?: any[];
        promotedObjectType?: string;
        isDeleted?: boolean
        campaignIdList?: any[]
        statusList?: any[],
        memoList?: any[]
        remarkList?: any[]
    }>({ pageNum: 1, pageSize: 20 })
    const listAjax = useAjax((params) => getAdqAdgroupsList(params), { formatResult: true })
    const syncAjax = useAjax((adAccountId) => putAdqAdgroupsSync(adAccountId))
    const delListAdqAdgroups = useAjax((params) => delListAdqAdgroupsApi(params))
    const editAdqAdgroupsData = useAjax((params) => newEditAdqAdgroupsDataApi(params))
    const editAdqAdgroups = useAjax((params) => editAdqAdgroupsDataApi(params))
    const putAdqAdgroupsSyncBatchApi = useAjax((params) => putAdqAdgroupsSyncBatch(params))
    /************************/

    useEffect(() => {
        // let { accountId, campaignId, adgroupId, ...obj } = queryParmas
        // let new_queryParmas = {
        //     ...obj,
        //     accountIdList: accountId ? [accountId] : [],
        //     campaignIdList: campaignId ? [campaignId] : [],
        //     adgroupIdList: adgroupId ? [adgroupId] : []
        // }
        getList({ pageNum: 1, pageSize: 20 })
    }, [accountId, userId, queryParmas])

    // 获取列表
    const getList = useCallback((params: {
        pageNum: number;
        pageSize: number;
        accountIdList?: any[];
        adgroupName?: string;
        adgroupIdList?: any[];
        promotedObjectType?: string;
        isDeleted?: boolean
        campaignIdList?: any[]
        statusList?: any[],
        memoList?: any[]
        remarkList?: any[]
    }) => {
        listAjax.run({ ...params, userId })
    }, [userId, listAjax])
    // 同步 
    const sync = useCallback(() => {
        if (selectedRows?.length === 0) {
            message.error('请先勾选要同步的广点通账号!')
            return
        }
        let arr = [...new Set(selectedRows?.map(item => item.accountId))]
        syncAjax.run({ accountIdList: arr }).then(res => {
            res && listAjax.refresh()
            res ? message.success('同步成功！') : message.error('同步失败！')

        })
    }, [listAjax, selectedRows])

    /** 删除 */
    const deleteHandle = (type: 0 | 1, adgroupId?: number) => {
        delListAdqAdgroups.run({ adgroupIds: type === 1 ? selectedRows.map(item => item.adgroupId) : [adgroupId] }).then(res => {
            message.success('删除成功')
            setSelectedRows([])
            listAjax.refresh()
        })
    }

    /** 修改排期出价 */
    const editScheduling = () => {
        setUpdate({ visible: true, title: '批量修改' })
    }
    /** 修改排期出价 */
    const editDeepConversion = () => {
        setUpdate({ visible: true, title: '批量修改深度优化' })
    }

    // 单个启停
    const onChange = () => {
        listAjax.refresh()
        setSelectedRows([])
    }
    // 批量启停
    const adStatus = (type: 'play' | 'suspend') => {
        let params: any = {}
        if (type === 'play') {
            params.configuredStatus = 'AD_STATUS_NORMAL'
            params.adgroupIds = selectedRows.filter((item: { configuredStatus: string, adgroupId: number }) => item.configuredStatus === 'AD_STATUS_SUSPEND').map(item => item.adgroupId)
        } else {
            params.configuredStatus = 'AD_STATUS_SUSPEND'
            params.adgroupIds = selectedRows.filter((item: { configuredStatus: string, adgroupId: number }) => item.configuredStatus === 'AD_STATUS_NORMAL').map(item => item.adgroupId)
        }
        if (params.adgroupIds.length === 0) {
            message.warn(`所以账号都是${type === 'play' ? '启动' : '暂停'}状态,无需${type === 'play' ? '启动' : '暂停'}操作`)
            return
        }
        editAdqAdgroupsData.run(params).then(res => {
            message.success(`${type === 'play' ? '启动' : '暂停'}成功: ${res.success},失败: ${res.fail}`)//
            if (res?.fail) {
                notification.error({
                    message: `${type === 'play' ? '启动' : '暂停'}失败`,
                    description: `成功: ${res.success},修改失败${res.fail}条,失败的请到任务列表查看`,
                    duration: 0
                });
            }
            listAjax.refresh()
            setSelectedRows([])
        })
    }
    //同步广告
    const syncAd = useCallback(() => {
        putAdqAdgroupsSyncBatchApi.run({ adgroupIds: selectedRows?.map(item => item.adgroupId) }).then(res => {
            if (res) {
                message.success('同步成功！')
                listAjax.refresh()
            }
        })
    }, [selectedRows])
    // 批量复制
    const copyHandle = () => {
        setCopyData({ visible: true })
    }

    const handleSave = (row: any) => {
        const hide = message.loading(`广告“${row.adgroupId}”广告名称修改成<${row.adgroupName}>,修改中`, 0, () => {
            message.success('修改成功');
        });
        editAdqAdgroups.run({ adgroupIds: [row.adgroupId], adgroupName: row.adgroupName }).then(res => {
            message.success('修改广告名称成功')
            listAjax.refresh()
            hide()
        })
    }

    const details = (data: any) => {
        setDetailData(data)
        setDetailShow(true)
    }
    return <div>
        {/* 修改广告 */}
        {update.visible && <UpdateAd
            {...update}
            selectedRows={selectedRows}
            onChange={() => {
                setUpdate({ visible: false, title: '' })
                listAjax.refresh()
                setSelectedRows([])
            }}
            onClose={() => { setUpdate({ visible: false, title: '' }) }}
        />}
        {/* 复制广告 */}
        {copyData.visible && <Copy selectedRows={selectedRows} {...copyData} onClose={() => setCopyData({ visible: false })} onChange={() => { setCopyData({ visible: false }); listAjax.refresh(); setSelectedRows([]) }} />}
        <Row gutter={[6, 6]} align='middle' style={{ marginBottom: 15 }}>
            <Col>
                {Ts && Ts()}
            </Col>
            <Col>
                <Input
                    placeholder='广告账号'
                    allowClear
                    style={{ width: 120 }}
                    onChange={(e) => {
                        let value = e.target.value
                        let arr: any = []
                        if (value) {
                            value = value.replace(/[,，\s]/g, ',')
                            arr = value.split(',').filter((a: any) => a)
                        }
                        set_queryFrom({ ...queryFrom, accountIdList: arr })
                    }}
                />
            </Col>
            <Col>
                <Input
                    placeholder='广告名称'
                    allowClear
                    style={{ width: 120 }}
                    onChange={(e) => {
                        let value = e.target.value
                        set_queryFrom({ ...queryFrom, adgroupName: value })
                    }}
                />
            </Col>
            <Col>
                <Input
                    placeholder='广告ID'
                    allowClear
                    style={{ width: 120 }}
                    onChange={(e) => {
                        let value = e.target.value
                        let arr: any = []
                        if (value) {
                            value = value.replace(/[,，\s]/g, ',')
                            arr = value.split(',').filter((a: any) => a)
                        }
                        set_queryFrom({ ...queryFrom, adgroupIdList: arr })
                    }}
                />
            </Col>
            <Col>
                <Input
                    placeholder='计划ID'
                    allowClear
                    style={{ width: 120 }}
                    onChange={(e) => {
                        let value = e.target.value
                        let arr: any = []
                        if (value) {
                            value = value.replace(/[,，\s]/g, ',')
                            arr = value.split(',').filter((a: any) => a)
                        }
                        set_queryFrom({ ...queryFrom, campaignIdList: arr })
                    }}
                />
            </Col>
            <Col>
                <Select
                    placeholder='推广目标选择'
                    style={{ width: 120 }}
                    showSearch
                    filterOption={(input: any, option: any) =>
                        (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                    }
                    allowClear
                    onChange={(value: any) => {
                        set_queryFrom({ ...queryFrom, promotedObjectType: value })
                    }}
                >
                    {Object.keys(PromotedObjectType).map(key => {
                        return <Select.Option value={key} key={key}>{PromotedObjectType[key]}</Select.Option>
                    })}
                </Select>
            </Col>
            <Col>
                <Select
                    placeholder='是否已删除'
                    style={{ width: 120 }}
                    showSearch
                    filterOption={(input: any, option: any) =>
                        (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                    }
                    allowClear
                    onChange={(value: any) => {
                        set_queryFrom({ ...queryFrom, isDeleted: value })
                    }}
                >
                    <Select.Option value={true}>已删除</Select.Option>
                    <Select.Option value={false}>未删除</Select.Option>
                </Select>
            </Col>
            <Col>
                <Select
                    placeholder='广告状态'
                    mode="multiple"
                    style={{ width: 120 }}
                    showSearch
                    filterOption={(input: any, option: any) =>
                        (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                    }
                    allowClear
                    onChange={(value: any) => {
                        set_queryFrom({ ...queryFrom, statusList: value })
                    }}
                >
                    {
                        Object.keys(AdStatusEnum).map(key => {
                            return <Select.Option value={key} key={key}>{AdStatusEnum[key]}</Select.Option>
                        })
                    }
                </Select>
            </Col>
            <Col>
                <Input
                    placeholder='腾讯备注'
                    allowClear
                    style={{ width: 120 }}
                    onChange={(e) => {
                        let value = e.target.value
                        let arr: any = []
                        if (value) {
                            value = value.replace(/[,，\s]/g, ',')
                            arr = value.split(',').filter((a: any) => a)
                        }
                        set_queryFrom({ ...queryFrom, memoList: arr })
                    }}
                />
            </Col>
            <Col>
                <Input
                    placeholder='本地备注'
                    allowClear
                    style={{ width: 120 }}
                    onChange={(e) => {
                        let value = e.target.value
                        let arr: any = []
                        if (value) {
                            value = value.replace(/[,，\s]/g, ',')
                            arr = value.split(',').filter((a: any) => a)
                        }
                        set_queryFrom({ ...queryFrom, remarkList: arr })
                    }}
                />
            </Col>
            <Col>
                <Button type='primary' onClick={() => getList({ ...queryFrom, pageNum: 1 })}> 搜索</Button>
            </Col>
        </Row>
        <TableData
            isCard={false}
            columns={() => tableConfig(onChange, details, handleSave)}
            ajax={listAjax}
            syncAjax={sync}
            fixed={{ left: 2, right: 4 }}
            dataSource={listAjax?.data?.data?.records}
            loading={listAjax?.loading || syncAjax?.loading}
            scroll={{ y: 560 }}
            total={listAjax?.data?.data?.total}
            page={listAjax?.data?.data?.current}
            pageSize={listAjax?.data?.data?.size}
            myKey={'adgroupId'}
            gutter={[0, 10]}
            config={txAdConfig}
            configName="腾讯广告"
            leftChild={<Space direction='vertical'>
                <Row gutter={[10, 10]} align='middle'>
                    <Col>
                        <Switch checkedChildren="普通模式" unCheckedChildren="深度优化" checked={model} onChange={(checked) => { setModel(checked); setSelectedRows([]) }} style={model ? {} : { background: '#67c23a' }} />
                    </Col>
                    {model ? <>

                        <Col><Button  type='primary' style={{ background: '#1890ff' }} icon={<FieldTimeOutlined />} disabled={selectedRows.length === 0} onClick={editScheduling}>修改排期出价名称</Button></Col>
                        <Col><Button type='primary' style={{ background: '#1890ff' }} icon={<CopyOutlined />} disabled={selectedRows.length === 0} onClick={copyHandle}>批量复制</Button></Col>
                        <Col><Button type='primary' style={{ background: '#67c23a', borderColor: '#67c23a' }} loading={editAdqAdgroupsData.loading} icon={<PlayCircleOutlined />} disabled={selectedRows.length === 0} onClick={() => adStatus('play')}>启动广告</Button></Col>
                        <Col><Button type='primary' style={{ background: '#e6a23c', borderColor: '#e6a23c' }} loading={editAdqAdgroupsData.loading} icon={<PauseCircleOutlined />} disabled={selectedRows.length === 0} onClick={() => adStatus('suspend')}>暂停广告</Button></Col>
                        <Col><Button type='primary' style={{ background: '#00bcd4', borderColor: '#00bcd4' }} loading={putAdqAdgroupsSyncBatchApi.loading} icon={<SyncOutlined />} disabled={selectedRows.length === 0} onClick={syncAd}>批量同步广告</Button></Col>
                        <Col>
                            <Popconfirm
                                title="确定删除?"
                                onConfirm={() => deleteHandle(1)}
                                okText="是"
                                cancelText="否"
                                disabled={selectedRows.length === 0}
                            >
                                <Button danger type='primary' loading={delListAdqAdgroups.loading} icon={<DeleteOutlined />} disabled={selectedRows.length === 0}>删除</Button>
                            </Popconfirm>
                        </Col>
                    </> : <Col><Button type='primary' icon={<TransactionOutlined />} disabled={selectedRows.length === 0} onClick={editDeepConversion}>修改深度优化ROI</Button></Col>}
                    <Col>
                        <Button type='dashed' onClick={() => { setCzjlShow(true) }}>操作记录</Button>
                    </Col>
                </Row>
            </Space>}
            rowSelection={{
                selectedRowKeys: selectedRows.map(item => item.adgroupId.toString()),
                getCheckboxProps: (record: any) => ({
                    disabled: model ?
                        record.status === 'STATUS_DELETED' :
                        record.status === 'STATUS_DELETED' ||
                        !(!model &&
                            record?.promotedObjectType === 'PROMOTED_OBJECT_TYPE_WECHAT_OFFICIAL_ACCOUNT' &&
                            record?.optimizationGoal === 'OPTIMIZATIONGOAL_FOLLOW' &&
                            record?.deepConversionSpec?.deepConversionWorthSpec?.goal === 'GOAL_1DAY_PURCHASE_ROAS'
                        )
                }),
                onChange: (selectedRowKeys: any, selectedRowss: any) => {
                    let newArr: any = [...selectedRows]
                    let type = selectedRowss.length === 0 ? 'delAll' : selectedRowss.length === listAjax?.data.data.records.length ? 'add' : 'del'
                    switch (type) {
                        case 'add':
                            console.log('新增')
                            newArr = [...newArr, ...selectedRowss]
                            break;
                        case 'del':
                            console.log('删除')
                            newArr.forEach((item: { adgroupId: any }) => {
                                if (selectedRowss.every((i: { adgroupId: any }) => i.adgroupId != item.adgroupId)) {
                                    newArr = newArr.filter((i: { adgroupId: any }) => i.adgroupId != item.adgroupId)
                                }
                            })
                            break;
                        case 'delAll':
                            console.log('删除全部')
                            newArr.forEach((item: { adgroupId: any }) => {
                                if (listAjax?.data.data.records.some((i: { adgroupId: any }) => i.adgroupId == item.adgroupId)) {
                                    newArr = newArr.filter((i: { adgroupId: any }) => i.adgroupId != item.adgroupId)
                                }
                            })
                            break;
                    }
                    setSelectedRows(newArr)
                }
            }}
            onChange={(props: any) => {
                let { sortData, pagination } = props
                let { current, pageSize } = pagination
                // console.log(pagination)
                // console.log({...queryFrom, pageNum: current, pageSize })
                set_queryFrom({ ...queryFrom, pageNum: current, pageSize })
                getList({ ...queryFrom, pageNum: current, pageSize })
            }}
        />
        {detailShow && <PlanDetail visible={detailShow} onClose={() => { setDetailShow(false) }} data={detailData} />}
        {czjlShow && <Modal
            visible={czjlShow}
            onCancel={() => { setCzjlShow(false) }}
            onOk={() => { setCzjlShow(false) }}
            width={1200}
            footer={null}
            title={"广告操作记录"}
        >
            <Log {...props} />
        </Modal>}
    </div>
}
export default Ad