import React, { useEffect, useState } from "react"
import DayAd from "./dayAd"
import columns12 from "./tableConfig"
import { getPresets } from "@/components/QueryForm/const"
import TableData from "../../components/TableData"
import QueryForm from "@/components/QueryForm"
import { PromotionDataDay, getPromotionDataTencentListApi, getPromotionDataTencentTotalApi, newEditAdqAdgroupsDataApi } from "@/services/gameData/adlist"
import { useAjax } from "@/Hook/useAjax"
import moment from "moment"
import { Button, Space, Switch, message, notification } from "antd"
import { PauseCircleOutlined, PlayCircleOutlined } from "@ant-design/icons"



const TencentMonitor: React.FC = () => {

    /***************************************/
    const [queryForm, setQueryForm] = useState<PromotionDataDay>({ pageNum: 1, pageSize: 50, sourceSystem: 'ZX_ONE', costBeginDate: moment().format('YYYY-MM-DD'), costEndDate: 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 [selectedRows, setSelectedRows] = useState<any[]>([])
    const [isZj, setIsZj] = useState<boolean>(true)

    const getPromotionDataTencentList = useAjax((params) => getPromotionDataTencentListApi(params))
    const getPromotionDataTencentTotal = useAjax((params) => getPromotionDataTencentTotalApi(params))
    const editAdqAdgroupsData = useAjax((params) => newEditAdqAdgroupsDataApi(params))
    /***************************************/

    useEffect(() => {
        getPromotionDataTencentList.run(queryForm)
        getPromotionDataTencentTotal.run(queryForm).then(res => {
            res.id = 1
            res.accountName = '总计'
            setTotalData([res])
        })
    }, [queryForm])

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

    // 批量启停
    const adStatus = (type: 'play' | 'suspend') => {
        let params: any = {}
        if (type === 'play') {
            params.configuredStatus = 'AD_STATUS_NORMAL'
            params.adgroupIds = selectedRows.filter((item: { configuredStatus: string, promotionId: number }) => item.configuredStatus === 'AD_STATUS_SUSPEND').map(item => item.promotionId)
        } else {
            params.configuredStatus = 'AD_STATUS_SUSPEND'
            params.adgroupIds = selectedRows.filter((item: { configuredStatus: string, promotionId: number }) => item.configuredStatus === 'AD_STATUS_NORMAL').map(item => item.promotionId)
        }
        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
                });
            }
            getPromotionDataTencentList.refresh()
            setSelectedRows([])
        })
    }

    return <div>
        <TableData
            czChild={<Space>
                {/* <Switch checkedChildren="开启全选" unCheckedChildren="关闭全选" checked={!isZj} onChange={(e) => { setIsZj(!e); }} /> */}
                <Button type='primary' size="small" style={{ background: '#67c23a', borderColor: '#67c23a' }} loading={editAdqAdgroupsData.loading} icon={<PlayCircleOutlined />} disabled={selectedRows.length === 0} onClick={() => adStatus('play')}>启动</Button>
                <Button type='primary' size="small" style={{ background: '#e6a23c', borderColor: '#e6a23c' }} loading={editAdqAdgroupsData.loading} icon={<PauseCircleOutlined />} disabled={selectedRows.length === 0} onClick={() => adStatus('suspend')}>暂停</Button>
                <span style={{ color: 'red' }}>操作完数据结果延时5分钟之内，即时结果去腾讯后台查看</span>
            </Space>}
            leftChild={<QueryForm
                initialValues={{ sourceSystem: 'ZX_ONE', consumeDay: [moment(), moment()] }}
                onChange={(data: any) => {
                    const { type, gameClassify, costBeginDay, costEndDay, sysUserName, ...params } = data
                    let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                    newQueryForm.pageNum = 1
                    newQueryForm.pitcherName = sysUserName
                    newQueryForm.accountType = type
                    newQueryForm.classify = gameClassify
                    if (costBeginDay && costEndDay) {
                        newQueryForm.costBeginDate = costBeginDay
                        newQueryForm.costEndDate = costEndDay
                    } else {
                        delete newQueryForm.costBeginDate
                        delete newQueryForm.costEndDate
                    }
                    setQueryForm({ ...newQueryForm, ...params })
                }}
                isSource
                isAccountId
                isAccount
                isType
                isAgentId
                isBGGameClassify
                isConsumeDay={{ ranges: getPresets() }}
                isCpName
                isGameId
                isSysUserId
                isProjectId
                isProjectName
                isPromotionId
                isPromotionName
                isAdTXStatus
            />}
            isZj={isZj}
            totalData={totalData}
            scroll={{ x: 1000, y: 600 }}
            ajax={getPromotionDataTencentList}
            fixed={{ left: 3, right: 1 }}
            dataSource={getPromotionDataTencentList?.data?.records?.map((item: any) => ({ ...item, id: Number(item.promotionId) }))}
            total={getPromotionDataTencentList?.data?.total}
            page={queryForm.pageNum}
            pageSize={queryForm.pageSize}
            sortData={{
                field: queryForm?.sortFiled,
                order: queryForm?.sortType === 'asc' ? 'ascend' : 'descend'
            }}
            title='腾讯广告监控'
            onChange={(props: any) => {
                let { pagination, sortData } = props
                let { current, pageSize } = pagination
                let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                if (sortData && sortData?.order) {
                    newQueryForm['sortType'] = sortData?.order === 'ascend' ? 'asc' : 'desc'
                    newQueryForm['sortFiled'] = sortData?.field
                } else {
                    delete newQueryForm['sortType']
                    delete newQueryForm['sortFiled']
                }
                newQueryForm.pageNum = current
                newQueryForm.pageSize = pageSize
                setQueryForm({ ...newQueryForm })
            }}
            rowSelection={{
                selectedRowKeys: selectedRows.map(item => item.promotionId + ''),
                getCheckboxProps: (record: any) => ({
                    disabled: record.status === 'STATUS_DELETED' || record?.accountName === '总计'
                }),
                onSelect: (record: { promotionId: number }, selected: boolean) => {
                    if (selected) {
                        selectedRows.push({ ...record })
                        setSelectedRows([...selectedRows])
                    } else {
                        let newSelectAccData = selectedRows.filter((item: { promotionId: number }) => item.promotionId !== record.promotionId)
                        setSelectedRows([...newSelectAccData])
                    }
                },
                onSelectAll: (selected: boolean, selectedRowss: { promotionId: number }[], changeRows: { promotionId: number }[]) => {
                    if (selected) {
                        let newSelectAccData = [...selectedRows]
                        changeRows.forEach((item: { promotionId: number }) => {
                            let index = newSelectAccData.findIndex((ite: { promotionId: number }) => ite.promotionId === item.promotionId)
                            if (index === -1) {
                                newSelectAccData.push({ ...item })
                            }
                        })
                        setSelectedRows([...newSelectAccData])
                    } else {
                        let newSelectAccData = selectedRows.filter((item: { promotionId: number }) => {
                            let index = changeRows.findIndex((ite: { promotionId: number }) => ite.promotionId === item.promotionId)
                            if (index !== -1) {
                                return false
                            } else {
                                return true
                            }
                        })
                        setSelectedRows([...newSelectAccData])
                    }
                }
            }}
            config={columns12(dayHandle, () => { getPromotionDataTencentList.refresh() })}
            configName={'腾讯广告监控'}
        />

        {visible && <DayAd adName={adName} visible={visible} onClose={() => { setVisible(false); setPromotionId(undefined) }} queryForm={queryForm} promotionId={promotionId} />}
    </div>
}

export default TencentMonitor