import { Checkbox, Divider, Select, Space } from "antd";
import { DefaultOptionType } from "antd/es/select";
import React, { useEffect, useState } from "react";

interface Props {
    corpList: DefaultOptionType[],
    value?: string[],
    onChange?: (e: string[]) => void;
}

const SelectCorp: React.FC<Props> = ({ corpList, value, onChange }) => {

    const [oldFiltered, setOldFiltered] = useState<DefaultOptionType[]>([]);
    const [filtered, setFiltered] = useState<DefaultOptionType[]>([]);

    useEffect(() => {
        setOldFiltered(corpList);
        setFiltered(corpList);
    }, [corpList]);

    const handleSearch = (val) => {
        const f = oldFiltered.filter((item) => {
            const inputStr = val.replace(/[,，\s]/g, ',');
            if (inputStr && inputStr.includes(',')) {
                const inputList = inputStr.split(',').filter((it) => it).map(i => i.toLowerCase());
                return inputList.includes(((item?.label ?? '') as string).toLowerCase())
            }
            return ((item?.label ?? '') as string).toLowerCase().includes(val.toLowerCase())
        });
        setFiltered(f);
    };


    return <Select
        value={value}
        onChange={(e) => onChange?.(e as string[])}
        showSearch
        style={{ minWidth: 200 }}
        maxTagCount={1}
        mode='multiple'
        placeholder="选择企业"
        filterOption={false}
        onSearch={handleSearch}
        allowClear
        options={filtered}
        popupRender={(menu) => (
            <>
                {menu}
                <Divider style={{ margin: '8px 0' }} />
                <Space style={{ padding: '0 8px 4px' }}>
                    <Checkbox onChange={(e) => {
                        if (e.target.checked) {
                            onChange?.(filtered.map(item => item.value) as string[])
                        } else {
                            onChange?.([])
                        }
                    }}>全选</Checkbox>
                </Space>
            </>
        )}
    />
}

export default React.memo(SelectCorp);