import { CloseOutlined, DownOutlined, FilterOutlined, SearchOutlined, UpOutlined } from "@ant-design/icons"
import { Button, DatePicker, Form, Input, InputNumber, Popover, Space } from "antd"
import React, { useEffect, useState } from "react"
import './filterQuery.less'
import moment from "moment"
import { useLocalStorageState, useTimeout } from "ahooks"

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 {
    onChange?: (data: any) => void
}
/**
 * 请求体 合集
 * @returns 
 */
const FilterQuery: React.FC<Props> = ({ onChange }) => {

    const [queryForm, setQueryForm] = useState<any>({})

    const queryList: QueryProps[] = [
        {
            lable: '广告创建时间',
            name: 'adCreateTime',
            type: 'DatePicker',
            value: (params) => <DatePicker.RangePicker {...params} />
        },
        {
            lable: '最低今日转化数',
            name: 'conversionsCountDayMin',
            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: 'costDayMin',
            type: 'InputNumber',
            value: (params) => <InputNumber placeholder="请输入最低今日消耗" style={{ width: '100%' }} {...params} />
        },
        {
            lable: '最小总消耗',
            name: 'costTotalMin',
            type: 'InputNumber',
            value: (params) => <InputNumber placeholder="请输入最小总消耗" style={{ width: '100%' }} {...params} />
        },
        {
            lable: '推广目标名称',
            name: 'promotedObjectName',
            type: 'Input',
            value: (params) => <Input placeholder="请输入推广目标名称" style={{ width: '100%' }} {...params} />
        },
        {
            lable: '推广目标类型',
            name: 'promotedObjectType',
            type: 'Input',
            value: (params) => <Input placeholder="请输入推广目标类型" style={{ width: '100%' }} {...params} />
        },
        {
            lable: '最低今日千次曝光成本',
            name: 'thousandDisplayPriceDayMin',
            type: 'InputNumber',
            value: (params) => <InputNumber placeholder="请输入最低今日千次曝光成本" style={{ width: '100%' }} {...params} />
        },
        {
            lable: '最低总千次曝光成本',
            name: 'thousandDisplayPriceTotalMin',
            type: 'InputNumber',
            value: (params) => <InputNumber placeholder="请输入最低总千次曝光成本" style={{ width: '100%' }} {...params} />
        },
    ]

    /********************************/
    const [form] = Form.useForm();
    const [visible, setVisible] = useState<boolean>(true)
    const [filterTrueList, setFilterTrueList] = useState<QueryProps[]>([])
    const [message, setMessage] = useLocalStorageState('filterQueryContentDayMessage', '');
    /********************************/

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

    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?.adCreateTime && newAllValue?.adCreateTime?.length > 0) {
            newAllValue.adCreateTimeMin = moment(newAllValue?.adCreateTime[0]).format('YYYY-MM-DD')
            newAllValue.adCreateTimeMax = moment(newAllValue?.adCreateTime[1]).format('YYYY-MM-DD')
            delete newAllValue?.adCreateTime
        }
        onChange?.({ ...newAllValue, ...queryForm })
    }

    return <div id="filterQueryContent">
        <div style={{ width: '100%', display: 'flex', gap: 8 }}>
            <Input
                placeholder="请输入广告名称"
                allowClear
                value={queryForm?.adgroupName}
                onChange={(e) => setQueryForm({ ...queryForm, adgroupName: e.target.value })}
            />
            <Popover
                open={visible}
                content={<div style={{ width: 500, height: 400, overflowY: 'auto', padding: '10px 16px' }}>
                    <Form
                        name="FilterQuery"
                        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>}
                title={<Space direction="vertical" size={0}>
                    <h3 style={{ fontWeight: 'bold', marginBottom: 0 }}>你可能找这类广告</h3>
                </Space>}
                trigger={'hover'}
                placement="bottomLeft"
                onOpenChange={(e) => setVisible(e)}
                getPopupContainer={() => document.getElementById('filterQueryContent') as any}
            >
                <Button><FilterOutlined />筛选 {visible ? <UpOutlined /> : <DownOutlined />}</Button>
            </Popover>
            <Button type="primary" onClick={onFinish} icon={<SearchOutlined />}>搜索</Button>
            <Button onClick={() => {
                form.resetFields();
                setQueryForm({})
            }}>重置</Button>
        </div>
        {filterTrueList.length > 0 && <div className="selectedFilter">
            {filterTrueList.map(item => {
                let value = form.getFieldValue([item.name])
                // if (item.type === 'DatePicker' && value && value?.length > 0) {
                //     console.log(value, Array.isArray(value))
                //     let start = new Date()
                //     // let end = moment(value(1)).format('YYYY-MM-DD')
                //     // value = start + '-' + end
                // }
                switch (item.name) {
                    case 'adCreateTime':
                        value = value ? '已经选择时间' : '请选择时间'
                        break
                    default:
                        value = value || '请输入'
                        break
                }
                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(FilterQuery)

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>
}