import { useAjax } from "@/Hook/useAjax"
import { Button, Input, message, Modal, Space, Spin, Table } from "antd"
import React, { useEffect, useState } from "react"
import { Columns } from "./tableConfig"
import { delV3StrategyApi, getV3StrategyListApi } from "@/services/adqV3"
import { getAdqV3AdListApi } from "@/services/launchAdq/adqv3";
import '../../index.less'

interface Props {
    userId: number
    type: string,
    putInType?: 'NOVEL' | 'GAME'
    onChange?: (value: any) => void
}
/**
 * 使用策略组
 * @returns 
 */
const UserTactics: React.FC<Props> = ({ onChange, type, userId, putInType }) => {

    /***********************/
    const [visible, setVisible] = useState<boolean>(false)
    const [queryFormNew, setQueryFormNew] = useState<PULLIN.GetV3StrategyListProps>({ pageNum: 1, pageSize: 20, type })
    const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([])

    const getStrategy = useAjax((params) => getV3StrategyListApi(params))
    const delStrategy = useAjax((params) => delV3StrategyApi(params))
    const getAdqV3AdList = useAjax((params) => getAdqV3AdListApi(params), { formatResult: true })
    /***********************/

    useEffect(() => {
        if (visible) {
            getList()
        }
    }, [visible, queryFormNew, putInType])

    const getList = () => {
        getStrategy.run({ ...queryFormNew, taskType: putInType })
    }

    const use = () => {
        setVisible(true)
    }

    const handleOk = () => {
        if (selectedRowKeys.length > 0) {
            const hide = message.loading('正在检测广告是否被删除...', 0)
            let { strategyValue } = selectedRowKeys[0]
            let { adData } = JSON.parse(strategyValue)
            getAdqV3AdList.run({ pageNum: 1, pageSize: 100, useType: 1, userId, adgroupIdList: adData.map((item: { adgroupId: any; }) => item.adgroupId) }).then(res => {
                if (res?.data) {
                    if (res.data?.records?.every((item: { isDeleted: boolean }) => !item.isDeleted)) {
                        onChange?.(selectedRowKeys[0])
                    } else {
                        message.error('当前有广告给删除了')
                    }
                } else {
                    message.error('找不到广告，或者服务器异常')
                }
                hide()
            }).catch(() => hide())
        } else {
            message.error('请选择策略组')
        }
    }

    const del = (id: number) => {
        delStrategy.run(id).then(res => {
            message.success('删除成功')
            getStrategy.refresh()
        })
    }

    return <>
        <Button type='primary' onClick={use}>使用策略组</Button>
        {visible && <Modal
            title='使用策略组'
            open={visible}
            onCancel={() => { setVisible(false) }}
            onOk={handleOk}
            width={1200}
            confirmLoading={getAdqV3AdList.loading}
            className="modalResetCss"
        >
            <Space style={{ width: '100%' }} direction='vertical'>
                <Space>
                    <Input.Search enterButton allowClear placeholder="请输入商品名称" onSearch={(value) => setQueryFormNew({ ...queryFormNew, strategyKey: value, pageNum: 1 })} />
                    <span style={{ color: 'red' }}>请确保广告没有被删除</span>
                </Space>
                <Table
                    dataSource={getStrategy?.data?.records}
                    loading={getStrategy.loading}
                    columns={Columns(del)}
                    size="small"
                    bordered
                    rowKey={'id'}
                    scroll={{ x: 800 }}
                    rowSelection={{
                        type: 'radio',
                        onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
                            console.log(selectedRowKeys, selectedRows);
                            setSelectedRowKeys(selectedRows)
                        }
                    }}
                    pagination={{
                        total: getStrategy?.data?.total,
                        current: queryFormNew?.pageNum,
                        pageSize: queryFormNew?.pageSize
                    }}
                    onChange={(pagination) => {
                        const { current, pageSize } = pagination
                        setQueryFormNew({ ...queryFormNew, pageNum: current as number, pageSize: pageSize as number || 20 })
                    }}
                />
            </Space>
        </Modal>}
    </>
}


export default React.memo(UserTactics)