import { useAjax } from "@/Hook/useAjax";
import { PauseCircleOutlined, PlayCircleOutlined, QuestionCircleOutlined, TransactionOutlined } from "@ant-design/icons";
import { Button, Checkbox, Col, Input, Row, Select, Space, Tooltip, message } from "antd"
import React, { useCallback, useEffect, useState } from "react"
import { ADGROUP_STATUS } from "../const";
import { getAdqV3AdListApi, modifyStatusBatchApi, syncBatchApi } from "@/services/launchAdq/adqv3";
import tableConfig from "./tableConfig";
import { txAdConfig } from "../config";
import UpdateAd from "./updateAd";
import TableData from "@/pages/launchSystemNew/components/TableData";


const Ad: React.FC<ADQV3.AdProps> = ({ userId, creativeHandle }) => {

    /*****************************************/
    const [queryFrom, set_queryFrom] = useState<ADQV3.GetAdListProps>({ pageNum: 1, pageSize: 20, useType: 1 })
    const [isClearSelect, setIsClearSelect] = useState(true)
    const [selectedRows, setSelectedRows] = useState<any[]>([])
    const [update, setUpdate] = useState<{ visible: boolean }>({ visible: false })

    const syncBatch = useAjax((params) => syncBatchApi(params))
    const modifyStatusBatch = useAjax((params) => modifyStatusBatchApi(params))
    const getAdqV3AdList = useAjax((params) => getAdqV3AdListApi(params), { formatResult: true })
    /*****************************************/

    useEffect(() => {
        getList({ pageNum: 1, pageSize: 20, useType: 1 })
    }, [userId])

    // 获取列表
    const getList = useCallback((params: ADQV3.GetAdListProps) => {
        getAdqV3AdList.run({ ...params, userId })
    }, [userId, getAdqV3AdList])

    // 同步 
    const sync = useCallback(() => {
        if (selectedRows?.length > 0) {
            let accountAdgroupMaps = [...new Set(selectedRows?.map(item => item.accountId + ',' + item.adgroupId))]
            syncBatch.run({ accountAdgroupMaps }).then(res => {
                res && getAdqV3AdList.refresh()
                res ? message.success('同步成功！') : message.error('同步失败！')
            })
        } else {
            message.error('请勾选')
        }

    }, [getAdqV3AdList, selectedRows])

    // 批量启停
    const adStatus = (type: boolean) => {
        let newSelectedRows = []
        if (type) {
            newSelectedRows = selectedRows.filter((item: { configuredStatus: string, adgroupId: number }) => item.configuredStatus === 'AD_STATUS_SUSPEND')
        } else {
            newSelectedRows = selectedRows.filter((item: { configuredStatus: string, adgroupId: number }) => item.configuredStatus === 'AD_STATUS_NORMAL')
        }
        if (newSelectedRows.length === 0) {
            message.warn(`所有广告都是${type ? '启动' : '暂停'}状态,无需${type ? '启动' : '暂停'}操作`)
            return
        }
        let accountAdgroupMaps = [...new Set(newSelectedRows?.map(item => item.accountId + ',' + item.adgroupId))]
        modifyStatusBatch.run({ accountAdgroupMaps, suspend: type }).then(res => {
            message.success(`${type ? '启动' : '暂停'}成功`)
            getAdqV3AdList.refresh()
            setSelectedRows([])
        })
    }


    return <div>
        <Row gutter={[6, 6]} align='middle' style={{ marginBottom: 15 }}>
            <Col>
                <Select
                    placeholder='应用类型'
                    style={{ width: 90 }}
                    showSearch
                    filterOption={(input: any, option: any) =>
                        (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                    }
                    value={queryFrom.useType}
                    onChange={(value: any) => {
                        set_queryFrom({ ...queryFrom, useType: value })
                    }}
                >
                    <Select.Option value={1}>小说</Select.Option>
                    <Select.Option value={2}>游戏</Select.Option>
                </Select>
            </Col>
            <Col>
                <Input
                    placeholder='广告账号(多个,分割)'
                    allowClear
                    style={{ width: 160 }}
                    onChange={(e) => {
                        let value = e.target.value
                        let arr: any = []
                        if (value) {
                            value = value.replace(/[,，\s]/g, ',')
                            arr = value.split(',').filter((a: any) => a)
                        }
                        set_queryFrom({ ...queryFrom, accountIdList: arr })
                    }}
                />
            </Col>
            <Col>
                <Input
                    placeholder='广告ID(多个,分割)'
                    allowClear
                    style={{ width: 150 }}
                    onChange={(e) => {
                        let value = e.target.value
                        let arr: any = []
                        if (value) {
                            value = value.replace(/[,，\s]/g, ',')
                            arr = value.split(',').filter((a: any) => a)
                        }
                        set_queryFrom({ ...queryFrom, adgroupIdList: arr })
                    }}
                />
            </Col>
            <Col>
                <Select
                    placeholder='广告状态'
                    mode="multiple"
                    style={{ minWidth: 120 }}
                    showSearch
                    filterOption={(input: any, option: any) =>
                        (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                    }
                    allowClear
                    onChange={(value: any) => {
                        set_queryFrom({ ...queryFrom, systemStatusList: value })
                    }}
                >
                    {Object.keys(ADGROUP_STATUS).map(key => {
                        return <Select.Option value={key} key={key}>{ADGROUP_STATUS[key]}</Select.Option>
                    })}
                </Select>
            </Col>
            <Col>
                <Input
                    placeholder='广告名称'
                    allowClear
                    style={{ width: 120 }}
                    onChange={(e) => {
                        let value = e.target.value
                        set_queryFrom({ ...queryFrom, adgroupName: value })
                    }}
                />
            </Col>
            <Col>
                <Input
                    placeholder='腾讯备注'
                    allowClear
                    style={{ width: 120 }}
                    onChange={(e) => {
                        let value = e.target.value
                        let arr: any = []
                        if (value) {
                            value = value.replace(/[,，\s]/g, ',')
                            arr = value.split(',').filter((a: any) => a)
                        }
                        set_queryFrom({ ...queryFrom, accountMemo: arr })
                    }}
                />
            </Col>
            <Col>
                <Input
                    placeholder='本地备注'
                    allowClear
                    style={{ width: 120 }}
                    onChange={(e) => {
                        let value = e.target.value
                        let arr: any = []
                        if (value) {
                            value = value.replace(/[,，\s]/g, ',')
                            arr = value.split(',').filter((a: any) => a)
                        }
                        set_queryFrom({ ...queryFrom, accountRemark: arr })
                    }}
                />
            </Col>
            <Col>
                <Space>
                    <Button
                        type="primary"
                        onClick={() => {
                            if (isClearSelect) {
                                setSelectedRows([])
                            }
                            getList({ ...queryFrom, pageNum: 1 })
                        }}
                    >
                        <Space>
                            <span>搜索</span>
                            <Checkbox className='clearCheckbox' onClick={(e) => e.stopPropagation()} checked={isClearSelect} onChange={(e) => setIsClearSelect(e.target.checked)} />
                            <Tooltip title="勾选搜索清空已选">
                                <QuestionCircleOutlined />
                            </Tooltip>
                        </Space>
                    </Button>

                    {selectedRows?.length > 0 && <Button type='link' style={{ padding: 0, color: 'red' }} onClick={() => {
                        setSelectedRows([])
                    }}>清空已选（{selectedRows?.length}）</Button>}
                </Space>
            </Col>
        </Row>
        <TableData
            isCard={false}
            columns={() => tableConfig(() => getAdqV3AdList.refresh(), creativeHandle)}
            ajax={getAdqV3AdList}
            syncAjax={sync}
            fixed={{ left: 2, right: 5 }}
            dataSource={getAdqV3AdList?.data?.data?.records}
            loading={getAdqV3AdList?.loading || syncBatch?.loading}
            scroll={{ y: 560 }}
            total={getAdqV3AdList?.data?.data?.total}
            page={getAdqV3AdList?.data?.data?.current}
            pageSize={getAdqV3AdList?.data?.data?.size}
            myKey={'adgroupId'}
            gutter={[0, 10]}
            config={txAdConfig}
            configName="腾讯广告3.0"
            leftChild={<Space direction='vertical'>
                <Row gutter={[10, 10]} align='middle'>
                    <Col><Button type='primary' style={{ background: '#67c23a', borderColor: '#67c23a' }} loading={modifyStatusBatch.loading} icon={<PlayCircleOutlined />} disabled={selectedRows.length === 0} onClick={() => adStatus(true)}>启动</Button></Col>
                    <Col><Button type='primary' style={{ background: '#e6a23c', borderColor: '#e6a23c' }} loading={modifyStatusBatch.loading} icon={<PauseCircleOutlined />} disabled={selectedRows.length === 0} onClick={() => adStatus(false)}>暂停</Button></Col>
                    <Col><Button type='primary' icon={<TransactionOutlined />} disabled={selectedRows.length === 0} onClick={() => setUpdate({ visible: true })}>修改出价</Button></Col>
                </Row>
            </Space>}
            rowSelection={{
                selectedRowKeys: selectedRows.map(item => item.adgroupId.toString()),
                getCheckboxProps: (record: any) => ({
                    disabled: record.isDeleted
                }),
                onSelect: (record: { adgroupId: number, mpName: string }, selected: boolean) => {
                    if (selected) {
                        selectedRows.push({ ...record })
                        setSelectedRows([...selectedRows])
                    } else {
                        let newSelectAccData = selectedRows.filter((item: { adgroupId: number }) => item.adgroupId !== record.adgroupId)
                        setSelectedRows([...newSelectAccData])
                    }
                },
                onSelectAll: (selected: boolean, selectedRowss: { adgroupId: number }[], changeRows: { adgroupId: number }[]) => {
                    if (selected) {
                        let newSelectAccData = [...selectedRows]
                        changeRows.forEach((item: { adgroupId: number }) => {
                            let index = newSelectAccData.findIndex((ite: { adgroupId: number }) => ite.adgroupId === item.adgroupId)
                            if (index === -1) {
                                newSelectAccData.push({ ...item })
                            }
                        })
                        setSelectedRows([...newSelectAccData])
                    } else {
                        let newSelectAccData = selectedRows.filter((item: { adgroupId: number }) => {
                            let index = changeRows.findIndex((ite: { adgroupId: number }) => ite.adgroupId === item.adgroupId)
                            if (index !== -1) {
                                return false
                            } else {
                                return true
                            }
                        })
                        setSelectedRows([...newSelectAccData])
                    }
                }
            }}
            onChange={(props: any) => {
                let { pagination } = props
                let { current, pageSize } = pagination
                set_queryFrom({ ...queryFrom, pageNum: current, pageSize })
                getList({ ...queryFrom, pageNum: current, pageSize })
            }}
        />

        {/* 修改广告 */}
        {update.visible && <UpdateAd
            {...update}
            selectedRows={selectedRows}
            onChange={() => {
                setUpdate({ visible: false })
                getAdqV3AdList.refresh()
                setSelectedRows([])
            }}
            onClose={() => { setUpdate({ visible: false }) }}
        />}
    </div>
}


export default React.memo(Ad)