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

interface Props {
    initDataType?: undefined | 'onfocus'; // 初始化请求方式
    updateId?: any;
    request?: Function;
    selfCom?: any;
    dataSource?: [];
    onChange: Function;
    value?: any;
    autoFocus?: boolean;
    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,
        // eslint-disable-next-line react/destructuring-assignment
        fieldNames: this.props.fieldNames || { label: 'label', value: 'value' },
        initData: [],
        searchStr: '',
        canFocus: true,
    };

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

    componentWillReceiveProps = (nextProps: any) => {
        const { value, updateId } = this.props;
        const { data, initData } = this.state;
        if (JSON.stringify(nextProps.value) !== JSON.stringify(value)) {
            const vas = nextProps.value || undefined;
            let newData = data.slice();
            if (vas === undefined || vas === null) {
                newData = initData.slice();
            } else if (typeof vas === 'object') {
                if (!vas.label || !vas.label.length) {
                    newData = initData.slice();
                }
            }
            this.setState({ value: this.formaterValue(vas), data: newData });
            this.addValueOptions(vas);
        }
        if (nextProps.updateId !== undefined && JSON.stringify(nextProps.updateId) !== JSON.stringify(updateId)) {
            this.fetchData('', false, nextProps.updateId);
        }
    };

    fetchData = async (val: string, isDefault = false, id = undefined) => {
        let data = [];
        const { request, dataSource } = this.props;
        if (request) {
            this.setState({ fetching: true });
            const response = await request(val, id);
            if (response && response.data && response.success) {
                const resData = Array.isArray(response.data) ? response.data : response.data.list;
                data = Array.isArray(resData) ? resData : [];
                data = this.formaterData(data);
                if (isDefault) {
                    this.setState({ initData: data.slice() });
                }
            }
        } else {
            data = Array.isArray(dataSource) ? dataSource : [];
        }
        this.setState({ data, fetching: false });
    };

    onSearch = (val: string) => {
        const { initData } = this.state;
        this.setState({ searchStr: val });
        if (getStrLeng(val) >= 1) {
            this.fetchData(val);
        } else {
            this.setState({
                data: initData.slice(),
            });
        }
    };

    onFocus = () => {
        const { initDataType } = this.props;
        const { searchStr, canFocus, fetching } = this.state;
        if (initDataType === 'onfocus' && canFocus && !fetching) {
            this.setState({ data: [], canFocus: false });
            this.fetchData(searchStr, true);
        }
    };

    onBlur = () => {
        this.setState({ searchStr: '', canFocus: true });
    };

    formaterData = (data: any) => {
        const { fieldNames } = this.props;
        if (fieldNames) {
            const { value, label } = fieldNames;
            return data.map((item: any) => {
                return {
                    ...item,
                    value: typeof value === 'function' ? value(item) : item[value],
                    label: item[label],
                };
            });
        }
        return data;
    };

    formaterValue = (item: any) => {
        const { fieldNames } = this.props;
        if (!item) return item;
        if (fieldNames && item) {
            const { value, label } = fieldNames;
            if (Array.isArray(item)) {
                return item.map((ls: any) => {
                    return {
                        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],
                    };
                });
            }
            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: any[] = [];
            const valueArr = Array.isArray(values) ? values : [values];
            // 显示旧数据->显示新数据
            [...data, ...valueArr].forEach((item: any) => {
                const index = newData.findIndex((ls: any) => {
                    return ls.value === item.value;
                });
                if (index < 0) {
                    newData.push(item);
                }
            });
            this.setState({ data: newData });
        }
    };

    handleChange = (item: any) => {
        const { onChange } = this.props;
        const { data } = this.state;
        if (onChange) {
            if (Array.isArray(item)) {
                const itemData = item.map((temp: any) => {
                    return {
                        ...temp,
                        value: temp.key,
                        ...(data.find((ls: any) => {
                            return ls.value === temp.key;
                        }) || {}),
                    };
                });
                onChange(itemData);
            } else if (item) {
                onChange({
                    ...item,
                    value: item.key,
                    ...(data.find((ls: any) => {
                        return ls.value === item.key;
                    }) || {}),
                });
            } else {
                // 集成清空操作
                onChange(item);
            }
        }
    };

    render() {
        const { data, fetching, value } = this.state;
        const { selfCom, autoFocus, onChange, ...resert } = this.props;
        return (
            <>
                <Select
                    filterOption={false}
                    suffixIcon={<img alt="" className={s.suffixIcon} src="https://static.mttop.cn/admin/search.png" />}
                    {...resert}
                    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) => {
                        return (
                            <Select.Option key={d.value} value={d.value}>
                                {d.label}
                            </Select.Option>
                        );
                    })}
                </Select>
                {selfCom || null}
            </>
        );
    }
}

export default AssociationSearch;
