import React, { Component } from 'react'

export default class Mouse extends Component {
  constructor(props) {
    super(props);
    this.state = {
      clientX:0,
      clientY:0,
      x: 0,
      y: 0,
      isDown: props.isDown || false,
      cursor: 'default',
      offsetLeft: props.offsetLeft || 0,
      offsetTop: props.offsetTop || 0
    }
  }


  componentDidMount() {
    window.addEventListener('mousedown', this.handleMouseDown)
    window.addEventListener('mousemove', this.handleMouseMove)
    window.addEventListener('mouseup', this.handleMouseUp)
  }

  componentWillReceiveProps(nextProps) {
    // console.log(nextProps)
    this.setState({
      isDown: nextProps.isDown,
      offsetLeft: nextProps.offsetLeft,
      offsetTop: nextProps.offsetTop
    })
  }
  componentWillUnmount() {
    // window.removeEventListener('mousemove', this.handleMouseMove)
  }

  handleMouseDown = e => {
    // console.log(e)
    if (this.state.isDown == false) {
      return
    }
    this.setState({
      clientX: e.clientX,//获取x坐标和y坐标
      clientY: e.clientY,
      // isDown: true, //开关打开
      cursor: 'move',//设置样式
    })
  }
  handleMouseMove = e => {
    if (this.state.isDown == false) {
      return;
    }
    //获取x坐标和y坐标
    var nx = e.clientX;
    var ny = e.clientY;
    // //计算移动后的左偏移量和顶部的偏移量
    var nl = nx - (this.state.clientX - this.state.offsetLeft);
    var nt = ny - (this.state.clientY - this.state.offsetTop);
    this.setState({
      x: nl,
      y: nt
    })
  }
  handleMouseUp = e => {
    // console.log(e)
    this.setState({
      isDown: false,//开关关闭
      cursor: 'default'
    })
  }
  render() {
    const { x, y, cursor } = this.state
    // console.log('Mouse', this.props.children);
    return (
      <div>
        { this.props && this.props.children && this.props.children({ x, y, cursor }) }
      </div>
    )
  }
}
