import { getDynamicCreativeMonitorListApi, GetDynamicCreativeMonitorProps } from "@/services/adMonitor/adMonitor"
import { Button, Card, Col, message, Row, Space } from "antd"
import moment from "moment"
import FilterDynamicQuery from "./FilterDynamicQuery"
import React, { useEffect, useRef, useState } from "react"
import { dynamicConfig } from "./config"
import { useAjax } from "@/Hook/useAjax"
import TableData from "@/pages/launchSystemNew/components/TableData"
import tableDynamicConfig from "./tableDynamicConfig"
import { PauseCircleOutlined, PlayCircleOutlined } from "@ant-design/icons"
import { updateBatchDynamicCreativesInfoApi } from "@/services/launchAdq/adqv3"
import SaveSearch from "./SaveSearch"

const configName = '创意列表3.0'

/**
 * 创意数据
 * @returns 
 */
const TabDynamic: React.FC = () => {

    /***********************************/
    const ref = useRef(null)
    const [queryForm, setQueryForm] = useState<GetDynamicCreativeMonitorProps>({ pageNum: 1, pageSize: 20, columns: [], isDeleted: false, dataTimeMin: moment().subtract(7, 'days').format('YYYY-MM-DD'), dataTimeMax: moment().format('YYYY-MM-DD') })
    const [filterForm, setFilterForm] = useState<GetDynamicCreativeMonitorProps>()
    const [selectedRows, setSelectedRows] = useState<any[]>([])

    const getDynamicCreativeMonitorList = useAjax((params) => getDynamicCreativeMonitorListApi(params), { formatResult: true })
    const updateBatchDynamicCreativesInfo = useAjax((params) => updateBatchDynamicCreativesInfoApi(params))
    /***********************************/

    useEffect(() => {
        getList()
    }, [filterForm, queryForm])

    const getList = () => {
        let message = localStorage.getItem(`myAdMonitorConfig1.0.1_${configName}`)
        if (message) {
            message = JSON.parse(message)
        }
        let columns: string[] = []
        if (message && Array.isArray(message)) {
            message.forEach((item: { serverIndex: any; dataIndex: string; }) => {
                if (!['cz'].includes(item.dataIndex) && item?.serverIndex) {
                    columns.push(item?.serverIndex)
                }
            })
        } else {
            dynamicConfig.forEach((item: any) => {
                item?.data?.forEach((d: { default: any, serverIndex: string, dataIndex: string }) => {
                    if (d.default && !['cz'].includes(d.dataIndex) && d?.serverIndex) {
                        columns.push(d?.serverIndex)
                    }
                })
            })
        }
        let params: any = { ...queryForm, ...filterForm, columns }
        if (Object.keys(queryForm).includes('isDeleted') && typeof queryForm.isDeleted === 'boolean') {
            params.isDeleted = [params.isDeleted]
        }
        getDynamicCreativeMonitorList.run(params)
    }

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

    return <Card>
        <Row gutter={[6, 6]} align='middle' style={{ marginBottom: 10 }}>
            <FilterDynamicQuery
                queryForm={queryForm}
                setQueryForm={setQueryForm}
                onChange={(value) => {
                    setFilterForm({ ...value })
                }}
                ref={ref}
            />
        </Row>
        <div className='expandClassname'>
            <TableData
                refreshData={getList}
                isCard={false}
                className='expendTable'
                columns={() => tableDynamicConfig((data, type) => dynamicHandle(type, data))}
                ajax={getDynamicCreativeMonitorList}
                fixed={{ left: 2, right: 2 }}
                dataSource={getDynamicCreativeMonitorList?.data?.data?.records}
                loading={getDynamicCreativeMonitorList?.loading}
                scroll={{ y: 560 }}
                total={getDynamicCreativeMonitorList?.data?.data?.total}
                page={getDynamicCreativeMonitorList?.data?.data?.current}
                pageSize={getDynamicCreativeMonitorList?.data?.data?.size}
                myKey={'dynamic_creative_id'}
                gutter={[0, 10]}
                config={dynamicConfig}
                configName={configName}
                rowClassName={(record) => {
                    if (record?.tag_value === 100) {
                        return 'row_error'
                    } else if (record?.tag_value === 90) {
                        return 'row_warning'
                    } else {
                        return ''
                    }
                }}
                leftChild={<Space direction='vertical'>
                    <Row gutter={[10, 10]} align='middle'>
                        <Col><Button type='primary' style={{ background: '#67c23a', borderColor: '#67c23a' }} loading={updateBatchDynamicCreativesInfo.loading} icon={<PlayCircleOutlined />} disabled={selectedRows.length === 0} onClick={() => dynamicHandle('启动')}>启动</Button></Col>
                        <Col><Button type='primary' style={{ background: '#e6a23c', borderColor: '#e6a23c' }} loading={updateBatchDynamicCreativesInfo.loading} icon={<PauseCircleOutlined />} disabled={selectedRows.length === 0} onClick={() => dynamicHandle('暂停')}>暂停</Button></Col>
                        <Col><SaveSearch
                            type='DYNAMIC_SEARCH'
                            strategyValue={JSON.stringify({
                                queryForm,
                                filterForm
                            })}
                            onChange={(value) => {
                                let { queryForm, filterForm } = JSON.parse(value)
                                setQueryForm(data => ({ ...queryForm, pageNum: data.pageNum, pageSize: data.pageSize }))
                                setFilterForm(filterForm);
                                (ref.current as any)?.onOpen(filterForm)
                            }}
                        /></Col>
                    </Row>
                </Space>}
                rowSelection={{
                    selectedRowKeys: selectedRows.map(item => item.dynamic_creative_id.toString()),
                    getCheckboxProps: (record: any) => ({
                        disabled: record.status === 'STATUS_DELETED'
                    }),
                    onSelect: (record: { dynamic_creative_id: number, mpName: string }, selected: boolean) => {
                        if (selected) {
                            selectedRows.push({ ...record })
                            setSelectedRows([...selectedRows])
                        } else {
                            let newSelectAccData = selectedRows.filter((item: { dynamic_creative_id: number }) => item.dynamic_creative_id !== record.dynamic_creative_id)
                            setSelectedRows([...newSelectAccData])
                        }
                    },
                    onSelectAll: (selected: boolean, selectedRowss: { dynamic_creative_id: number }[], changeRows: { dynamic_creative_id: number }[]) => {
                        if (selected) {
                            let newSelectAccData = [...selectedRows]
                            changeRows.forEach((item: { dynamic_creative_id: number }) => {
                                let index = newSelectAccData.findIndex((ite: { dynamic_creative_id: number }) => ite.dynamic_creative_id === item.dynamic_creative_id)
                                if (index === -1) {
                                    newSelectAccData.push({ ...item })
                                }
                            })
                            setSelectedRows([...newSelectAccData])
                        } else {
                            let newSelectAccData = selectedRows.filter((item: { dynamic_creative_id: number }) => {
                                let index = changeRows.findIndex((ite: { dynamic_creative_id: number }) => ite.dynamic_creative_id === item.dynamic_creative_id)
                                if (index !== -1) {
                                    return false
                                } else {
                                    return true
                                }
                            })
                            setSelectedRows([...newSelectAccData])
                        }
                    }
                }}
                onChange={(props: any) => {
                    let { sortData, pagination } = props
                    let { current, pageSize } = pagination
                    let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                    newQueryForm.pageNum = current
                    newQueryForm.pageSize = pageSize
                    if (sortData && JSON.stringify('sortData') !== '{}') {
                        let { field, order } = sortData   // descend 降序 大到小  ascend 升序 小到大
                        if (order) {
                            newQueryForm.sortColumn = field
                            newQueryForm.sortAsc = order === 'ascend'
                        } else {
                            Object.keys(newQueryForm).forEach(key => {
                                if (key === 'sortColumn' || key === 'sortAsc') {
                                    delete newQueryForm[key]
                                }
                            })
                        }
                    } else {
                        Object.keys(newQueryForm).forEach(key => {
                            if (key === 'sortField' || key === 'sort') {
                                delete newQueryForm[key]
                            }
                        })
                    }
                    setQueryForm({ ...newQueryForm })
                }}
            />
        </div>
    </Card>
}

export default TabDynamic