import { CloseOutlined, DownOutlined, FilterOutlined, SearchOutlined, UpOutlined } from "@ant-design/icons"
import { Button, DatePicker, Form, Input, InputNumber, Popover, Select, Space } from "antd"
import React, { forwardRef, useEffect, useImperativeHandle, useState } from "react"
import '../../launchSystemNew/adq/ad/index.less'
import moment from "moment"
import { useLocalStorageState, useTimeout } from "ahooks"
import { GetDynamicCreativeMonitorProps } from "@/services/adMonitor/adMonitor"
import { useModel } from "umi"
import { DELIVERY_MODE_ENUM } from "../tencentAdPutIn/const"
import { AdUnitType_Enum } from "@/pages/launchSystemNew/account/const"
const { RangePicker } = DatePicker;

type TypeProps = 'DatePicker' | 'Input' | 'InputNumber' | 'Select'
interface QueryProps {
    lable: string,
    name: string,
    type: TypeProps,
    value: (data?: { value?: any, onChange?: (value?: any) => void }) => JSX.Element,
    isValue?: boolean
}

interface Props {
    queryForm: GetDynamicCreativeMonitorProps,
    setQueryForm: React.Dispatch<React.SetStateAction<GetDynamicCreativeMonitorProps>>
    onChange?: (data: any) => void
    initialValues?: any
}
/**
 * 请求体 AD 合集
 * @returns 
 */
const FilterDynamicQuery = forwardRef(({ onChange, initialValues, queryForm, setQueryForm }: Props, ref) => {

    /********************************/
    const [form] = Form.useForm();
    const [visible, setVisible] = useState<boolean>(true)
    const [filterTrueList, setFilterTrueList] = useState<QueryProps[]>([])
    const [message, setMessage] = useLocalStorageState('filterQueryContentAdMessage3.0', '');
    const { getGroupList } = useModel('useLaunchAdq.useAdAuthorize')
    const { getPicherList } = useModel('useOperating.useWxGroupList')
    /********************************/

    useImperativeHandle(ref, () => ({
        onOpen(data: any) {
            setVisible(true)
            let { createdTimeMin, createdTimeMax, adgroupIds, ...params } = data
            if (createdTimeMin && createdTimeMax) {
                params.createdTime = [moment(createdTimeMin), moment(createdTimeMax)]
            }
            if (adgroupIds?.length) {
                params.adgroupIds.toSting()
            }
            form.setFieldsValue(params)
        },
    }));

    useTimeout(() => {
        setVisible(false);
    }, 1000);

    useEffect(() => {
        getPicherList.run()
    }, [])

    const queryList: QueryProps[] = [
        // {
        //     lable: '广告名称',
        //     name: 'adgroupName',
        //     type: 'Input',
        //     value: (params) => <Input placeholder="请输入广告名称" style={{ width: '100%' }} {...params} />
        // },
        {
            lable: '广告ID',
            name: 'adgroupIds',
            type: 'Input',
            value: (params) => <Input placeholder="请输入广告ID(多个,隔开)" style={{ width: '100%' }} {...params} />
        },
        {
            lable: '投放模式',
            name: 'deliveryMode',
            type: 'Select',
            value: (params) => <Select
                placeholder='投放模式'
                style={{ width: '100%', minWidth: 130 }}
                showSearch
                allowClear
                filterOption={(input: any, option: any) =>
                    (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                }
                mode="multiple"
                {...params}
            >
                <Select.Option value={'DELIVERY_MODE_CUSTOMIZE'}>自定义创意</Select.Option>
                <Select.Option value={'DELIVERY_MODE_COMPONENT'}>组件化创意</Select.Option>
            </Select>
        },
        {
            lable: '创意创建时间',
            name: 'createdTime',
            type: 'DatePicker',
            value: (params) => <RangePicker {...params} />
        },
        {
            lable: '广告账号',
            name: 'accountIdStr',
            type: 'Input',
            value: (params) => <Input placeholder="请输入广告账号(多个,隔开)" style={{ width: '100%' }} {...params} />
        },
        {
            lable: '业务单元类型',
            name: 'adUnitType',
            type: 'Select',
            value: (params) => <Select
                placeholder='业务单元类型'
                style={{ width: '100%', minWidth: 130 }}
                showSearch
                filterOption={(input: any, option: any) =>
                    (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                }
                allowClear
                {...params}
                options={Object.keys(AdUnitType_Enum).map(key => ({ label: AdUnitType_Enum[key as keyof typeof AdUnitType_Enum], value: key }))}
            />
        },
        {
            lable: '最小总消耗',
            name: 'costTotalMin',
            type: 'InputNumber',
            value: (params) => <InputNumber placeholder="请输入最小总消耗" style={{ width: '100%' }} {...params} />
        },
        {
            lable: '最低转化数',
            name: 'conversionsCountTotalMin',
            type: 'InputNumber',
            value: (params) => <InputNumber placeholder="请输入最低总转化数" style={{ width: '100%' }} {...params} />
        },

        {
            lable: '最低千次曝光成本',
            name: 'thousandDisplayPriceTotalMin',
            type: 'InputNumber',
            value: (params) => <InputNumber placeholder="请输入最低总千次曝光成本" style={{ width: '100%' }} {...params} />
        },
    ]

    useEffect(() => {
        setFiled(message)
    }, [message])

    const setFiled = (message?: string) => {
        if (message) {
            let newFiter: any = []
            message.split(',').forEach(key => {
                let data = queryList.find(item => item.name === key)
                if (data) {
                    newFiter.push(data)
                }
            })
            console.log('==========>', newFiter)
            setFilterTrueList(newFiter)
        } else {
            setFilterTrueList([])
        }
    }

    const onFinish = async () => {
        let newAllValue = await form.validateFields()
        if (newAllValue?.createdTime && newAllValue?.createdTime?.length > 0) {
            newAllValue.createdTimeMin = moment(newAllValue?.createdTime[0]).format('YYYY-MM-DD')
            newAllValue.createdTimeMax = moment(newAllValue?.createdTime[1]).format('YYYY-MM-DD')
            delete newAllValue?.createdTime
        }
        if (newAllValue?.adgroupIds) {
            newAllValue.adgroupIds = newAllValue.adgroupIds.split(',')
        }
        setQueryForm({ ...queryForm, pageNum: 1 })
        onChange?.(newAllValue)
    }

    return <div id="filterQueryContentDynamic">
        <div style={{ width: '100%', display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <Input
                placeholder="请输入广告名称"
                allowClear
                style={{ width: 140 }}
                value={queryForm?.adgroupName}
                onChange={(e) => setQueryForm({ ...queryForm, adgroupName: e.target.value })}
            />
            <Select
                showSearch
                maxTagCount={1}
                style={{ minWidth: 100 }}
                allowClear
                mode="multiple"
                placeholder="请选择投手"
                filterOption={(input, option) =>
                    (option?.children as any).toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
                value={queryForm.sysUserIds}
                onChange={(value) => setQueryForm({ ...queryForm, sysUserIds: value, pageNum: 1 })}
            >
                {getPicherList?.data?.map((item: { nickname: string, userId: number }, index: number) =>
                    <Select.Option
                        value={item.userId}
                        key={item.userId + '' + index}
                    >
                        {item.nickname}
                    </Select.Option>
                )}
            </Select>
            <Input
                placeholder="请输入创意名称"
                allowClear
                style={{ width: 140 }}
                value={queryForm?.dynamicCreativeName}
                onChange={(e) => setQueryForm({ ...queryForm, dynamicCreativeName: e.target.value })}
            />
            <Select
                placeholder='启用禁用状态'
                style={{ minWidth: 120 }}
                showSearch
                allowClear
                value={queryForm?.configuredStatus}
                filterOption={(input: any, option: any) =>
                    (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                }
                onChange={(e) => setQueryForm({ ...queryForm, configuredStatus: e })}
                mode="multiple"
            >
                <Select.Option value={'AD_STATUS_NORMAL'}>有效</Select.Option>
                <Select.Option value={'AD_STATUS_SUSPEND'}>暂停</Select.Option>
            </Select>
            <Select
                showSearch
                mode='multiple'
                maxTagCount={1}
                value={queryForm.groupAccountIds}
                style={{ minWidth: 130 }}
                allowClear
                placeholder="请选择账号分组"
                onChange={(value: number[]) => {
                    setQueryForm({ ...queryForm, groupAccountIds: value, pageNum: 1 })
                }}
            >
                {getGroupList?.data?.map((item: { groupId: number, groupName: number }) => <Select.Option
                    value={item.groupId}
                    key={item.groupId}
                >
                    {item.groupName}
                </Select.Option>)}
            </Select>
            <Input
                placeholder="请输入创意ID(多个,隔开)"
                style={{ width: 140 }}
                value={queryForm?.dynamicCreativeId ? queryForm?.dynamicCreativeId.join(',') : undefined}
                onChange={(e) => setQueryForm({
                    ...queryForm,
                    dynamicCreativeId: e.target.value ? e.target.value.split(',') : [],
                    pageNum: 1
                })}
            />
            <Select
                placeholder='已删除?'
                style={{ width: 90 }}
                showSearch
                allowClear
                filterOption={(input: any, option: any) =>
                    (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                }
                value={queryForm.isDeleted}
                onChange={(e) => {
                    setQueryForm({ ...queryForm, isDeleted: e, pageNum: 1 })
                }}
            >
                <Select.Option value={true}>是</Select.Option>
                <Select.Option value={false}>否</Select.Option>
            </Select>

            <RangePicker
                placeholder={['数据时间开始', '数据时间结束']}
                value={(queryForm?.dataTimeMin && queryForm?.dataTimeMax) ? [moment(queryForm.dataTimeMin), moment(queryForm.dataTimeMax)] : undefined as any}
                style={{ width: 260 }}
                onChange={(_, o) => {
                    setQueryForm({ ...queryForm, dataTimeMin: o[0], dataTimeMax: o[1], pageNum: 1 })
                }}
            />

            <Popover
                title={<Space direction="vertical" size={0}>
                    <h3 style={{ fontWeight: 'bold', marginBottom: 0 }}>你可能找这类创意</h3>
                </Space>}
                open={visible}
                trigger={'click'}
                placement="bottomLeft"
                onOpenChange={(e) => {
                    setVisible(e)
                    if (e) {
                        form.setFieldsValue(initialValues)
                    }
                }}
                getPopupContainer={() => document.getElementById('filterQueryContentDynamic') as any}
                content={<div style={{ width: 500, height: 400, overflowY: 'auto', padding: '10px 16px' }}>
                    <Form
                        name="FilterQueryDynamic3.0"
                        form={form}
                        colon={false}
                        layout="vertical"
                        onValuesChange={(changedValues) => {
                            console.log(changedValues)
                            let messageArr = message ? message?.split(',') : []
                            Object.keys(changedValues).forEach(key => {
                                if (!(messageArr?.includes(key))) {
                                    messageArr.push(key)
                                    setMessage(messageArr.join(','))
                                    // setFiled(messageArr.join(','))
                                }
                            })
                        }}
                        onFinish={onFinish}
                    >
                        {queryList.map(item => <Form.Item label={<strong>{item.lable}</strong>} name={item.name} key={item.name}>
                            {item.value()}
                        </Form.Item>)}
                    </Form>
                </div>}
            >
                <Button className="bt"><FilterOutlined />筛选 {visible ? <UpOutlined /> : <DownOutlined />}</Button>
            </Popover>
            <Button type="primary" onClick={onFinish} icon={<SearchOutlined />}>搜索</Button>
            <Button onClick={() => {
                form.resetFields();
                setQueryForm({ pageNum: 1, pageSize: 20, columns: [], isDeleted: false })
                onFinish()
            }}>重置</Button>
        </div>
        <div className="selectedFilterAd">
            {filterTrueList.map(item => {
                let value = form.getFieldValue([item.name])
                switch (item.name) {
                    case 'isDeleted':
                        value = typeof value === 'boolean' ? value ? '是' : '否' : '请选择'
                        break
                    case 'deliveryMode':
                        value = value?.length > 0 ? value.map((item: string) => DELIVERY_MODE_ENUM[item as keyof typeof DELIVERY_MODE_ENUM]).toString() : '请选择'
                        break
                    case 'adUnitType':
                        value = AdUnitType_Enum[value as keyof typeof AdUnitType_Enum] || '请选择'
                        break
                    case 'createdTime':
                        value = value ? '已经选择时间' : '请选择时间'
                        break
                    default:
                        value = value || '请输入'
                }
                return <Popover
                    placement="bottom"
                    trigger={'click'}
                    destroyTooltipOnHide={true}
                    content={<PopoverSetValue
                        type={item.type}
                        dataEntry={item.value}
                        value={form.getFieldValue([item.name])}
                        onChange={(value) => {
                            form.setFieldsValue({ [item.name]: value })
                            onFinish()
                        }}
                    />}
                    title={item.lable}
                    key={item.name}
                >
                    <div>
                        <div className="text">
                            {item.lable}：{value || '请选择'}
                        </div>
                        <DownOutlined style={{ fontSize: 10, marginRight: 6 }} />
                        <div className="close" onClick={() => {
                            form.setFieldsValue({ [item.name]: undefined })
                            let messageArr = message?.split(',') || []
                            messageArr = messageArr.filter(key => key !== item.name)
                            let messageStr = messageArr.length > 0 ? messageArr.join(',') : undefined
                            setMessage(messageStr)
                            // setFiled(messageStr)
                        }}><CloseOutlined /></div>
                    </div>
                </Popover>
            })}
        </div>
    </div>
})

export default React.memo(FilterDynamicQuery)

interface PopoverSetValueProps {
    type: TypeProps,
    dataEntry: (data?: { value?: any, onChange?: (value?: any) => void }) => JSX.Element,
    value?: any
    onChange?: (value?: any) => void
}
const PopoverSetValue: React.FC<PopoverSetValueProps> = ({ type, dataEntry, value, onChange }) => {

    /*************************/
    const [data, setData] = useState<any>()
    /*************************/

    useEffect(() => {
        setData(value)
    }, [value])

    return <Space>
        {dataEntry({
            value: data,
            onChange(value) {
                if (['Input'].includes(type)) {
                    setData(value.target.value)
                } else {
                    setData(value)
                }
            },
        })}
        <Button type="primary" onClick={() => {
            onChange?.(data)
        }}>确定</Button>
    </Space>
}