import { IReactOption, IReactOptionsComponent } from '@wowpic/xform-types';
import { Select as AntdSelect } from 'antd';
import React, { FunctionComponent } from 'react';
import { covertOptionGroup } from '../utils';

const Select: FunctionComponent<IReactOptionsComponent> = props => {
    const { options: originalOptions, showSearch, mode } = props;
    const newProps = { ...props };
    let newOptions = [...originalOptions];

    // 是否带搜索框, 如果没有指定，默认对内嵌内容进行搜索
    if (showSearch) {
        const { optionFilterProp, filterOption } = props;
        if (!optionFilterProp) {
            newProps.optionFilterProp = 'children';
        }
        if (!filterOption) {
            newProps.filterOption = (input: string, option: any) =>
                String(option.props[props.optionFilterProp])
                    .toLowerCase()
                    .indexOf(input.toLowerCase()) >= 0;
        }
    }

    // 如果mode是tag select option的value必须为string类型
    if (mode === 'tags') {
        newOptions = originalOptions.map(item => {
            const { value, ...other } = item;
            if (typeof value === 'string') {
                return item;
            }
            return {
                value: value.toString(),
                ...other
            };
        });
    }

    // 对optipns按group进行分组
    const groups = covertOptionGroup(newOptions);

    return (
        <AntdSelect
            getPopupContainer={triggerNode => triggerNode.parentNode}
            style={{ minWidth: '70px' }}
            {...newProps}>
            {groups.map(({ groupLabel, options }) => {
                if (groupLabel === 'noGroup') {
                    return options.map(
                        (option: IReactOption, index: number) => {
                            const { label } = option;
                            return (
                                <AntdSelect.Option
                                    key={groupLabel + index}
                                    {...option}>
                                    {label}
                                </AntdSelect.Option>
                            );
                        }
                    );
                }
                const children = options.map(
                    (option: IReactOption, index: number) => {
                        const { label } = option;
                        return (
                            <AntdSelect.Option
                                key={groupLabel + index}
                                {...option}>
                                {label}
                            </AntdSelect.Option>
                        );
                    }
                );
                return (
                    <AntdSelect.OptGroup key={groupLabel} label={groupLabel}>
                        {children}
                    </AntdSelect.OptGroup>
                );
            })}
        </AntdSelect>
    );
};

export default Select;
