import { Button } from 'antd';
import React, { useRef } from 'react';
import { XForm } from '../packages/react/src/index';
import { ISchema } from '../packages/types/src/index';

const schema: ISchema = [
    {
        key: 'select1',
        type: 'Select',
        ui: {
            label: 'options为string情况'
        },
        options: '/options1'
    },
    {
        key: 'select2',
        type: 'Select',
        ui: {
            label: 'options为array情况'
        },
        options: [
            {
                name: '选项1',
                value: '值1'
            },
            {
                name: '选项2',
                value: '值2'
            }
        ]
    },
    {
        key: 'select3',
        type: 'Select',
        ui: {
            label: 'options为function情况'
        },
        options: {
            action: (_field, _form) => {
                return new Promise((resolve) => {
                    setTimeout(() => {
                        resolve([
                            {
                                name: '选项1',
                                value: '值1'
                            },
                            {
                                name: '选项2',
                                value: '值2'
                            }
                        ]);
                    }, 5000);
                });

            },
            watch: [ 'select2' ]
        }
    },
    {
        key: 'select4',
        type: 'Select',
        ui: {
            label: 'options为object情况'
        },
        options: {
            action: '/options2?type=${select2.value}',
            nameProperty: 'label',
            valueProperty: 'value',
            path: 'data.list',
            watch: [ 'select2' ],
            defaultIndex: 0,
        }
    }
];

export default function() {
    const formRef = useRef(null);

    const onSubmit = () => {
        formRef.current.submit().then((data: any) => {
            console.log(data);
        });
    };

    const onReset = () => {
        formRef.current.reset();
    };

    const onEmpty = () => {
        formRef.current.empty();
    };

    return (
        <>
            <XForm
                ref={formRef}
                schema={schema}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 12 }}
            />
            <div style={{display: 'flex', justifyContent: 'center'}}>
                <Button type="primary" onClick={onSubmit}>提交</Button>
                <Button style={{ marginLeft: '10px' }} onClick={onReset}>重置</Button>
                <Button style={{ marginLeft: '10px' }} onClick={onEmpty}>清空</Button>
            </div>
        </>
    );
}