import * as React from 'react';
import { Form, Select, Button } from 'antd';
import { apis } from '@/apis';
import { Query } from '../types';
import LocalStorage from '@/LocalStorage';

const FormItem = Form.Item;
const { Option } = Select;

interface Props {
    onClickSearch: (query: Query) => Promise<any>,
    onClickReset: (query: Query) => Promise<any>,
};

const Search: React.FC<Props> = (props: Props) => {
    const {
        onClickSearch,
        onClickReset
    } = props;

    const [form] = Form.useForm();

    type ApplicationList = {
        label: string,
        value: string,
    }[];

    const [applicationList, setApplicationList] = React.useState<ApplicationList>([]);

    const fetchApplicationList = async () => {
        try {
            const userInfo = LocalStorage.getUserInfo();
            const userId = (userInfo?.id ?? '').toString();
            const res = await apis.fetchTakaiApplicationList(userId);
            const list = res.data.map((item: any) => {
                return {
                    label: item.name,
                    value: item.appId,
                }
            });
            setApplicationList(list);
        } catch (error: any) {
            console.error(error);
        }
    }

    const init = async () => {
        await fetchApplicationList();
    };

    React.useEffect(() => {
        init();
    }, []);

    // 点击查询
    const handleClickSearch = async () => {
        const values = form.getFieldsValue();
        await onClickSearch(values);
    };

    // 点击重置
    const handleClickReset = async () => {
        form.resetFields();
        const values = form.getFieldsValue();
        await onClickReset(values);
    };

    return (
        <Form form={form} layout='inline' colon={false}>
            <FormItem label='应用' name='appId'>
                <Select
                    style={{ width: 200 }}
                    placeholder='全部'
                    allowClear={true}
                >
                    {
                        applicationList.map((item, index) => {
                            return <Option value={item.value} key={index}>
                                {item.label}
                            </Option>
                        })
                    }
                </Select>
            </FormItem>
            <FormItem>
                <Button
                    style={{ marginRight: 16 }}
                    type='primary'
                    onClick={handleClickSearch}
                >
                    查询
                </Button>
                <Button onClick={handleClickReset}>
                    重置
                </Button>
            </FormItem>
        </Form>
    );
};

export default Search;