import React from 'react'
import cls from 'classnames'
import { shallowEqualImmutable } from 'src/utils/utils'
import { getEventNodeById } from 'stores/funcs/newEvent'
import newEventStores from 'stores/newEvent'

export default class BlockOrder extends React.Component {
  constructor(props) {
    super(props)
    this.curEventNodeId = newEventStores.curEventNodeId
    this.state = {
      order: this.getOrder()
    }

    this.onEventChange = this.onEventChange.bind(this)
    this.getStyle = this.getStyle.bind(this)
    this.getOrder = this.getOrder.bind(this)
    this.decoOrder = this.decoOrder.bind(this)
  }

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

  componentDidMount() {
    this.unsubscribe = newEventStores.listen(this.onEventChange)
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  componentDidUpdate(preProps) {
    // parentBid改变时需要更新
    if (preProps.bid !== this.props.bid) {
      let order = this.getOrder()
      if (order !== this.state.order) {
        this.setState({
          order: order
        })
      }
    }
  }

  onEventChange(status) {
    let obj = {}
    if (status) {
      if (status.types.includes('curEventNodeId')) {
        if (this.curEventNodeId !== status.data.curEventNodeId) {
          this.curEventNodeId = status.data.curEventNodeId
        }
      }
      if (status.types.includes('curEventBlockOrder')) {
        let order = this.getOrder()
        if (order !== this.state.order) {
          this.setState({
            order: order
          })
        }
      }
    }
    if (Object.keys(obj).length > 0) {
      this.setState(obj)
    }
  }

  getOrder() {
    let curNodeId = this.props.eventNodeId || this.curEventNodeId
    let eventNode = getEventNodeById(curNodeId)
    if (eventNode) {
      return eventNode.events.order.indexOf(this.props.bid)
    }
    return 0
  }

  getStyle() {
    const extraGapGroupLayer =
      this.props.extraGapGroupLayer > 0
        ? (this.props.extraGapGroupLayer - 1) * 2
        : 0
    return {
      left:
        -(
          8 +
          this.props.layer * 20 +
          (this.props.layer + 1) +
          extraGapGroupLayer
        ) -
        28 +
        'px'
    }
  }

  decoOrder() {
    let result = this.state.order + 1
    if (result < 10) {
      result = '0' + result
    }
    return result
  }

  render() {
    let { className } = this.props
    return (
      <div
        className={cls('block-order f--h', className)}
        style={this.getStyle()}
      >
        <div className="order-num f--hlc">
          <div className="num">{this.decoOrder()}</div>
        </div>
        <div className="order-dot f--hlc">
          <div className="dot" />
        </div>
      </div>
    )
  }
}
