import React, { useEffect, useState } from "react"
import { useAjax } from "@/Hook/useAjax"
import { getGDTListApi, GetGDTListProps, getGDTTotalApi } from "@/services/iaaData"
import TablePro from "@/components/TablePro"
import columns12 from "./tableConfig"
import QueryForm from "@/components/QueryForm"
import moment from "moment"
import { useModel } from "umi"
import { Button, message, notification, Space } from "antd"
import { newEditAdqAdgroupsDataApi } from "@/services/gameData"
import { PauseCircleOutlined, PlayCircleOutlined } from "@ant-design/icons"
import DayAd from "./dayAd"

/**
 * 腾讯广告列表
 * @returns 
 */
const TencentIaaAd: React.FC = () => {

    /****************************************/
    const { initialState } = useModel('@@initialState');
    const [selectedRows, setSelectedRows] = useState<any[]>([])
    const [queryForm, setQueryForm] = useState<GetGDTListProps>({
        pageNum: 1,
        pageSize: 30,
        costDayBegin: moment().format('YYYY-MM-DD'),
        costDayEnd: 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 editAdqAdgroupsData = useAjax((params) => newEditAdqAdgroupsDataApi(params))
    const getGDTList = useAjax((params) => getGDTListApi(params))
    const getGDTTotal = useAjax((params) => getGDTTotalApi(params))
    /****************************************/

    useEffect(() => {
        if (initialState?.iaaApp) {
            const [appId, productType] = initialState.iaaApp.split('||')
            getGDTList.run({ ...queryForm, appId, productType })
            getGDTTotal.run({ ...queryForm, appId, 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: '总计' }])
                }
            })
        }

    }, [queryForm, initialState?.iaaApp])

    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
                });
            }
            getGDTList.refresh()
            setSelectedRows([])
        })
    }


    return <div>
        <TablePro
            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={{ day3: [moment(), moment()] }}
                isAccountId
                isPromotionName
                isPutUserIdList
                isCpaBid
                isDeleted
                isPricing
                isStatus
                isPromotionId
                day1={{ placeholder: ['广告创建日期开始', '广告创建日期结束'] }}
                day2={{ placeholder: ['投放日期开始', '投放日期结束'] }}
                day3={{ placeholder: ['消耗日期开始', '消耗日期结束'] }}
                onChange={(data: any) => {
                    console.log(data)
                    const { day1, day2, day3, ...params } = data
                    let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                    newQueryForm.pageNum = 1
                    if (day1 && day1?.length === 2) {
                        newQueryForm['adCreateBegin'] = moment(day1[0]).format('YYYY-MM-DD')
                        newQueryForm['adCreateEnd'] = moment(day1[1]).format('YYYY-MM-DD')
                    } else {
                        delete newQueryForm['adCreateBegin']
                        delete newQueryForm['adCreateEnd']
                    }

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

                    if (day3 && day3?.length === 2) {
                        newQueryForm['costDayBegin'] = moment(day3[0]).format('YYYY-MM-DD')
                        newQueryForm['costDayEnd'] = moment(day3[1]).format('YYYY-MM-DD')
                    } else {
                        delete newQueryForm['costDayBegin']
                        delete newQueryForm['costDayEnd']
                    }
                    setQueryForm({ ...newQueryForm, ...params })
                }}
            />}
            isZj
            totalData={totalData}
            config={columns12(dayHandle, () => { getGDTList.refresh() })}
            configName={'腾讯广告列表'}
            fixed={{ left: 4, right: 2 }}
            scroll={{ x: 1000, y: 620 }}
            title='腾讯广告列表(游戏)'
            loading={getGDTList.loading}
            ajax={getGDTList}
            page={getGDTList?.data?.data?.current || 1}
            pageSize={getGDTList?.data?.data?.size || 20}
            total={getGDTList?.data?.data?.total || 0}
            dataSource={getGDTList?.data?.data?.records?.map((item: any) => ({ ...item, id: item.promotionId }))}
            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.promotionId + ''),
                getCheckboxProps: (record: any) => ({
                    disabled: record.status === 'STATUS_DELETED' || record?.accountId === '总计'
                }),
                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])
                    }
                }
            }}
        />

        {visible && <DayAd iaaApp={initialState?.iaaApp as string} adName={adName} visible={visible} onClose={() => { setVisible(false); setPromotionId(undefined) }} queryForm={queryForm} promotionId={promotionId} />}
    </div>
}

export default TencentIaaAd