import React from 'react';
import { Spin, Icon, Select } from 'antd';
import lodash from 'lodash';
import s from './index.less';

interface Props {
    initDataType?: undefined | 'onfocus'; //初始化请求方式
    updateId?: any;
    request?: Function;
    selfCom?: any;
    dataSource?: object[];
    onChange: Function;
    value?: any;
    fieldNames?: {
        value: any;
        label: string;
        key: any;
    };
}

class AssociationSearch extends React.Component<Props> {
    constructor(props: Props) {
        super(props);
        this.fetchData = lodash.debounce(this.fetchData, 400);
    }

    state = {
        value: undefined,
        data: [],
        fetching: false,
        fieldNames: this.props.fieldNames || { label: 'label', value: 'value' },
        initData: [],
        searchStr: '',
    };

    componentDidMount() {
        const value = this.formaterValue(this.props.value);
        this.setState({ value: value || undefined });
        !this.props.initDataType && this.fetchData('', true);
    }

    componentWillReceiveProps = (nextProps: any) => {
        if (JSON.stringify(nextProps.value) !== JSON.stringify(this.props.value)) {
            const vas = nextProps.value || undefined;
            let data = this.state.data;
            if (vas === undefined || vas === null) {
                data = this.state.initData;
            } else if (typeof vas === 'object') {
                if (!vas.label || !vas.label.length) {
                    data = this.state.initData;
                }
            }
            this.setState({ value: this.formaterValue(vas), data });
            this.addValueOptions(vas);
        }
        if (JSON.stringify(nextProps.updateId) !== JSON.stringify(this.props.updateId)) {
            nextProps.updateId !== undefined && this.fetchData('', false, nextProps.updateId);
        }
    };
    fetchData = async (val: string, isDefault = false, id = undefined) => {
        let data = [];
        if (this.props.request) {
            this.setState({ fetching: true });
            const response = await this.props.request(val, id);
            if (response && response.data && response.success) {
                const _data = Array.isArray(response.data) ? response.data : response.data.list;
                data = Array.isArray(_data) ? _data : [];
                data = this.formaterData(data);
                if (isDefault) {
                    this.setState({ initData: data.slice() });
                }
            }
        } else {
            data = Array.isArray(this.props.dataSource) ? this.props.dataSource : [];
            data = this.formaterData(data);
        }
        this.setState({ data, fetching: false });
        // this.addValueOptions(this.props.value);
    };
    onSearch = (val: string) => {
        this.setState({ searchStr: val });
        if (val.length >= 2) {
            this.fetchData(val);
        } else {
            this.setState({
                data: this.state.initData,
            });
        }
    };
    onFocus = () => {
        if (this.props.initDataType === 'onfocus') {
            this.fetchData(this.state.searchStr, true);
        }
    };
    onBlur = () => {
        this.setState({ searchStr: '' });
    };
    formaterData = (data: any) => {
        if (this.props.fieldNames) {
            const { value, label } = this.props.fieldNames;
            return data.map((item: any) => ({
                ...item,
                value: typeof value === 'function' ? value(item) : item[value],
                label: item[label],
            }));
        } else return data;
    };
    formaterValue = (item: any) => {
        if (!item) return item;
        if (this.props.fieldNames && item) {
            const { value, label } = this.props.fieldNames;
            if (Array.isArray(item)) {
                return item.map((ls: any) => ({
                    value: ls.value || ls.value === 0 ? ls.value : ls[value],
                    key: ls.value || ls.value === 0 ? ls.value : ls[value],
                    label: ls.label || ls[label],
                }));
            } else {
                return {
                    value: item.value || item.value === 0 ? item.value : item[value],
                    key: item.value || item.value === 0 ? item.value : item[value],
                    label: item.label || item[label],
                };
            }
        }
    };

    addValueOptions = (values: any) => {
        if (values === undefined) return values;
        const { data } = this.state;
        if (typeof values === 'object') {
            const newData: object[] = [];
            const valueArr = Array.isArray(values) ? values : [values];
            //显示旧数据
            [...valueArr, ...data].forEach((item: any) => {
                newData.findIndex((ls: any) => ls.value == item.value) < 0 && newData.push(item);
            });
            this.setState({ data: newData });
        }
    };
    handleChange = (item: any) => {
        if (this.props.onChange) {
            if (Array.isArray(item)) {
                const itemData = item.map((item: any) => {
                    return {
                        ...item,
                        value: item.key,
                        ...(this.state.data.find((ls: any) => ls.value === item.key) || {}),
                    };
                });
                this.props.onChange(itemData);
            } else {
                if (item) {
                    this.props.onChange({
                        ...item,
                        value: item.key,
                        ...(this.state.data.find((ls: any) => ls.value === item.key) || {}),
                    });
                } else {
                    //集成清空操作
                    this.props.onChange(item);
                }
            }
        }
    };

    render() {
        const { data, fetching, value } = this.state;
        const { selfCom } = this.props;
        return (
            <>
                <Select
                    filterOption={false}
                    suffixIcon={<img className={s.suffixIcon} src={'https://static.mttop.cn/admin/search.png'} />}
                    {...this.props}
                    value={value}
                    showSearch={true}
                    labelInValue={true}
                    notFoundContent={
                        fetching ? (
                            <Spin size="small" />
                        ) : (
                            <span style={{ fontSize: '12px' }}>对不起,您查询的数据不存在或已被删除</span>
                        )
                    }
                    onSearch={this.onSearch}
                    onChange={this.handleChange}
                    onFocus={this.onFocus}
                    onBlur={this.onBlur}
                >
                    {data.map((d: any) => (
                        <Select.Option key={d.value} value={d.value}>
                            {d.label}
                        </Select.Option>
                    ))}
                </Select>
                {selfCom ? selfCom : null}
            </>
        );
    }
}

export default AssociationSearch;
