import React, { useEffect, useState } from "react"
import { useAjax } from "@/Hook/useAjax"
import { getNovelGDTListApi, GetNovelGDTListProps, getNovelGDTTotalApi } from "@/services/iaaData"
import TablePro from "@/components/TablePro"
import columns12 from "./tableConfig"
import moment from "moment"
import { useModel } from "umi"
import { Button, Dropdown, message, Select, Space, Switch } from "antd"
import { modifyStatusBatchApi } from "@/services/gameData"
import { DeleteOutlined, DownOutlined, PauseCircleOutlined, PlayCircleOutlined } from "@ant-design/icons"
import DayAd from "./dayAd"
import QueryFormNovel from "@/components/QueryForm/queryFormNovel"
import UpdateAd3 from "@/pages/iaaData/components/UpdateAd3"
import AutoAcquisitionSet from "./autoAcquisitionSet"
import AutoAcquisitionSetTask from "@/pages/iaaData/components/AutoAcquisitionSet/autoAcquisitionSetTask"

/**
 * 腾讯广告列表
 * @returns 
 */
const TencentNovelAd: React.FC<{ configName?: string, dayConfigName?: string }> = ({ configName, dayConfigName }) => {

    /****************************************/
    const { initialState } = useModel('@@initialState');
    const [selectedRows, setSelectedRows] = useState<any[]>([])
    const [queryForm, setQueryForm] = useState<GetNovelGDTListProps>({
        pageNum: 1,
        pageSize: 30,
        dataTimeMin: moment().format('YYYY-MM-DD'),
        dataTimeMax: moment().format('YYYY-MM-DD'),
    })
    const [totalData, setTotalData] = useState<any[]>([])
    const [visible, setVisible] = useState<boolean>(false)
    const [promotionId, setPromotionId] = useState<number>()
    const [adName, setAdName] = useState<string>('')
    const [updateData, setUpdateDate] = useState<{ visible: boolean, type: '修改出价' | '修改名称' | '修改日限额' | '修改投放时间' | '删除' | '深度优化ROI' | '修改投放首日开始时间' }>({ visible: false, type: '修改出价' })
    const [autoAcqVisible, setAutoAcqVisible] = useState<boolean>(false)
    const [handleType, setHandleType] = useState<number>(1)
    const [isZj, setIsZj] = useState<boolean>(true)

    const modifyStatusBatch = useAjax((params) => modifyStatusBatchApi(params))
    const getGDTList = useAjax((params) => getNovelGDTListApi(params))
    const getGDTTotal = useAjax((params) => getNovelGDTTotalApi(params))
    /****************************************/

    useEffect(() => {
        getList()
    }, [queryForm, initialState?.iaaApp, initialState?.productType])

    const getList = () => {
        if (initialState?.iaaApp?.length && initialState?.productType) {
            getGDTList.run({ ...queryForm, appId: initialState.iaaApp, productType: initialState.productType })
            getGDTTotal.run({ ...queryForm, appId: initialState.iaaApp, productType: initialState.productType }).then((res: { data: { id: number; accountId: string } }) => {
                if (res?.data) {
                    let data = res?.data
                    data.id = 1
                    data.accountId = '总计'
                    setTotalData([data])
                } else {
                    setTotalData([{ id: 1, accountId: '总计' }])
                }
            })
        } else {
            setTotalData([{ id: 1, accountId: '总计' }])
            getGDTList.mutate({ data: undefined })
        }
    }

    const dayHandle = (data: any) => {
        setVisible(true)
        setAdName(data.adgroupName)
        setPromotionId(data.adgroupId)
    }

    // 批量启停
    const adStatus = (type: boolean) => {
        let newSelectedRows = []
        if (type) {
            newSelectedRows = selectedRows.filter((item: { configuredStatus: string, adgroupId: number }) => item.configuredStatus === 'AD_STATUS_SUSPEND')
        } else {
            newSelectedRows = selectedRows.filter((item: { configuredStatus: string, adgroupId: number }) => item.configuredStatus === 'AD_STATUS_NORMAL')
        }
        if (newSelectedRows.length === 0) {
            message.warn(`所有广告都是${type ? '启动' : '暂停'}状态,无需${type ? '启动' : '暂停'}操作`)
            return
        }
        let accountAdgroupMaps = [...new Set(newSelectedRows?.map(item => item.accountId + ',' + item.adgroupId))]
        modifyStatusBatch.run({ accountAdgroupMaps, suspend: !type }).then(res => {
            if (res?.data?.failIdList?.length === 0) {
                message.success(`${type ? '启动' : '暂停'}成功`)
                getGDTList.refresh()
                setSelectedRows([])
            } else {
                message.success(`${type ? '启动' : '暂停'}失败，${JSON.stringify(res?.data?.list)}`)
            }
        })
    }

    return <div>
        <TablePro
            czChild={<Space>
                <Switch checkedChildren="开启全选" unCheckedChildren="关闭全选" checked={!isZj} onChange={(e) => { setIsZj(!e); }} />
                <Select
                    style={{ width: 120 }}
                    onChange={(e) => {
                        setHandleType(e)
                        setSelectedRows([])
                    }}
                    value={handleType}
                    dropdownMatchSelectWidth={false}
                    options={[{ label: '广告操作', value: 1 }, { label: '修改首日付费 ROI', value: 3 }, { label: '修改首日变现 ROI', value: 4 }]}
                />
                <Button type='primary' style={{ background: '#67c23a', borderColor: '#67c23a' }} loading={modifyStatusBatch.loading} icon={<PlayCircleOutlined />} disabled={selectedRows.length === 0} onClick={() => adStatus(true)}>启动</Button>
                <Button type='primary' style={{ background: '#e6a23c', borderColor: '#e6a23c' }} loading={modifyStatusBatch.loading} icon={<PauseCircleOutlined />} disabled={selectedRows.length === 0} onClick={() => adStatus(false)}>暂停</Button>
                {handleType === 1 ? <>
                    <Button type='primary' danger icon={<DeleteOutlined />} disabled={selectedRows.length === 0} onClick={() => {
                        setUpdateDate({ visible: true, type: '删除' })
                    }}>删除</Button>
                    <Dropdown
                        menu={{
                            items: [
                                {
                                    label: <span style={{ display: 'inline-block', width: 120 }}>修改出价</span>,
                                    key: '1',
                                    disabled: selectedRows.length === 0,
                                    onClick: () => { setUpdateDate({ visible: true, type: '修改出价' }) }
                                },
                                {
                                    label: '修改名称',
                                    key: '2',
                                    disabled: selectedRows.length === 0,
                                    onClick: () => { setUpdateDate({ visible: true, type: '修改名称' }) }
                                },
                                {
                                    label: '修改日限额',
                                    key: '3',
                                    disabled: selectedRows.length === 0,
                                    onClick: () => { setUpdateDate({ visible: true, type: '修改日限额' }) }
                                },
                                {
                                    label: '修改投放日期',
                                    key: '4',
                                    disabled: selectedRows.length === 0,
                                    onClick: () => { setUpdateDate({ visible: true, type: '修改投放时间' }) }
                                },
                                {
                                    label: '修改投放首日开始时间',
                                    key: '5',
                                    disabled: selectedRows.length === 0,
                                    onClick: () => { setUpdateDate({ visible: true, type: '修改投放首日开始时间' }) }
                                },
                                {
                                    label: '一键起量',
                                    key: '6',
                                    disabled: selectedRows.length === 0,
                                    onClick: () => { setAutoAcqVisible(true) }
                                }
                            ]
                        }}
                        placement="bottomLeft"
                        arrow
                    >
                        <Button>
                            <Space>
                                修改广告
                                <DownOutlined />
                            </Space>
                        </Button>
                    </Dropdown>
                    <AutoAcquisitionSetTask
                        selectAdList={selectedRows}
                    />
                </> : handleType === 3 ? <>
                    <Button type='primary' disabled={selectedRows.length === 0} onClick={() => {
                        setUpdateDate({ visible: true, type: '深度优化ROI' })
                    }}>修改首日付费 ROI</Button>
                </> : handleType === 4 ? <>
                    <Button type='primary' disabled={selectedRows.length === 0} onClick={() => {
                        setUpdateDate({ visible: true, type: '深度优化ROI' })
                    }}>修改首日变现 ROI</Button>
                </> : null}
                <span style={{ color: 'red' }}>操作完数据结果延时5分钟之内，即时结果去腾讯后台查看</span>
            </Space>}
            leftChild={<QueryFormNovel
                initialValues={{ day3: [moment(), moment()] }}
                isAccountId
                isPutUserIdList
                isAdgroupId
                isAdgroupName
                isMarketingGoal
                isMarketingTargetType
                isMemo
                isRemark
                isBookNameList
                isDeleted
                isStatus
                isPromotedObjectName
                isPromotedObjectType
                isOptimizationGoal
                isCostTotalMin
                isThousandDisplayPriceTotalMin
                isConversionsCountTotalMin
                isIncomeRoi1
                isRegCost
                isRegCostPla
                isCpc
                day1={{ placeholder: ['广告创建日期开始', '广告创建日期结束'] }}
                day2={{ placeholder: ['投放日期开始', '投放日期结束'] }}
                day3={{ placeholder: ['消耗日期开始', '消耗日期结束'] }}
                onChange={(data: any) => {
                    console.log(data)
                    const { day1, day2, day3, bookNameList, ...params } = data
                    let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                    newQueryForm.pageNum = 1
                    if (day1 && day1?.length === 2) {
                        newQueryForm['adCreateTimeMin'] = moment(day1[0]).format('YYYY-MM-DD')
                        newQueryForm['adCreateTimeMax'] = moment(day1[1]).format('YYYY-MM-DD')
                    } else {
                        delete newQueryForm['adCreateTimeMin']
                        delete newQueryForm['adCreateTimeMax']
                    }

                    if (day2 && day2?.length === 2) {
                        newQueryForm['putDateBegin'] = moment(day2[0]).format('YYYY-MM-DD')
                        newQueryForm['putDateEnd'] = moment(day2[1]).format('YYYY-MM-DD')
                    } else {
                        delete newQueryForm['putDateBegin']
                        delete newQueryForm['putDateEnd']
                    }

                    if (day3 && day3?.length === 2) {
                        newQueryForm['dataTimeMin'] = moment(day3[0]).format('YYYY-MM-DD')
                        newQueryForm['dataTimeMax'] = moment(day3[1]).format('YYYY-MM-DD')
                    } else {
                        delete newQueryForm['dataTimeMin']
                        delete newQueryForm['dataTimeMax']
                    }

                    if (bookNameList) {
                        newQueryForm['bookNameList'] = bookNameList.replace(/[,，\s]/g, ',').split(',').filter((a: any) => a)
                    } else {
                        delete newQueryForm['bookNameList']
                    }
                    setQueryForm({ ...newQueryForm, ...params })
                }}
            />}
            isZj={isZj}
            totalData={totalData}
            config={columns12(dayHandle, () => { getList() })}
            configName={configName || '腾讯小说广告列表'}
            fixed={{ left: 4, right: 2 }}
            scroll={{ x: 1000, y: 620 }}
            title='腾讯广告列表'
            loading={getGDTList.loading}
            ajax={getGDTList}
            page={queryForm?.pageNum || 1}
            pageSize={queryForm?.pageSize || 20}
            total={getGDTList?.data?.data?.total || 0}
            dataSource={getGDTList?.data?.data?.records?.map((item: any) => ({ ...item, id: item.adgroupId, deepConversionSpec: item?.deepConversionSpecJson ? JSON.parse(item.deepConversionSpecJson) : {} }))}
            onChange={(pagination: any, _: any, sortData: any) => {
                let { current, pageSize } = pagination
                let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                if (sortData && sortData?.order) {
                    newQueryForm['sortAsc'] = sortData?.order === 'ascend' ? true : false
                    newQueryForm['sortFiled'] = sortData?.field
                } else {
                    delete newQueryForm['sortAsc']
                    delete newQueryForm['sortFiled']
                }
                newQueryForm.pageNum = current || newQueryForm.pageNum
                newQueryForm.pageSize = pageSize || newQueryForm.pageSize
                setQueryForm({ ...newQueryForm })
            }}
            rowSelection={{
                selectedRowKeys: selectedRows.map(item => item.adgroupId + ''),
                getCheckboxProps: (record: any) => ({
                    disabled:
                        handleType === 3 ? record.status === 'STATUS_DELETED' || record?.accountId === '总计' || !(record?.deepConversionSpec?.deepConversionWorthSpec?.goal === 'GOAL_1DAY_PURCHASE_ROAS') :
                            handleType === 4 ? record.status === 'STATUS_DELETED' || record?.accountId === '总计' || !(record?.deepConversionSpec?.deepConversionWorthSpec?.goal === 'GOAL_1DAY_MONETIZATION_ROAS') :
                                record.status === 'STATUS_DELETED' || record?.accountId === '总计'
                }),
                onSelect: (record: { adgroupId: number }, selected: boolean) => {
                    if (selected) {
                        selectedRows.push({ ...record })
                        setSelectedRows([...selectedRows])
                    } else {
                        let newSelectAccData = selectedRows.filter((item: { adgroupId: number }) => item.adgroupId !== record.adgroupId)
                        setSelectedRows([...newSelectAccData])
                    }
                },
                onSelectAll: (selected: boolean, selectedRowss: { adgroupId: number }[], changeRows: { adgroupId: number }[]) => {
                    if (selected) {
                        let newSelectAccData = [...selectedRows]
                        changeRows.forEach((item: { adgroupId: number }) => {
                            let index = newSelectAccData.findIndex((ite: { adgroupId: number }) => ite.adgroupId === item.adgroupId)
                            if (index === -1) {
                                newSelectAccData.push({ ...item })
                            }
                        })
                        setSelectedRows([...newSelectAccData])
                    } else {
                        let newSelectAccData = selectedRows.filter((item: { adgroupId: number }) => {
                            let index = changeRows.findIndex((ite: { adgroupId: number }) => ite.adgroupId === item.adgroupId)
                            if (index !== -1) {
                                return false
                            } else {
                                return true
                            }
                        })
                        setSelectedRows([...newSelectAccData])
                    }
                }
            }}
        />

        {visible && <DayAd configName={dayConfigName} appId={initialState?.iaaApp as number[]} productType={initialState?.productType as string} adName={adName} visible={visible} onClose={() => { setVisible(false); setPromotionId(undefined) }} queryForm={{ costDayBegin: queryForm?.dataTimeMin, costDayEnd: queryForm?.dataTimeMax }} promotionId={promotionId} />}

        {/* 修改广告 */}
        {updateData.visible && <UpdateAd3
            {...updateData}
            updateData={selectedRows}
            onClose={() => {
                setUpdateDate({ visible: false, type: '修改出价' })
            }}
            onChange={() => {
                setUpdateDate({ visible: false, type: '修改出价' })
                getGDTList.refresh()
                if (updateData.type === '删除') {
                    setSelectedRows([])
                }
            }}
        />}

        {/* 批量一键起量 */}
        {autoAcqVisible && <AutoAcquisitionSet
            selectAdList={selectedRows}
            visible={autoAcqVisible}
            onClose={() => {
                setAutoAcqVisible(false)
            }}
            onChange={() => {
                setAutoAcqVisible(false)
                getGDTList.refresh()
                setSelectedRows([])
            }}
        />}
    </div>
}

export default TencentNovelAd