import React, { useEffect, useState } from "react"
import { useAjax } from "@/Hook/useAjax"
import { getNovelDynamicListApi, GetNovelDynamicListProps, getNovelDynamicTotalApi } from "@/services/iaaData"
import TablePro from "@/components/TablePro"
import columns12 from "./tableConfig"
import moment from "moment"
import { useModel } from "umi"
import { Button, message, Modal, Space, Switch, Table } from "antd"
import { updateBatchDynamicCreativesInfoApi } from "@/services/gameData"
import { PauseCircleOutlined, PlayCircleOutlined } from "@ant-design/icons"
import DayAd from "./dayAd"
import QueryFormNovel from "@/components/QueryForm/queryFormNovel"

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

    /****************************************/
    const { initialState } = useModel('@@initialState');
    const [selectedRows, setSelectedRows] = useState<any[]>([])
    const [queryForm, setQueryForm] = useState<GetNovelDynamicListProps>({
        pageNum: 1,
        pageSize: 30,
        dataTimeMin: moment().format('YYYY-MM-DD'),
        dataTimeMax: moment().format('YYYY-MM-DD'),
    })
    const [totalData, setTotalData] = useState<any[]>([{ dynamicCreativeId: 1, accountId: '总计' }])
    const [visible, setVisible] = useState<boolean>(false)
    const [promotionId, setPromotionId] = useState<number>()
    const [dynamicCreativeId, setDynamicCreativeId] = 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 [isZj, setIsZj] = useState<boolean>(true)

    const updateBatchDynamicCreativesInfo = useAjax((params) => updateBatchDynamicCreativesInfoApi(params))
    const getDynamicList = useAjax((params) => getNovelDynamicListApi(params))
    const getDynamicTotal = useAjax((params) => getNovelDynamicTotalApi(params))
    /****************************************/

    useEffect(() => {
        if (initialState?.iaaApp?.length && initialState?.productType) {
            getDynamicList.run({ ...queryForm, appId: initialState.iaaApp, productType: initialState.productType })
            getDynamicTotal.run({ ...queryForm, appId: initialState.iaaApp, productType: initialState.productType }).then((res: { data: { dynamicCreativeId: number; accountId: string } }) => {
                if (res?.data) {
                    let data = res?.data
                    data.dynamicCreativeId = 1
                    data.accountId = '总计'
                    setTotalData([data])
                } else {
                    setTotalData([{ dynamicCreativeId: 1, accountId: '总计' }])
                }
            })
        }

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

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

    const dynamicHandle = (type: '删除' | '启动' | '暂停', data?: any) => {
        let accountAdgroupMaps = data ? [data.accountId + ',' + data.dynamicCreativeId] : [...new Set(selectedRows?.map(item => item.accountId + ',' + item.dynamicCreativeId))]
        let hide: any
        if (data) {
            hide = message.loading(`正在设置...`, 0, () => {
                message.success('设置成功');
            });
        }
        switch (type) {
            case '启动':
            case '暂停':
                updateBatchDynamicCreativesInfo.run({ accountAdgroupMaps, suspend: type === '暂停' }).then(res => {
                    if (res?.data?.failIdList?.length === 0) {
                        message.success(`修改操作完成！`)
                        getDynamicList.refresh()
                        setSelectedRows([])
                    } else {
                        setFailIdList(res?.data?.list || [])
                        setFailVisible(true)
                    }
                    if (hide) {
                        hide()
                    }
                })
                break
        }
    }


    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={updateBatchDynamicCreativesInfo.loading} icon={<PlayCircleOutlined />} disabled={selectedRows.length === 0} onClick={() => dynamicHandle('启动')}>启动</Button>
                <Button type='primary' size="small" style={{ background: '#e6a23c', borderColor: '#e6a23c' }} loading={updateBatchDynamicCreativesInfo.loading} icon={<PauseCircleOutlined />} disabled={selectedRows.length === 0} onClick={() => dynamicHandle('暂停')}>暂停</Button>
                <span style={{ color: 'red' }}>操作完数据结果延时5分钟之内，即时结果去腾讯后台查看</span>
            </Space>}
            leftChild={<QueryFormNovel
                initialValues={{ day3: [moment(), moment()] }}
                isPutUserId
                isDeleted
                isConfiguredStatus
                isDynamicCreativeName
                isDynamicCreativeId
                isDeliveryMode
                isAccountId
                isAdgroupName
                isAdgroupId
                day1={{ placeholder: ['创意创建时间开始', '创意创建时间结束'] }}
                day3={{ placeholder: ['消耗日期开始', '消耗日期结束'] }}
                isCostTotalMin
                isThousandDisplayPriceTotalMin
                isConversionsCountTotalMin
                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['createdTimeMin'] = moment(day1[0]).format('YYYY-MM-DD')
                        newQueryForm['createdTimeMax'] = moment(day1[1]).format('YYYY-MM-DD')
                    } else {
                        delete newQueryForm['createdTimeMin']
                        delete newQueryForm['createdTimeMax']
                    }

                    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']
                    }
                    setQueryForm({ ...newQueryForm, ...params })
                }}
            />}
            isZj={isZj}
            totalData={totalData}
            config={columns12(dayHandle, () => { getDynamicList.refresh() })}
            configName={configName || '腾讯小说创意列表'}
            fixed={{ left: 4, right: 2 }}
            scroll={{ x: 1000, y: 620 }}
            title='腾讯创意列表'
            rowKey={'dynamicCreativeId'}
            loading={getDynamicList.loading}
            ajax={getDynamicList}
            page={getDynamicList?.data?.data?.current || 1}
            pageSize={getDynamicList?.data?.data?.size || 20}
            total={getDynamicList?.data?.data?.total || 0}
            dataSource={getDynamicList?.data?.data?.records?.map((item: any) => ({ ...item, id: item.dynamicCreativeId }))}
            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.dynamicCreativeId),
                getCheckboxProps: (record: any) => ({
                    disabled: record.dynamicCreativeIsDeleted == 1 || record?.accountId === '总计'
                }),
                onSelect: (record: { dynamicCreativeId: number }, selected: boolean) => {
                    if (selected) {
                        selectedRows.push({ ...record })
                        setSelectedRows([...selectedRows])
                    } else {
                        let newSelectAccData = selectedRows.filter((item: { dynamicCreativeId: number }) => item.dynamicCreativeId !== record.dynamicCreativeId)
                        setSelectedRows([...newSelectAccData])
                    }
                },
                onSelectAll: (selected: boolean, selectedRowss: { dynamicCreativeId: number }[], changeRows: { dynamicCreativeId: number }[]) => {
                    if (selected) {
                        let newSelectAccData = [...selectedRows]
                        changeRows.forEach((item: { dynamicCreativeId: number }) => {
                            let index = newSelectAccData.findIndex((ite: { dynamicCreativeId: number }) => ite.dynamicCreativeId === item.dynamicCreativeId)
                            if (index === -1) {
                                newSelectAccData.push({ ...item })
                            }
                        })
                        setSelectedRows([...newSelectAccData])
                    } else {
                        let newSelectAccData = selectedRows.filter((item: { dynamicCreativeId: number }) => {
                            let index = changeRows.findIndex((ite: { dynamicCreativeId: number }) => ite.dynamicCreativeId === item.dynamicCreativeId)
                            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); setDynamicCreativeId(undefined) }}
            queryForm={queryForm}
            promotionId={promotionId}
            dynamicCreativeId={dynamicCreativeId}
        />}

        {failVisible && <Modal
            title={<strong>报错信息</strong>}
            open={failVisible}
            className='modalResetCss'
            width={650}
            onCancel={() => { setFailVisible(false); setFailIdList([]) }}
            footer={null}
        >
            <Table
                size="small"
                bordered
                rowKey={'adgroupId'}
                columns={[{
                    title: '广告ID',
                    dataIndex: 'adgroupId',
                    key: 'adgroupId',
                    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 DynamicNovel