import React, { Component } from 'react';
import './index.less';
import Assets from '@src/components/Assets';

export default class AnswerSelect extends Component {
  constructor(props) {
    super(props);
    const select = [];
    for (let i = 0; i < props.list.length; i += 1) {
      select[i] = false;
    }
    this.state = { selecting: false, select };
  }

  onChange(index) {
    const { onChange } = this.props;
    const { select } = this.state;
    for (let i = 0; i < select.length; i += 1) {
      select[i] = false;
    }
    select[index] = true;
    if (onChange) onChange(select);
  }

  open() {
    this.setState({ selecting: true });
  }

  close() {
    this.setState({ selecting: false });
  }

  render() {
    const { selecting } = this.state;
    const { value, list = [] } = this.props;
    let index = 0;
    for (let i = 0; i < list.length; i += 1) {
      if (list[i].key === value) {
        index = i;
        break;
      }
    }
    const title = list.length > 0 ? list[index] : '';
    return (
      <div className="answer-select">
        <div hidden={!selecting} className="mask" onClick={() => this.close()} />
        <div className="select-warp">
          <div className="text" onClick={() => this.open()}>
            {title}
            <Assets name="chooser_icon" />
          </div>
          <div className={`select-body ${selecting ? 'select' : ''}`}>
            {list.map(item => {
              return (
                <div className="select-option" onClick={() => this.close()}>
                  {item}
                </div>
              );
            })}
          </div>
        </div>
      </div>
    );
  }
}
