import { CloseOutlined, DownOutlined, FilterOutlined, SearchOutlined, UpOutlined } from "@ant-design/icons"
import { Button, DatePicker, Form, Input, InputNumber, Popover, Select, Space } from "antd"
import React, { useEffect, useState } from "react"
import './index.less'
import moment from "moment"
import { useLocalStorageState, useTimeout } from "ahooks"
import { AdStatusEnum, OptimizationGoalEnum, PromotedObjectType } from "@/services/launchAdq/enum"
import { AdListProps } from "@/services/adMonitor/adMonitor"
import { useModel } from "umi"
// import { useModel } from "umi"

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

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

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

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

    const queryList: QueryProps[] = [
        {
            lable: '广告创建时间',
            name: 'adCreateTime',
            type: 'DatePicker',
            value: (params) => <DatePicker.RangePicker {...params} />
        },
        {
            lable: '投放时间',
            name: 'putDate',
            type: 'DatePicker',
            value: (params) => <DatePicker.RangePicker {...params} />
        },
        // {
        //     lable: '投手',
        //     name: 'sysUserIds',
        //     type: 'Select',
        //     value: (params) => <Select
        //         showSearch
        //         style={{ width: '100%', minWidth: 130 }}
        //         allowClear
        //         mode="multiple"
        //         placeholder="请选择投手"
        //         filterOption={(input, option) =>
        //             (option?.children as any).toLowerCase().indexOf(input.toLowerCase()) >= 0
        //         }
        //         {...params}
        //     >
        //         {getPicherList?.data?.map((item: { nickname: string, userId: number }, index: number) =>
        //             <Select.Option
        //                 value={item.userId}
        //                 key={item.userId + '' + index}
        //             >
        //                 {item.nickname}
        //             </Select.Option>
        //         )}
        //     </Select>
        // },
        {
            lable: '广告账号',
            name: 'accountIdStr',
            type: 'Input',
            value: (params) => <Input placeholder="请输入广告账号(多个,隔开)" style={{ width: '100%' }} {...params} />
        },
        // {
        //     lable: '广告名称',
        //     name: 'adgroupName',
        //     type: 'Input',
        //     value: (params) => <Input placeholder="请输入广告名称" style={{ width: '100%' }} {...params} />
        // },
        // {
        //     lable: '广告ID',
        //     name: 'adgroupIdStr',
        //     type: 'Input',
        //     value: (params) => <Input placeholder="请输入广告ID(多个,隔开)" style={{ width: '100%' }} {...params} />
        // },
        {
            lable: '推广目标名称',
            name: 'promotedObjectName',
            type: 'Input',
            value: (params) => <Input placeholder="请输入推广目标名称" style={{ width: '100%' }} {...params} />
        },
        {
            lable: '腾讯账号备注',
            name: 'accountMemo',
            type: 'Input',
            value: (params) => <Input placeholder="请输入腾讯账号备注" style={{ width: '100%' }} {...params} />
        },
        {
            lable: '本地账号备注',
            name: 'accountRemark',
            type: 'Input',
            value: (params) => <Input placeholder="请输入本地账号备注" style={{ width: '100%' }} {...params} />
        },
        // {
        //     lable: '推广目标',
        //     name: 'promotedObjectType',
        //     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}
        //     >
        //         {Object.keys(PromotedObjectType).map(key => {
        //             return <Select.Option value={key} key={key}>{PromotedObjectType[key]}</Select.Option>
        //         })}
        //     </Select>
        // },
        {
            lable: '优化目标',
            name: 'optimizationGoal',
            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())
                }
                {...params}
            >
                {Object.keys(OptimizationGoalEnum).map(key => <Select.Option value={key} key={key}>{OptimizationGoalEnum[key as keyof typeof OptimizationGoalEnum]}</Select.Option>)}
            </Select>
        },
        {
            lable: '是否深度优化',
            name: 'isDeepConversionSpec',
            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())
                }
                {...params}
            >
                <Select.Option value={true}>是</Select.Option>
                <Select.Option value={false}>否</Select.Option>
            </Select>
        },
        // {
        //     lable: '已删除?',
        //     name: 'isDeleted',
        //     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())
        //         }
        //         {...params}
        //     >
        //         <Select.Option value={true}>是</Select.Option>
        //         <Select.Option value={false}>否</Select.Option>
        //     </Select>
        // },
        // {
        //     lable: '广告状态',
        //     name: 'status',
        //     type: 'Select',
        //     value: (params) => <Select
        //         placeholder='广告状态'
        //         mode="multiple"
        //         style={{ width: '100%', minWidth: 130 }}
        //         showSearch
        //         filterOption={(input: any, option: any) =>
        //             (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
        //         }
        //         allowClear
        //         {...params}
        //     >
        //         {Object.keys(AdStatusEnum).map(key => {
        //             return <Select.Option value={key} key={key}>{AdStatusEnum[key]}</Select.Option>
        //         })}
        //     </Select>
        // },
        // {
        //     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: 'thousandDisplayPriceDayMin',
        //     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?.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
        }
        if (newAllValue?.putDate && newAllValue?.putDate?.length > 0) {
            newAllValue.putDateBegin = moment(newAllValue?.putDate[0]).format('YYYY-MM-DD')
            newAllValue.putDateEnd = moment(newAllValue?.putDate[1]).format('YYYY-MM-DD')
            delete newAllValue?.putDate
        }
        setQueryForm({ ...queryForm, pageNum: 1 })
        onChange?.(newAllValue)
    }

    return <div id="filterQueryContentAd">
        <div style={{ width: '100%', display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <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?.adgroupName}
                onChange={(e) => setQueryForm({ ...queryForm, adgroupName: e.target.value })}
            />
            <Select
                placeholder='广告状态'
                mode="multiple"
                maxTagCount={1}
                style={{ minWidth: 130 }}
                showSearch
                filterOption={(input: any, option: any) =>
                    (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                }
                allowClear
                value={queryForm.status}
                onChange={(e) => {
                    setQueryForm({ ...queryForm, status: e, pageNum: 1 })
                }}
            >
                {Object.keys(AdStatusEnum).map(key => {
                    return <Select.Option value={key} key={key}>{AdStatusEnum[key as keyof typeof AdStatusEnum]}</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.adgroupIdStr} onChange={(e) => setQueryForm({ ...queryForm, adgroupIdStr: e.target.value, 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>
            <Select
                placeholder='推广目标'
                style={{ minWidth: 130 }}
                showSearch
                filterOption={(input: any, option: any) =>
                    (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                }
                allowClear
                value={queryForm.promotedObjectType}
                onChange={(e) => {
                    setQueryForm({ ...queryForm, promotedObjectType: e, pageNum: 1 })
                }}
            >
                {Object.keys(PromotedObjectType).map(key => {
                    return <Select.Option value={key} key={key}>{PromotedObjectType[key as keyof typeof PromotedObjectType]}</Select.Option>
                })}
            </Select>

            <DatePicker.RangePicker
                placeholder={['数据时间筛选(起始)', '数据时间筛选(结束)']}
                value={(queryForm?.dataTimeMin && queryForm?.dataTimeMax) ? [moment(queryForm.dataTimeMin), moment(queryForm.dataTimeMax)] : undefined as any}
                style={{ width: 320 }}
                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)}
                getPopupContainer={() => document.getElementById('filterQueryContentAd') as any}
                content={<div style={{ width: 500, height: 400, overflowY: 'auto', padding: '10px 16px' }}>
                    <Form
                        name="FilterQueryAd"
                        form={form}
                        colon={false}
                        layout="vertical"
                        initialValues={initialValues}
                        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])
                // 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 'status':
                        value = AdStatusEnum[value as keyof typeof AdStatusEnum]
                        break
                    case 'isDeleted':
                        value = typeof value === 'boolean' ? value ? '是' : '否' : '请选择'
                        break
                    case 'isDeepConversionSpec':
                        value = typeof value === 'boolean' ? value ? '是' : '否' : '请选择'
                        break
                    case 'optimizationGoal':
                        value = OptimizationGoalEnum[value as keyof typeof OptimizationGoalEnum] || '请选择'
                        break
                    case 'promotedObjectType':
                        value = PromotedObjectType[value as keyof typeof PromotedObjectType] || '请选择'
                        break
                    case 'adCreateTime': case 'putDate':
                        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(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>
}