import QueryForm from "@/components/QueryForm";
import TablePro from "@/components/TablePro";
import { Button, message, Modal, Space, Table } from "antd";
import React, { useEffect, useState } from "react"
import { useModel } from "umi";
import moment from "moment";
import { getByteAdListApi, GetByteAdListProps, getByteAdTotalApi } from "@/services/iaaData";
import { useAjax } from "@/Hook/useAjax";
import columns12 from "./tableConfig";
import { PauseCircleOutlined, PlayCircleOutlined } from "@ant-design/icons";
import DayAd from "./dayAd";
import { newEditTTAdgroupsDataApi } from "@/services/gameData";


/**
 * 头条广告列表
 * @returns 
 */
const AdList: React.FC = () => {
    /****************************************/
    const { initialState } = useModel('@@initialState');
    const [selectedRows, setSelectedRows] = useState<any[]>([])
    const [queryForm, setQueryForm] = useState<GetByteAdListProps>({
        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 [failIdList, setFailIdList] = useState<{ adgroupId: number, code: number, message: string, messageCn: string }[]>([])
    const [failVisible, setFailVisible] = useState<boolean>(false)

    // const editAdqAdgroupsData = useAjax((params) => newEditAdqAdgroupsDataApi(params))
    const getByteAdList = useAjax((params) => getByteAdListApi(params))
    const getByteAdTotal = useAjax((params) => getByteAdTotalApi(params))
    const newEditTTAdgroupsData = useAjax((params) => newEditTTAdgroupsDataApi(params))
    /****************************************/

    useEffect(() => {
        if (initialState?.iaaApp?.length && initialState?.productType) {
            getByteAdList.run({ ...queryForm, appId: initialState.iaaApp, productType: initialState.productType })
            getByteAdTotal.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: '总计' }])
                }
            })
        }

    }, [queryForm, initialState?.iaaApp, initialState?.productType])

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

    // 批量启停
    const adStatus = (type: 'play' | 'suspend') => {
        let params: any = {}
        params.suspend = type === 'play' ? false : true
        params.adgroupIds = selectedRows.map(item => item.accountId + ',' + item.adId)
        if (params.adgroupIds.length === 0) {
            message.warn(`所以账号都是${type === 'play' ? '启动' : '暂停'}状态,无需${type === 'play' ? '启动' : '暂停'}操作`)
            return
        }
        let hide =  message.loading(`正在设置...`, 0, () => {
            message.success('设置成功');
        });
        newEditTTAdgroupsData.run(params).then((res: any) => {
            if (res?.failIdList?.length === 0) {
                message.success(`操作完成！`)
                getByteAdList.refresh()
                setSelectedRows([])
            } else {
                setFailIdList(res?.list || [])
                setFailVisible(true)
            }
            hide()
        })
    }

    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={newEditTTAdgroupsData.loading} icon={<PlayCircleOutlined />} disabled={selectedRows.length === 0} onClick={() => adStatus('play')}>启动</Button>
                <Button type='primary' size="small" style={{ background: '#e6a23c', borderColor: '#e6a23c' }} loading={newEditTTAdgroupsData.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
                isTTPricing
                isTTStatus
                isPromotionId
                day1={{ placeholder: ['广告创建日期开始', '广告创建日期结束'] }}
                day2={{ placeholder: ['投放日期开始', '投放日期结束'] }}
                day3={{ placeholder: ['消耗日期开始', '消耗日期结束'] }}
                onChange={(data: any) => {
                    console.log(data)
                    const { promotionId, promotionName, day1, day2, day3, ...params } = data
                    let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                    newQueryForm.adId = promotionId
                    newQueryForm.adName = promotionName
                    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)}
            configName={'头条广告列表'}
            fixed={{ left: 4, right: 2 }}
            scroll={{ x: 1000, y: 620 }}
            title='头条广告列表'
            loading={getByteAdList.loading}
            ajax={getByteAdList}
            page={getByteAdList?.data?.data?.current || 1}
            pageSize={getByteAdList?.data?.data?.size || 20}
            total={getByteAdList?.data?.data?.total || 0}
            dataSource={getByteAdList?.data?.data?.records?.map((item: any, index: number) => ({ ...item, id: item.adId.toString(16) }))}
            rowKey={'id'}
            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.id),
                getCheckboxProps: (record: any) => ({
                    disabled: record.adStatus === 'PROJECT_STATUS_DELETE' || record?.accountId === '总计'
                }),
                onSelect: (record: { adId: string }, selected: boolean) => {
                    if (selected) {
                        selectedRows.push({ ...record })
                        setSelectedRows([...selectedRows])
                    } else {
                        let newSelectAccData = selectedRows.filter((item: { adId: string }) => item.adId !== record.adId)
                        setSelectedRows([...newSelectAccData])
                    }
                },
                onSelectAll: (selected: boolean, selectedRowss: { adId: number }[], changeRows: { adId: number }[]) => {
                    if (selected) {
                        let newSelectAccData = [...selectedRows]
                        changeRows.forEach((item: { adId: number }) => {
                            let index = newSelectAccData.findIndex((ite: { adId: number }) => ite.adId === item.adId)
                            if (index === -1) {
                                newSelectAccData.push({ ...item })
                            }
                        })
                        setSelectedRows([...newSelectAccData])
                    } else {
                        let newSelectAccData = selectedRows.filter((item: { adId: number }) => {
                            let index = changeRows.findIndex((ite: { adId: number }) => ite.adId === item.adId)
                            if (index !== -1) {
                                return false
                            } else {
                                return true
                            }
                        })
                        setSelectedRows([...newSelectAccData])
                    }
                }
            }}
        />

        {visible && <DayAd appId={initialState?.iaaApp as number[]} productType={initialState?.productType as string} adName={adName} visible={visible} onClose={() => { setVisible(false); setPromotionId(undefined) }} queryForm={queryForm} promotionId={promotionId} />}
        {failVisible && <Modal
            title={<strong>报错信息</strong>}
            open={failVisible}
            className='modalResetCss'
            width={650}
            onCancel={() => { setFailVisible(false); setFailIdList([]) }}
            footer={null}
        >
            <Table
                size="small"
                bordered
                rowKey={'creativeId'}
                columns={[{
                    title: '创意ID',
                    dataIndex: 'creativeId',
                    key: 'creativeId',
                    width: 110,
                    render: (value) => <span style={{ fontSize: 12 }}>{value}</span>,
                }, {
                    title: 'code',
                    dataIndex: 'code',
                    key: 'code',
                    width: 70,
                    align: 'center',
                    render: (value) => <span style={{ fontSize: 12 }}>{value}</span>,
                }, {
                    title: '错误信息',
                    dataIndex: 'messageCn',
                    key: 'messageCn',
                    render: (value) => <span style={{ fontSize: 12 }}>{value}</span>,
                }]}
                dataSource={failIdList}
            />
        </Modal>}
    </div>
}

export default AdList