import { UpOutlined, DownOutlined } from '@ant-design/icons';
import { IFieldGroup, IReactFieldGroupProps } from '@wowpic/xform-types';
import React, { FunctionComponent, useCallback, useEffect, useState } from 'react';
import Switcher from './switcher';
import { Card, Form, Button, Tooltip } from 'antd';

const FieldGroup: FunctionComponent<IReactFieldGroupProps> = ({
    core,
    field
}) => {
    const [state, setState] = useState<IFieldGroup>(field);
    const { ui, props } = state;
    const { labelCol, wrapperCol, collapse: _collapse } = props;

    const [collapse, setCollapse] = useState<boolean>(_collapse || false);

    // 实际上 field 地址不会发生改变，即使从返回值里拿也没用，所以手动生成一个新对象来进行更新
    const setField = useCallback(() => setState({ ...field }), [field]);

    // 因为 field 地址不会改变，变的只是 state，所以以下事件监听只会触发一次
    useEffect(() => {
        field.on('CHILDREN_CHANGE', setField);
        field.on('VALID_CHANGE', setField);

        return () => {
            field.removeListener('CHILDREN_CHANGE', setField);
            field.removeListener('VALID_CHANGE', setField);
        };
    }, [field, setField]);

    const { children } = state;

    return (
        <Form.Item {...ui} {...(ui?.label ? { label: <Tooltip title={`${ui.label}(${field.key})`} placement="left">{ui.label}</Tooltip> } : null)}>
            <Card className={`x-card ${collapse ? 'collapse' : ''}`} title={(
                <div className="x-card-title">
                    <div>
                        {ui.label}
                    </div>
                </div>
            )}
                extra={
                    <Button
                        shape="circle"
                        icon={collapse ? <DownOutlined /> : <UpOutlined />}
                        onClick={() => setCollapse(!collapse)} />
                }
            >
                <Switcher core={core} fields={children.map(field => {
                    field.ui = {
                        labelCol: labelCol || { span: 4 },
                        wrapperCol: wrapperCol || { span: 18 },
                        ...field.ui
                    };
                    return field;
                })} />
            </Card>
        </Form.Item>
    );
};

export default FieldGroup;
