import React, { forwardRef, useEffect, useImperativeHandle } from "react"
import { SearchOutlined, SyncOutlined } from "@ant-design/icons";
import './global.less'
import { Button, Card, Checkbox, DatePicker, Form, Input, Radio, Select, Space } from "antd";
import { useEventListener } from "ahooks";
import { observer, useLocalObservable } from "mobx-react";
import globaStores from "@/store"

// let DatePickers: any = DatePicker
// const { RangePicker }: { RangePicker: any } = DatePickers;
const {RangePicker} = DatePicker
interface PublicConfig {
    name: string,
    label?: string,
    placeholder?: string,
    allowClear?: boolean
}

// 选择
interface SelectConfig extends PublicConfig {
    type: 'select',
    data: {
        label: any,
        value: any
    }[],
    mode?: "multiple" | "tags" | undefined
    showSearch?: boolean
}

// 输入框
interface InputConfig extends PublicConfig {
    type: 'input',
}

// 多选框
interface CheckboxConfig {
    type: 'checkbox',
    name: string,
    label?: string,
    checkboxName?: string
}
// 单日期选择
interface DatePickerConfig extends PublicConfig {
    type: "datePicker",
    disabledDate?: any // 禁用不可选择日期
    format?: string// 展示的日期格式
    picker?: 'date' | 'week' | 'month' | 'quarter' | 'year'
}
// 双日期选择
interface RangePickerConfig {
    type: 'rangePicker',
    name: string,
    label?: string,
    allowClear?: boolean
    placeholder?: [string, string],
    disabledDate?: any // 禁用不可选择日期
    format?: string// 展示的日期格式
}
// 单选框选择
interface RadioGroupConfig {
    type: 'radioGroup',
    name: string,
    isButton?: boolean,
    label?: string,
    data: {
        label: any,
        value: any,
        disabled?: boolean
    }[],
    buttonStyle?: 'outline' | 'solid'
}

export type ConfigProps = Array<SelectConfig | InputConfig | CheckboxConfig | RangePickerConfig | DatePickerConfig | RadioGroupConfig>

interface Props {
    onChange?: (data?: any) => void  // 返回字段
    children?: JSX.Element,          // 按钮组件
    config?: ConfigProps,            // 搜索配置
    initialValues?: any,             // 默认值
    onData?: (data: any) => void
}


const TopRightBtn = forwardRef((props: Props, ref: any) => {
    const { onChange, children, config = [], initialValues = {}, onData } = props

    /** -----变量开始----- */
    const { globaStore } = useLocalObservable(() => ({ globaStore: globaStores }))
    const { data: { isFullscreen } } = globaStore
    const [form] = Form.useForm()
    const isParentClassify = Form.useWatch('isParentClassify', form);
    /** -----变量结束----- */

    //映射ref方法
    // useImperativeHandle(ref, () => ({ isParentClassify }))
    useEffect(() => {
        onData && onData({ isParentClassify })
    }, [isParentClassify])

    useEventListener('keydown', (ev: any) => {
        if (ev.code === 'NumpadEnter') {
            onSearch()
        }
    });

    // 点击搜索
    const onSearch = async () => {
        form.submit()
        let data = await form.validateFields()
        onChange && onChange(data)
    }
    // 重置
    const reset = () => {
        form.resetFields();
        onSearch()
    }

    return <>
        {!isFullscreen && <Card hoverable>
            <Form layout="inline" className='queryForm' name="basic" form={form} initialValues={initialValues}>
                {config?.map((item: SelectConfig | InputConfig | CheckboxConfig | RangePickerConfig | DatePickerConfig | RadioGroupConfig, index: number) => {
                    switch (item.type) {
                        case 'select':
                            return <Form.Item label={item.label || ''} name={item.name} key={'select' + index}>
                                <Select
                                    // open={true}
                                    maxTagCount={1}
                                    mode={item?.mode}
                                    showSearch
                                    style={{ minWidth: 150 }}
                                    allowClear={item?.allowClear || true}
                                    placeholder={item.placeholder || '请选择'}
                                    filterOption={(input, option) =>
                                        (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                >
                                    {item.data?.map((item1: { label: any, value: any }, ind: number) => <Select.Option value={item1.label} key={item1.value + item1.label + ind}>{item1.value}</Select.Option>)}
                                </Select>
                            </Form.Item>
                        case 'checkbox':
                            return <Form.Item label={item.label || ''} valuePropName="checked" name={item.name} key={'checkbox' + index}>
                                <Checkbox>{item?.checkboxName}</Checkbox>
                            </Form.Item>
                        case 'input':
                            return <Form.Item label={item.label || ''} name={item.name} key={'input' + index}>
                                <Input placeholder={item.placeholder || '请输入'} allowClear={item?.allowClear || true} style={{ width: 150 }} />
                            </Form.Item>
                        case 'datePicker':
                            return <Form.Item label={item.label || ''} name={item.name} key={'datePicker' + index}>
                                <DatePicker placeholder={item?.placeholder} picker={item?.picker} format={item?.format} disabledDate={item?.disabledDate} allowClear={item?.allowClear || true} />
                            </Form.Item>
                        case 'rangePicker':
                            return <Form.Item label={item.label || ''} name={item.name} key={'rangePicker' + index}>
                                <RangePicker style={{ width: 225 }} placeholder={item?.placeholder} format={item?.format} disabledDate={item?.disabledDate} allowClear={item?.allowClear || true} />
                            </Form.Item>
                        case 'radioGroup':
                            return <Form.Item label={item.label || ''} name={item.name} key={'radioGroup' + index}>
                                <Radio.Group buttonStyle={item?.buttonStyle}>
                                    {item?.data?.map((item1: { label: any, value: any, disabled?: boolean }, ind: number) => {
                                        if (item?.isButton) {
                                            return <Radio.Button value={item1.label} disabled={item1?.disabled} key={item1.value + item1.label + ind}>{item1.value}</Radio.Button>
                                        } else {
                                            return <Radio value={item1.label} disabled={item1?.disabled} key={item1.value + item1.label + ind}>{item1.value}</Radio>
                                        }
                                    })}
                                </Radio.Group>
                            </Form.Item>
                        default:
                            return null
                    }
                })}

                <Form.Item>
                    <Space>
                        <Button type="primary" icon={<SearchOutlined />} onClick={onSearch}>搜索</Button>
                        <Button icon={<SyncOutlined />} onClick={reset}>重置</Button>
                    </Space>
                </Form.Item>
            </Form>
            {children && <div className="topRightBtn" style={{ marginTop: 10 }}>
                <div>{children}</div>
            </div>}
        </Card>}
    </>
})

export default React.memo(observer(TopRightBtn))