import React, { Component } from 'react'; import classes from '../seller.css'; type Props = { products: any; onAddHandler: (product: any) => void; isHide: boolean; clickHandler: (hide: boolean) => void; } type State = { searchBy: string; inputValue: string; value: string; foundProducts: any; timeout: any; }; class FindProducts extends Component { constructor(props: Props) { super(props); this.state = { searchBy: 'barcode', inputValue: '', value: '', foundProducts: [], timeout: 0, } } onDropDownClick = (by: string) => { this.setState({searchBy: by}) }; handleChange = (e: any) => { const { products } = this.props; if (products.length > 0) { let value = e.target.value.replace(new RegExp("\\\\", "g"), ""); const searchBy = this.state.searchBy; this.setState({value}); let timeout; if (this.state.timeout) { clearTimeout(this.state.timeout) } if (value.length > 0 && products) { timeout = setTimeout(() => { this.setState({inputValue: value}); let items = products.filter((item: any) => { return item[searchBy].toLowerCase().search(value.toLowerCase()) !== -1; }); const filtered = items.filter((item: any) => item.remain_amount - item.count > 0); this.setState({foundProducts: filtered}); }, 1000); this.setState({timeout: timeout}); } else { this.setState({foundProducts: []}); this.setState({inputValue: ""}); } } }; renderNotFound() { return (

Oops! Item not found

) } onItemClick = (item: any) => { item.count++; this.props.onAddHandler(item); this.setState({inputValue: ""}); this.setState({value: ""}); this.setState({foundProducts: []}) }; renderFound = () => { return (
{this.state.foundProducts.map((item: any) => { const time = item.expire_date * 1000; const date = `${new Date(time).getFullYear()}/${new Date(time).getMonth() + 1}`; return(
this.onItemClick(item)} key={item.item_id} className='dropdown-item' style={{ cursor: 'pointer' }}>

{item.trade_name}

{item.sale_price}

{date}

) })}
) }; renderFoundProducts = ()=> { if(this.state.inputValue.length > 0) { if(this.state.foundProducts.length === 1 && this.state.searchBy === "barcode") { this.onItemClick(this.state.foundProducts[0]); } return (
{ this.state.foundProducts.length > 0 ? this.renderFound(): this.renderNotFound() }
) } return ""; }; render() { const selectStyle = this.props.isHide ? "dropdown show": "dropdown"; const dropMenue = this.props.isHide ? "dropdown-menu show" : "dropdown-menu"; return (
this.handleChange(e)} /> {this.renderFoundProducts()}
); } } export default FindProducts;