import react from "react";
import style from "./index.less";
import classNames from 'classnames';
import {deepClone} from '@utils/tools.js';
import LiItem from '@common/components/LiItem';
/**
  单列多选组件下拉 2019-2-20 By_liucf
  接收参数：
  show：是否展示下拉
  data：下拉数据
  handleConfirm: 确定事件
  seleData、seleId：选中的数据和id，回读标识选中状态用
**/

class SlideItem extends react.Component{
  constructor(props){
    super(props);
    const seleData = deepClone(props.seleData||[]);
    const seleId = deepClone(props.seleId||[]);
    this.state={
      seleData:seleData||"",
      seleId:seleId||[]
    }
    this.handleSelect = this.handleSelect.bind(this);
    this.handleClear = this.handleClear.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }

  getListClass(){
    let isHide = this.props.show?'':style['hide'];
    return classNames(style['list'],isHide);
  }

  /*getSeleStyle(id){
    const {seleId} = this.state;
    if(seleId.includes(id)){
      return style['selected'];
    }
    return '';
  }*/

  handleSelect(e,item){
    e&&e.stopPropagation();
    let {seleData,seleId} = this.state;
    const {name,id} = item;
    if(seleId.includes(id)){
      seleId.splice(seleId.indexOf(id),1);
      seleData = seleData.replace(name,'');
    }else{
      seleId.push(id);
      seleData += name;
    }
    this.setState({
      seleData,
      seleId
    })
  }

  handleClear(e){
    e&&e.stopPropagation();
    this.setState({
      seleData:"",
      seleId:[]
    })
  }

  getStyle(){
    const {show} = this.props;
    return {
      display:show?'table':'none' 
    }
  }
  handleClick(e){//确定
    e&&e.stopPropagation();
    const {handleConfirm} = this.props;
    const params = this.state;
    handleConfirm&&handleConfirm(params);
  }
  componentWillReceiveProps(next){
    if(this.props.show!==next.show){
      const seleData = deepClone(this.props.seleData||[]);
      const seleId = deepClone(this.props.seleId||[]);
      this.setState({
        seleData:seleData||"",
        seleId:seleId||[]
      });
    }
  }
  render(){
    const {data} = this.props;
    const {seleId} = this.state;
    return <div className={this.getListClass()} style={this.getStyle()} contentEditable="false">
        <ul>
          {data&&data.map((it)=>{
          return <LiItem handleClick={(e)=>this.handleSelect(e,it)}
                         selected={seleId.includes(it.id)}
                         title={it.name.length>8?it.name:''}>{it.name&&it.name.length>8?it.name.slice(0,8)+'...':it.name}</LiItem>
        })}
          <li onClick={this.handleClear} className={style['mClear']}>清空选项</li>
          <li onClick={this.handleClick} className={style['mConfirm']}>确定</li>
        </ul>
      </div>
  }
}

export default SlideItem;