import { useAjax } from "@/Hook/useAjax"
import { PromotedObjectType } from "@/services/launchAdq/enum"
import { delStrategyApi, getStrategyApi } from "@/services/launchAdq/localAd"
import { Button, Input, message, Modal, Select, Space, Table } from "antd"
import React, { useEffect, useState } from "react"
import { Columns } from "./tableConfig"
import moment from "moment"


interface Props {
    setQueryForm: any
    setAccountCreateLogs: any,
    setLaunchMode: any
}
/**
 * 使用策略组
 * @returns 
 */
const UserTactics: React.FC<Props> = ({ setQueryForm: setQuery, setAccountCreateLogs, setLaunchMode }) => {

    /***********************/
    const [visible, setVisible] = useState<boolean>(false)
    const [queryForm, setQueryForm] = useState<{ promotedObjectType?: string, strategyKey?: string }>({})
    const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([])
    const [loading, setLoading] = useState<boolean>(false)

    const getStrategy = useAjax((params) => getStrategyApi(params))
    const delStrategy = useAjax((params) => delStrategyApi(params))
    /***********************/

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

    const getList = () => {
        getStrategy.run(queryForm)
    }

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

    const handleOk = () => {
        if (selectedRowKeys.length > 0) {
            const hide = message.loading('设置中。。。', 0)
            setLoading(true)
            setTimeout(() => {
                const { queryForm, accountCreateLogs, launchMode } = JSON.parse(selectedRowKeys[0].strategyValue)
                setLaunchMode(launchMode)
                if (queryForm?.sysAdgroup) {
                    if (queryForm?.sysAdgroup?.beginDate && moment(queryForm?.sysAdgroup?.beginDate) < moment()) {
                        queryForm.sysAdgroup.beginDate = moment().format('YYYY-MM-DD')
                        message.warning('请注意，检测投放开始日期小于今天，已自动改成今天，如需修改，请重新设置')
                    }
                    if (queryForm?.sysAdgroup?.endDate && moment(queryForm?.sysAdgroup?.endDate) < moment()) {
                        queryForm.sysAdgroup.endDate = moment().format('YYYY-MM-DD')
                        message.warning('请注意，检测投放结束日期小于今天，已自动改成今天，如需修改，请重新设置')
                    }
                }
                setQuery({ ...queryForm })
                setAccountCreateLogs(accountCreateLogs)
                message.success('设置成功')
                setSelectedRowKeys([])
                hide()
                setLoading(false)
                setVisible(false)
            }, 1500)
        } 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={800}
            confirmLoading={loading}
        >
            <Space style={{ width: '100%' }} direction='vertical'>
                <Space>
                    <Input allowClear placeholder="策略组名称" value={queryForm?.strategyKey} onChange={(e) => { setQueryForm({ ...queryForm, strategyKey: e.target.value }) }} />
                    <Select
                        style={{ width: 150 }}
                        allowClear
                        value={queryForm?.promotedObjectType}
                        placeholder="请选择推广目标"
                        showSearch
                        filterOption={(input: any, option: any) =>
                            (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                        }
                        onChange={(e) => { setQueryForm({ ...queryForm, promotedObjectType: e }) }}
                    >
                        {Object.keys(PromotedObjectType).map(key => {
                            return <Select.Option value={key} key={key}>{PromotedObjectType[key]}</Select.Option>
                        })}
                    </Select>
                </Space>
                <Table
                    dataSource={getStrategy?.data}
                    loading={getStrategy.loading}
                    columns={Columns(del)}
                    size="small"
                    bordered
                    rowKey={'id'}
                    rowSelection={{
                        type: 'radio',
                        onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
                            console.log(selectedRowKeys, selectedRows);
                            setSelectedRowKeys(selectedRows)
                        }
                    }}
                />
            </Space>
        </Modal>}
    </>
}


export default React.memo(UserTactics)