import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Search } from 'amos-framework';
import cls from 'classnames';
import './index.scss';
/**
 * 信息框-带标题和搜索
 *
 * @class ScreenCard
 * @extends {Component}
 */
class ScreenCard extends Component {

  static propTypes = {
    title: PropTypes.any,
    showSearch: PropTypes.bool,
    onSearch: PropTypes.func,
    wrapperClassName: PropTypes.any,
    className: PropTypes.string,
    children: PropTypes.any,
    wrapperStyle: PropTypes.object,
    style: PropTypes.object,
    other: PropTypes.any
  };

  static defaultProps = {

  };

  constructor(props) {
    super(props);
    this.state = {
      width: '',
      titleWidth: ''
    };
  }

  componentDidMount() {
    this.getHeight();
    window.addEventListener('resize', this.getHeight);
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.props.title !== prevProps.title) {
      this.getHeight();
    }
  }

  getHeight = () => {
    if (this.title) {
      const titleWidth = this.title.offsetWidth;
      // eslint-disable-next-line no-magic-numbers
      this.setState({ titleWidth: titleWidth + 110 });
    }
  }
  onIconClick = (e, value) => {

    this.props.onSearch(value);
  }

  render() {
    const { title, showSearch, children, style, className, wrapperStyle, wrapperClassName, other } = this.props;
    const { titleWidth } = this.state;

    return (
      <div
        ref={node => this.node = node}
        className={cls('ccs-com-screencard', wrapperClassName)}
        style={{
          ...wrapperStyle || {},
          borderImage: `url("/upload/sfcc/common/背景框.png") 50 50 50 245 fill / 50 50 50 ${titleWidth} / 0 repeat stretch`
        }}
      >
        <div className="ccs-com-screencard-header">
          <span ref={node => this.title = node} title={title}>{ title }</span>
          { showSearch && (
            <Search
              icon="search"
              placeholder="搜索"
              onIconClick={this.onIconClick}
              onSearch={(e) => this.props.onSearch(e.target.value)}
            />
          ) }
          { other }
        </div>
        <div className="ccs-com-screencard-content">
          <div style={style} className={cls('ccs-scrollbar', className)}>
            { children }
          </div>
        </div>
      </div>
    );
  }
}

export default ScreenCard;
