import React from 'react'
import TextareaAutosize from 'react-autosize-textarea'
import newEventActions from 'actions/newEvent'
import newEventStores from 'stores/newEvent'
import { getEventBlockByBid } from 'stores/funcs/newEvent'
import { BLOCK_OP_TYPE } from 'const/const'
import { shallowEqualImmutable } from 'utils/utils'

export default class BlockDescWrap extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      desc: this.getDesc()
    }

    this.getDesc = this.getDesc.bind(this)
    this.onChange = this.onChange.bind(this)
    this.onBlur = this.onBlur.bind(this)
  }

  shouldComponentUpdate(nextProps, nextState) {
    return (
      !shallowEqualImmutable(this.props, nextProps) ||
      !shallowEqualImmutable(this.state, nextState)
    )
  }

  componentDidUpdate(preProps) {
    if (preProps.bid !== this.props.bid) {
      this.setState({
        desc: this.getDesc()
      })
    }
  }

  getDesc() {
    let result = ''
    let nodeId = this.props.eventNodeId || newEventStores.curEventNodeId
    let block = getEventBlockByBid(this.props.bid, nodeId)
    if (block && block.type === BLOCK_OP_TYPE.BLOCK) {
      result = block.com || ''
    }
    return result
  }

  onChange(e) {
    let value = e && e.target ? e.target.value : e
    this.setState({
      desc: value
    })
  }

  onBlur() {
    if (this.getDesc() !== this.state.desc) {
      let nodeId = this.props.eventNodeId || newEventStores.curEventNodeId
      newEventActions.updateBlockProp({
        nodeId,
        blockId: this.props.bid,
        prop: 'com',
        value: this.state.desc
      })
    }
  }

  render() {
    let { desc } = this.state
    return (
      <div className="desc-wrap">
        {this.props.hasGroupExtraLine ? (
          <div className="group-desc-extra-line" />
        ) : null}
        <div className="input-wrap f--h">
          <button className="btn-clear btn-icon"/>
          <div className="input-area f--hlc">
            <TextareaAutosize
              value={desc || ''}
              placeholder={'分组详情'}
              onChange={this.onChange}
              onBlur={this.onBlur}
              className={'desc-textarea'}
              maxRows={4}
              async={true}
            />
          </div>
        </div>
      </div>
    )
  }
}
