import React, {
  useEffect,
  useRef,
  useState,
} from 'react';
import ReactDOM from 'react-dom';

import {
  AutoComplete,
  Input,
  Pagination,
  Tabs,
} from 'antd';
import classNames from 'classnames';
import PinyinMatch from 'pinyin-match';

import Icon, {
  CloseOutlined,
  RightCircleOutlined,
  SearchOutlined,
} from '@ant-design/icons';

import Draggable from './draggable';
import styles from './index.less';

const { TabPane } = Tabs;
const HistorySvg = () => (<svg className="icon" viewBox="0 0 1024 1024" version="1.1" width="10" height="10"><path d="M1016.405333 0h-351.573333a7.594667 7.594667 0 0 0-5.376 12.885333l149.077333 149.674667-244.224 249.770667H434.346667A7.594667 7.594667 0 0 0 426.666667 419.84v169.898667c0 4.266667 3.413333 7.594667 7.594666 7.594666h169.813334c4.266667 0 7.68-3.413333 7.68-7.594666V486.826667l263.253333-257.792 136.106667 135.509333A7.594667 7.594667 0 0 0 1024 359.253333V7.68A7.594667 7.594667 0 0 0 1016.405333 0z"  fill="#C1C1C1"></path><path d="M979.626667 640a45.226667 45.226667 0 0 0-44.202667 46.08v249.258667H88.490667V88.576h245.418666l1.194667-0.085333A45.056 45.056 0 0 0 378.88 44.288 45.056 45.056 0 0 0 333.994667 0H7.68A7.68 7.68 0 0 0 0 7.68v1008.64c0 4.266667 3.413333 7.68 7.68 7.68h1008.64c4.266667 0 7.68-3.413333 7.68-7.68V686.08a45.226667 45.226667 0 0 0-44.373333-46.08z" fill="#C1C1C1"></path></svg>);
const HistoryHrefIcon = props => <Icon component={HistorySvg} {...props} />;
const Empty = () => {
    return (
        <div className={styles.empty}>
            <img src="https://panda-water.cn/web4/assets/images/dataNull/暂无数据大.png"/>
            <p>非常抱歉，找不到和您查询相关的内容或信息</p>
        </div>
    )
}
function itemRender(current, type, originalElement) {
    if (type === 'prev') {
      return <a>上一页</a>;
    }
    if (type === 'next') {
      return <a>下一页</a>;
    }
    return originalElement;
  }
const Modal = (props) => {
    console.log(props);
    const dragRef = useRef(null);
    const [isWidgetShow, setIsWidgetShow] = useState(false);
    const [keyword, setKeyWord] = useState(props.value);
    const [searchProduct, setSearchProduct] = useState([]);
    // const [tabIndex]
    const [pageCurrent, setPageCurrent] = useState(1);
    const [fasts, setFasts] = useState(props.console.concat(props.willSearch) || []);
    const [searchProductList, setSearchProductList] = useState([]);
    const recentKeywords = props.recentKeywords.toJS ? props.recentKeywords.toJS(): props.recentKeywords;
    const triggerElRef = props.triggerElRef;
    const target = function() {
        if(triggerElRef.current) {
            const rect = triggerElRef.current.getBoundingClientRect();
            return {
                y: rect.top,
                x: rect.left
            }
        }
    }();

    const rawData = props.menu.concat(props.flatMenu);
    useEffect(() => {
        let ret = []
        let searchResult = []
        props.menu.map(item => {
            const match = PinyinMatch.match(item.name, keyword);
            if(match) {
                ret.push(item)
            }
        })
        setSearchProduct(ret);
        rawData.forEach(item => {
            if(keyword !== "" && PinyinMatch.match(item.name, keyword) ) {
                searchResult.push(item)
            }
        });
        setFasts(searchResult);

    }, [keyword])
    const transformSearchHistory = () => {
        const label = keyword !== "" ? "你是不是想搜：":"搜索历史：";
        const data = keyword!== "" ? searchProduct:recentKeywords
        let ret = [{
            value: '搜索历史：',
            label: (
                <li className={styles['group-label']} title={label} tabIndex={-1}>
                     <div className={styles['item-inner']}>
                        搜索历史：
                    </div>
                </li>
            )
        }]
        data.map((item, index) => {
             ret.push({
                 value: item.name || item.data,
                 label: (
                    <li className={styles['group-item']} title={item.data || item.name} tabIndex={-1} dataindex={index}>
                        <div className={styles['item-inner']}>
                            <span className={styles['item-text']}>{item.data || item.name}</span>
                        </div>
                    </li>
                 )
             })
        })
        return ret.length > 0 ? ret: [];
    }

    // const transformSeachProductList = () => {
    //     return (
    //         <div className={styles.resultContainer}>
    //             {
    //                 searchProduct.map((item, index) => {
    //                     const match =  props.matchValue(item.name, keyword)
    //                     const name =  keyword!== "" && match ? (
    //                         <div className={styles.withHightLight}>
    //                             {
    //                                 item.name.substring(0, match[0])
    //                             }
    //                             <em>
    //                                 {
    //                                     item.name.substring(match[0], match[1] + 1)
    //                                 }
    //                             </em>
    //                             {
    //                                 item.name.substring(match[1] + 1)
    //                             }
    //                         </div>
    //                     ): item.name;
    //                     return (
    //                         <a className={styles.item} key={index}>
    //                             <span className={styles.title}>
    //                                 {name}
    //                                 <RightCircleOutlined/>
    //                             </span>
    //                             <span className={styles.subtitle}>产品功能入口</span>
    //                         </a>
    //                     )
    //                 })
    //             }
                
    //         </div>
    //     )
    // }
    const goFeature = (event, item) => {
        event.persist && event.persist()
        event && event.stopPropagation();
        props.goFeature(item.path, item, keyword)
    }
    const goProduct = (event, item) => {
        event.persist && event.persist()
        event && event.stopPropagation();
        props.goProduct && props.goProduct(event, item, keyword)
    }
    const paginationProps = {
        total: fasts.length,
        current: pageCurrent,
        pageSize: 20,
        onChange: page => {
            console.log(page);
            setPageCurrent(page);
        },
    }
    const largestPage = Math.ceil(paginationProps.total / 20);
   
    if (paginationProps.current > largestPage) {
        paginationProps.current = largestPage;
    }
    const paginationContent = () => {
        if(paginationProps.total < 20) {
            return null
        }
        return (
            <div className={styles.footer}>
                <Pagination 
                    {...paginationProps}
                    showSizeChanger={false} 
                    itemRender={itemRender} 
                    size="small"/>
            </div>
        )
    };


    const transformSearchFasts = () => {
        if(fasts.length === 0) {
            return <Empty/>
        }
        let splitDataSource = [...fasts];
        if (fasts.length > (paginationProps.current - 1) * paginationProps.pageSize) {
            splitDataSource = [...fasts].splice(
              (paginationProps.current - 1) * paginationProps.pageSize,
              paginationProps.pageSize,
            );
        };
        return (
            <div className={styles.resultContainer}>
                {
                    splitDataSource.map((item, index) => {
                        const match =  props.matchValue(item.name, keyword)
                        console.log(match, keyword)
                        const name = keyword!== "" && match ? (
                            <div className={styles.withHightLight}>
                                {
                                    item.name.substring(0, match[0])
                                }
                                <em>
                                    {
                                        item.name.substring(match[0], match[1] + 1)
                                    }
                                </em>
                                {
                                    item.name.substring(match[1] + 1)
                                }
                            </div>
                        ): item.name;
                        return (
                            <a className={styles.item} key={index} onClick={(event) => {item.parent ? goFeature(event, item): goProduct(event, item)}}>
                                <span className={styles.title}>
                                    {name}
                                    {
                                        item.parent ? <HistoryHrefIcon className={styles.href}/>: <RightCircleOutlined/>
                                    }
                                    
                                </span>
                                <span className={styles.subtitle}>{item.parent ? item.parent.name: '产品功能入口'}</span>
                            </a>
                        )
                    })
                }

                {
                    paginationContent()
                }
                
            </div>
        )
    }
    const handleChange = (value) => {
        setKeyWord(value)
    }
    const handleSearch = (value) => {
        setKeyWord(value)
    };

    const handleFocus = (event) => {
        event.persist && event.persist()
        event && event.nativeEvent.stopImmediatePropagation()
    }
    
    const onSelect = (value) => {
        setKeyWord(value);
    };
    const onClose = () => {
        setIsWidgetShow(true)
    }
    if(isWidgetShow) {
        return null
    }
    const children = (
        <Draggable  dragHandleClassName={styles.header}
                default={
                    Object.assign(Object.assign({}, target), {}, {
                        width: 420,
                        height: 680
                    })
                }
                bounds="window" 
                minHeight={400} 
                minWidth={360} 
                enableUserSelectHack={false} >
            <div className={styles['base-wedget']} ref={dragRef}>
                <div className={styles.header}>
                    搜索更多
                   <button className={classNames(styles.btn, styles.close)} onClick={onClose}>
                      <CloseOutlined />
                   </button>
                </div>
                <div className={styles.body}>
                    <div className={styles.search}>
                        <AutoComplete options={transformSearchHistory()} 
                                      dropdownClassName={styles.searchList} 
                                      value={keyword} 
                                      onSelect={onSelect}
                                      onSearch={handleSearch}
                                      onChange={handleChange}
                                      onFocus={handleFocus}
                                      >
                            <Input size="middle" placeholder="请输入"  allowClear suffix={<SearchOutlined className="site-form-item-icon" />}/>
                        </AutoComplete>
                    </div>
                    <div className={styles.result}>
                                {
                                     transformSearchFasts()
                                }
                        {/* <Tabs defaultActiveKey="1" size="small">
                            <TabPane tab="产品功能入口" key="1">
                                {
                                    transformSeachProductList()
                                }  
                            </TabPane>
                            <TabPane tab="快捷操作" key="2">
                                {
                                    transformSearchFasts()
                                }

                            </TabPane>
                          
                        </Tabs> */}
                    </div>
                </div>
            </div>
            
        </Draggable>
    )
    return ReactDOM.createPortal(children, document.body)
}

export default Modal;
