import React from 'react';
import { connect } from 'dva';
import { Select, Spin, message, Pagination } from 'antd';
import {
    initFilter, getOnlyPropertyData, getDataFieldValue, empty, extendRule, extendInclude,
    initFilterGroup, extendGroupRule, extendFilterGroup, guid, getParseValue, setDataFieldValue
} from "../../utils/common";
import config from "../../config";
import debounce from 'lodash/debounce';
import storage from '../../utils/storage'
import { serializeRequestParams } from '../../utils/request'
import { IFComponent } from '@woowalker/feui';
import { isEqual } from 'lodash'
const { Option } = Select;

class MultiSelectPagination extends React.Component {
    constructor(props) {
        super(props);
        this.lastFetchId = 0;
        this.fetchUser = debounce(this.fetchUser, 500);
        this.state = {
            initJson: {},
            data: [],
            value: [],
            allData: [],
            baseNav: [],//数据库
            //fetching: false,
            record: this.props.record,
            searchKey: null,
            TotalCount: 0
        }
    }

    componentDidMount() {
        this.getValue()
        //this.initFilterJson();
    }


    static getDerivedStateFromProps(nextprops, preprops) {
        // if (nextprops.record !== preprops.record) {
        //     return {
        //         record: nextprops.record,
        //     }
        // }
        // return null
        if (isEqual(nextprops.record, preprops.record)) {
            return null;
        }
        if (nextprops?.record?.ID != preprops?.record?.ID || (nextprops?.record && preprops?.record && nextprops.colConfig &&
            !isEqual(nextprops?.record[nextprops.colConfig.field], preprops?.record[nextprops.colConfig.field]))) {
            return {
                record: nextprops.record,
            }
        }
    }

    // shouldComponentUpdate(nextProps,nextState){
    //     if(isEqual(nextProps.record,this.props.record))
    //     {
    //         return true;
    //     }else{
    //         return true;
    //     }
    // }

    componentDidUpdate(prevProps, prevState) {
        if (prevState.record?.ID !== this.props.record?.ID
            || !isEqual(prevState.record[this.props.colConfig.field], this.props.record[this.props.colConfig.field])) {
            this.setState({
                value: [],
                //isUpdate:true,
            }, () => {
                this.getValue()
                this.initFilterJson();
            })
        }
    }

    // UNSAFE_componentWillReceiveProps(NextProps) {
    //     const { record } = NextProps
    //     if (this.props.record?.ID!== record?.ID ||this.props.record[this.props.colConfig.field] !==record[this.props.colConfig.field]) {
    //         this.setState({
    //             //record: record,
    //             value: []
    //         }, () => {
    //             this.getValue()
    //             this.initFilterJson();
    //         }
    //         )
    //     }
    // }

    getValue = () => {
        let { saveField, navField, labelField, onChangeHandle, sortField, idField, filterField } = this.props.data;
        labelField = labelField ? labelField : "NAME"
        const record = this.state.record;
        var navFields = navField.split(',');
        var saveFields = saveField.split(',');
        var saveId = "";
        navFields.forEach((item, i) => {
            if (item == "ID") {
                saveId = saveFields[i];
            }
        })
        let value = this.state.value;
        const data = this.state.data;
        var allData = this.state.allData;
        if (record && this.props.colConfig.field) {
            var fieldVal = getDataFieldValue(record, this.props.colConfig.field)
            //const navShowFieldArray = this.props.colConfig.field.split('.');      //获取显示字段 数组(取数组后两个)
            fieldVal && Array.isArray(fieldVal) && fieldVal.map(item => {
                if (!item.IS_DELETED) {
                    let labelFields = labelField.split(',');
                    var labelFieldFix = labelFields.length > 0 ? labelFields[0] : [];
                    if (saveId) {
                        value.push({ key: getDataFieldValue(item, saveId), label: getDataFieldValue(item, labelFieldFix), ID: item.ID ? item.ID : guid() });
                        let queryItem = {};
                        saveFields.forEach((savekey, i) => {
                            var getvalue = getDataFieldValue(item, savekey);
                            setDataFieldValue(queryItem, navFields[i], getvalue);
                        });
                        allData.push(queryItem);

                    }
                }
            })

            this.setState({
                baseNav: fieldVal ? fieldVal : [],
                allData,
                saveId,
            })
        }
        //value = this.unique(value);
        this.setState({
            value
        })
    }
    //数组去重
    unique = (arr) => {
        let obj = {};
        arr = arr.reduce((item, next) => {
            if (!obj[next.key]) {
                item.push(next);
                obj[next.key] = true;
            }
            return item;
        }, []);
        return arr
    }

    //初始化传参
    initFilterJson = (changeValue, isSearch) => {
        const { navField, showField, labelField, onChangeHandle, sortField, idField, filterField, filterOrgType } = this.props.data;
        const { searchKey } = this.state;

        const record = this.props.record;
        let json = initFilter(this.props.login.OrgId, '', sortField ? sortField : 'ID', 1);
        json.OrgType = filterOrgType;
        const { column } = this.props.colConfig;
        if (navField) {
            const nav = navField.split(',');
            nav.map(item => {
                if (item.indexOf('.') != -1) {
                    var lastIndex = item.lastIndexOf('.');
                    var incluePath = item.substring(0, lastIndex);
                    extendInclude(json, incluePath);
                }
            })
        }
        if (column && column.Nav_Filters) {
            // let group = initFilterGroup(false);//wyw 
            let group = initFilterGroup(column.IS_AND_FILITER);//wyw 是否过滤条件取并集
            column.Nav_Filters.map(item => {
                let val = '';
                const getFieldValueFunc = (field, thisRef) => getDataFieldValue(record, field);
                if (item.VALUE.indexOf('@record') != -1) {
                    val = getParseValue(item.VALUE, '', '', getFieldValueFunc)
                } else if (item.VALUE.indexOf('@head') != -1) {
                    val = getParseValue(item.VALUE, '', getFieldValueFunc)
                } else {
                    val = getParseValue(item.VALUE, this.props.login.user);
                }
                if (val) {
                    if (item.IS_CUSTOM) {
                        json[item.FIELD_NAME] = val
                    } else {
                        extendGroupRule(group, item.FIELD_NAME, item.OPERATION, val);
                    }
                }
            })
            extendFilterGroup(json, group);
        }
        if (changeValue || searchKey) {
            const arrOBj = filterField ? filterField.split(',') : ['NAME', 'CODE'];
            let group = initFilterGroup(false);
            arrOBj.forEach((i, n) => {
                extendGroupRule(group, i, 9, changeValue ? changeValue : searchKey);
            });
            extendFilterGroup(json, group);
        }
        this.setState({ initJson: json }, () => {
            isSearch && this.fetchUser();
        })
    }

    isObjEqual = (o1, o2) => {
        var props1 = Object.getOwnPropertyNames(o1);
        var props2 = Object.getOwnPropertyNames(o2);
        if (props1.length != props2.length) {
            return false;
        }
        for (var i = 0, max = props1.length; i < max; i++) {
            var propName = props1[i];
            if (o1[propName] !== o2[propName]) {
                return false;
            }
        }
        return true;
    }

    fetchUser = (params = {}) => {//TODO 过滤条件 提交时需要加上ID
        this.initFilterJson('', false);
        const { navField, showField, labelField, onChangeHandle } = this.props.data;
        const { dispatch, data, api } = this.props
        let loadParam = { ...params };
        let json = this.state.initJson;
        if (!loadParam.PageIndex) {
            loadParam = {
                PageIndex: 1,
            }
        }
        let selectField = [];
        if (navField) {
            var navFieldArray = navField.split(",");
            selectField = selectField.concat(navFieldArray);
        }

        if (showField) {
            var showFieldArray = showField.split(",");
            selectField = selectField.concat(showFieldArray);
        } else {
            selectField = selectField.concat(["NAME", "CODE"]);
        }
        if (selectField.length == 0) {
            selectField = ["NAME", "CODE"];
        }
        // var labelFieldArray = labelField?.split(",");
        // if (labelFieldArray.length == 0) {
        //     labelFieldArray = ["NAME", "CODE"];
        // }
        // this.setState({
        //     loadParam,
        // });
        // api:数据API（必填）  onSelect：选中项事件（必填），选中后调用该事件
        // showField：下拉显示字段,navField：导航字段,labelField：显示字段,filterField：过滤字段,sortField：排序字段,sortOrder：排序方式,saveField:保存字段
        // onFilter：过滤事件（可选），在获取下拉数据时调用
        // onChangeHandle：改变事件（可选）， 分页下拉控件改变时调用
        // width：宽度（可选）
        if (!this.props.api) {
            return false;
        }
        this.lastFetchId += 1;
        const fetchId = this.lastFetchId;
        //this.setState({ data: [], fetching: true });
        this.setState({ loadParam }, () => {
            json.PageIndex = this.state.loadParam.PageIndex
            json.Start = (json.PageIndex - 1) * 10
            json.SelectField = selectField;
            let that = this;
            dispatch({
                type: 'editPage/getAutoCompleteData',
                payload: json,
                url: api,
                isIgnoreTenant: data.isIgnoreTenant,
                onComplete: function (ret) {
                    if (ret) {
                        // 修改前
                        // this.setState({ data: body.Data, fetching: false });
                        // 修改后
                        var allData = that.state.allData;
                        ret.Data && ret.Data.forEach(x => {
                            var isExitItem = allData.filter((it) => {
                                return it.ID == x.ID;
                            })
                            if (isExitItem.length == 0) {
                                allData.push(x);
                            }
                        })
                        that.setState({
                            data: ret.Data,
                            TotalCount: ret.TotalCount,
                            //fetching: false,
                            allData: allData
                        });
                    } else {

                    }
                }
            });
        });
        // this.props.dispatch({
        //     type: 'app/getDataByPost',
        //     payload: json,
        //     url: this.props.api,
        //     onlyData:false,
        //     onComplete: (ret) => {
        //         if (fetchId !== this.lastFetchId) {
        //             // for fetch callback order
        //             return;
        //         }
        //         if (ret.IsSuccessful) {
        //             // 修改前
        //             // this.setState({ data: body.Data, fetching: false });
        //             // 修改后
        //             this.setState({ data: ret.Data, TotalCount: ret.TotalCount,fetching: false });
        //         } else {
        //             message.error(ret.ErrorMessage)
        //         }
        //     }
        // })

    };
    autoComDataPage = (num) => {
        const { navField, showField, labelField, onChangeHandle, sortField, idField, filterField, filterOrgType } = this.props.data;
        let params = initFilter(this.props.login.OrgId, '', sortField ? sortField : 'ID', 0, num);
        this.fetchUser(params)
    }
    // getAutoCompleteLoadParam=(params={},e)=> {
    //     let loadParam={ ...initParams, ...params };
    //     return loadParam
    // }

    //检索
    onSearch = (value) => {
        this.setState({
            searchKey: value
        }, this.initFilterJson(value, 1))

    }
    //失去焦点 失去焦点清除searchKey 的值
    onBlur = (e) => {
        e.stop
        this.setState({ searchKey: null }, () => {
            this.initFilterJson('')
        })
    }
    //获取数组不相同的元素
    getArrDifSameValue = (arr1, arr2) => {
        var result = [];
        for (var i = 0; i < arr2.length; i++) {
            var obj = arr2[i];
            var id = obj.id;
            var isExist = false;
            for (var j = 0; j < arr1.length; j++) {
                var aj = arr1[j];
                var n = aj.id;
                if (n == id) {
                    isExist = true;
                    break;
                }
            }
            if (isExist) {
                result.push(obj);
            }
        }
        return result;
    }

    handleChange = (value, option) => {
        // let retVal = [];
        // let that = this;
        // const record = this.props.record;
        // let { saveField, navField, labelField, onChangeHandle, sortField, idField, filterField } = this.props.data;
        // if (navField) {
        //     var inputFields = navField.split(',');
        //     var saveFields = saveField.split(',');
        //     value.forEach(va => {
        //         let valueItem = that.state.allData.filter(xt => {
        //             return xt.ID == va.key;
        //         })
        //         if (valueItem.length > 0) {
        //             var retItem = {};
        //             inputFields.forEach((item, index) => {
        //                 retItem[saveFields[index]] = getDataFieldValue(valueItem[0], item)
        //             })
        //             if (va.ID) {
        //                 retItem.ID = va.ID;
        //             } else {
        //                 retItem.ID = guid()
        //             }
        //             retItem[idField] = record.ID;
        //             retItem.ORG_ID = record.ORG_ID;
        //             retVal.push(retItem);
        //         }

        //     })

        // }


        // this.setState({
        //     value: value,
        //     fetching: false,
        // });
        // if (typeof this.props.onChange === 'function') {
        //     this.props.onChange(retVal);
        // }
        // if (onChangeHandle && typeof onChangeHandle === 'function') {
        //     onChangeHandle(retVal);
        // }
        var sss = 0;
    };


    getDataValue = (stateValue) => {
        let { saveField, navField, idField } = this.props.data;
        let { field } = this.props.colConfig
        const record = this.props.record;
        var navPointIndex = field.lastIndexOf('.');
        var fieldId = "";
        if (navPointIndex !== -1) {
            var realField = field.substring(0, navPointIndex);
            let mainObj = getDataFieldValue(record, realField)
            fieldId = mainObj?.ID;
        } else {
            fieldId = record?.ID;
        }
        let retVal = [];
        let that = this;
        if (navField) {
            var inputFields = navField.split(',');
            var saveFields = saveField.split(',');
            stateValue.forEach(va => {
                let valueItem = that.state.allData.filter(xt => {
                    return xt.ID == va.key;
                })
                if (valueItem.length > 0) {
                    var retItem = {};
                    inputFields.forEach((item, index) => {
                        var getvalue = getDataFieldValue(valueItem[0], item)
                        setDataFieldValue(retItem, saveFields[index], getvalue);
                    })

                    retItem.ID = guid()
                    retItem[idField] = fieldId;
                    retItem.ORG_ID = record.ORG_ID;
                    retVal.push(retItem);
                }

            })

        }
        return retVal;
    }

    handleSelect = (item, option) => {
        let { onChangeHandle } = this.props.data;
        var stateValue = this.state.value;
        stateValue.push({ key: item.key, label: item.label, ID: guid() });
        this.setState({
            value: stateValue,
            //fetching: false,
        });
        let retVal = this.getDataValue(stateValue);
        this.state.baseNav.forEach(db => {
            const index = stateValue.findIndex(i => i.key == db[this.state.saveId]);
            if (index == -1) {
                db.IS_DELETED = true;
                retVal.push(db);
            } else {
                let retIndex = retVal.findIndex(rv => rv[this.state.saveId] == db[this.state.saveId])
                if (retIndex !== -1) {
                    retVal[retIndex].ID = db.ID;
                }
            }
        })

        if (typeof this.props.onChange === 'function') {
            this.props.onChange(retVal);
        }
        if (onChangeHandle && typeof onChangeHandle === 'function') {
            onChangeHandle(retVal);
        }

    };

    deHandleSelect = (item, option) => {

        let { onChangeHandle } = this.props.data;
        var stateValue = this.state.value;
        const index = stateValue.findIndex(i => i.key == item.key);
        stateValue.splice(index, 1);

        this.setState({
            value: stateValue,
            //fetching: false,
        });

        let retVal = this.getDataValue(stateValue);
        this.state.baseNav.forEach(db => {
            const index = stateValue.findIndex(i => i.key == db[this.state.saveId]);
            if (index == -1) {
                db.IS_DELETED = true;
                retVal.push(db);
            } else {
                let retIndex = retVal.findIndex(rv => rv[this.state.saveId] == db[this.state.saveId])
                if (retIndex !== -1) {
                    retVal[retIndex].ID = db.ID;
                }
            }
        })

        if (typeof this.props.onChange === 'function') {
            this.props.onChange(retVal);
        }
        if (onChangeHandle && typeof onChangeHandle === 'function') {
            onChangeHandle(retVal);
        }

    };


    showText = (d, showField) => {
        if (showField) {
            let tmp = '', tmpArr = showField.split(',');
            tmpArr.map(item => {
                if (tmp) {
                    tmp = tmp + '-'
                }
                tmp += getDataFieldValue(d, item);
            })
            tmp = tmp.trim('-')
            return tmp;
        } else {
            return getDataFieldValue(d, showField);
        }
    }

    dropdownRender = () => {
        return <>

        </>
    }

    getOptionId = (data, field) => {
        let fieldArray = field.split(',');
        fieldArray = fieldArray.length > 0 ? fieldArray[0] : [];
        fieldArray = fieldArray.split('.');
        if (fieldArray.length > 0) {
            fieldArray.splice(-1, 1)
        }
        fieldArray.push('ID')
        return getDataFieldValue(data, fieldArray.join('.'))
    }

    render() {
        const { data, value, TotalCount } = this.state;
        let { navField, showField, labelField, onChangeHandle, fieldName, selectLabelField } = this.props.data;
        if (selectLabelField) {
            labelField = selectLabelField
        }
        if (!labelField) {
            labelField = "NAME"
        }
        if (!showField) {
            showField = "CODE,NAME"
        }
        let tmpArr = [];
        if (showField) {
            tmpArr = showField.split(',');
        }
        //let controlValue = value ? value : getDataFieldValue(data, fieldName);
        const { loading } = this.props
        //const autoLoading = loading.effects['app/getDataByPost'];
        return (
            <Select
                mode="multiple"
                labelInValue={true}
                autoClearSearchValue={false}
                value={value}
                placeholder={this.props.promptInfo}
                // notFoundContent={fetching ? <Spin size="small" /> : null}
                filterOption={false}
                onSearch={this.onSearch}
                onMouseEnter={this.fetchUser}
                onChange={this.handleChange}
                onSelect={this.handleSelect}
                onDeselect={this.deHandleSelect}
                dropdownMatchSelectWidth={false}
                dropdownStyle={{ width: 300 }}
                style={{ width: '100%', minWidth: '100px' }}
                // style={{ minWidth: '100px', maxWidth: '250px' }}
                optionLabelProp="label"
                disabled={this.props.disabled}
                onBlur={this.onBlur}
            // dropdownRender={this.dropdownRender}
            >
                {
                    this.state.data && this.state.data.map(d => (
                        // d[labelField ? labelField : 'NAME']

                        <Option key={d["ID"]} label={getDataFieldValue(d, labelField)}>
                            {
                                //this.showText(d, showField)
                                tmpArr.map(item => {
                                    if (item.indexOf('.') > 0) {
                                        return getDataFieldValue(d, item);
                                    } else {
                                        return d[item];
                                    }
                                })
                                // d.text
                            }
                        </Option>
                    )).concat([
                        <Option disabled key="pagination" className="show-all">
                            {/* <Spin spinning={autoLoading}> */}
                            <Pagination
                                current={this.state.loadParam ? this.state.loadParam.PageIndex : 0}
                                onChange={(num) => this.autoComDataPage(num)}
                                size="small"
                                // total="10"
                                total={TotalCount}
                            />
                            {/* </Spin> */}
                        </Option>
                    ])
                }
            </Select>
        );
    }

}

MultiSelectPagination.propTypes = {
};

export default connect(({ login, loading, listPage, custom, app }) => ({ login, loading, listPage, custom, app }))(MultiSelectPagination);
