import React, { Component } from 'react';
import ReactDom from 'react-dom';
import styles from './style.css';
import arrIcon from './images/select_icon@2x.png';
import Popup from '../../Popup/Popup';

class Select extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hasValue:
        Object.keys(props).find(i => i === 'value') === -1 ? false : true,
      value: [],
    };
  }

  showPickerView = () => {
    console.log('showPickerView');
    console.log(this.props);

    const { placeholder, onChange, ...props } = this.props;
    let box = document.getElementById('ks-picker-box');
    if (!box) {
      box = document.createElement('div');
      box.id = 'ks-picker-box';
      document.body.appendChild(box);
    }
    this.picker = ReactDom.render(
      <Popup
        {...props}
        onChange={this.changeHandle}
        cancelHandle={this.cancelHandle}
        okHandle={this.okHandle}
      />,
      box
    );
  };
  changeHandle = val => {
    console.log(val);
    const { onChange } = this.props;
    onChange && onChange(val);
  };
  okHandle = () => {
    const { onChange } = this.props;
    const { value } = this.picker.state;
    const { hasValue } = this.state;
    if (hasValue) {
      onChange && onChange(value);
    } else {
      this.setState({
        value: value,
      });
    }
    this.closePickerHandle();
  };
  cancelHandle = () => {
    this.closePickerHandle();
  };
  closePickerHandle = () => {
    let box = document.getElementById('ks-picker-box');
    document.body.removeChild(box);
  };
  render() {
    const { placeholder, data } = this.props;
    const { value, hasValue } = this.state;

    let text = '';
    if (hasValue) {
      let val = this.props.value;
      text = val.length
        ? data.find(item => item.value === val[0]).label
        : placeholder
          ? placeholder
          : '';
    } else {
      text = value.length
        ? data.find(item => item.value === value[0]).label
        : placeholder
          ? placeholder
          : '';
    }
    return (
      <div className={styles.selectWrap} onClick={this.showPickerView}>
        {text}
        <span className={styles.arrow}>
          <img src={arrIcon} alt="" />
        </span>
      </div>
    );
  }
}

export default Select;
