// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { Scrollbars } from 'react-custom-scrollbars'
import { Icon, Radio } from 'antd'
import { LayoutCard } from '@woowalker/feui'
import CommonChart from '../../Chart/CommonChart'
import EnergyNodeModal from './EnergyNodeModal'
// 样式
import styles from './index.css'

class EmEnergyNodeRealTimePage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      num: 0,
      data: [],
      chartData: {}
    }
    this.timer = -1
    this._unmounted = false
  }

  componentDidMount () {
    this.getRealTimeData()
    this.getData()
  }

  componentWillUnmount () {
    this._unmounted = true
    clearTimeout(this.timer)
  }

  getRealTimeData = () => {
    const { login, formParam, data } = this.props
    const json = {
      OrgId: login.OrgId,
      Keyword: data.TreeSelected.join(','),
      Parameter1: formParam.Parameter1,
    }
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'EM/Monitoring/GetEnergyNodeRealTimeData',
      payload: json
    }).then(res => {
      res && !this._unmounted && this.setState({ data: res })
    }).finally(() => {
      if (!this._unmounted) {
        // 一个接口请求完之后，再定时进行请求
        clearTimeout(this.timer)
        this.timer = setTimeout(this.getRealTimeData, 5000)
      }
    })
  }

  getData = () => {
    const { login, formParam, data } = this.props
    const json = {
      OrgId: login.OrgId,
      Keyword: data.TreeSelected.join(','),
      Parameter1: formParam.Parameter1,
      Parameter2: this.state.num
    }

    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'EM/Monitoring/GetEnergyNodeData',
      payload: json
    }).then(res => {
      if (res && res.chartData) {
        const { chartData } = res
        this.setState({
          chartData: {
            xAxis: chartData.XAxis[0].Data,
            yAxis: chartData.YAxis,
            data: chartData.Data
          }
        })
      }
    })
  }

  handleChange = (e) => {
    this.setState({ num: e.target.value }, this.getData)
  }

  onModalRef = (ref) => {
    this.modalChild = ref
  }

  showModal = (appid, Hmi_id) => {
    this.modalChild.showModal(appid, Hmi_id)
  }

  handleUnCheckNode = (evt, key) => {
    evt.stopPropagation()
    const { setTreeNodeUnCheck } = this.props.data
    if (setTreeNodeUnCheck && setTreeNodeUnCheck instanceof Function) {
      setTreeNodeUnCheck(key)
    }
  }

  render () {
    let { data, num, chartData } = this.state
    const { Parameter1 } = this.props.formParam
    let bg_class = styles.electric_bg
    let status_class = styles.electric_status
    let curr_class = styles.electric_curr
    let sum_class = styles.electric_sum
    let wrapHeight = 250
    switch (Parameter1) {
      case 'Water':
        bg_class = styles.water_bg
        status_class = styles.water_status
        curr_class = styles.water_curr
        sum_class = styles.water_sum
        wrapHeight = 220
        break
      case 'Hot':
        bg_class = styles.hot_bg
        status_class = styles.hot_status
        curr_class = styles.hot_curr
        sum_class = styles.hot_sum
        wrapHeight = 220
        break
      case 'Gas':
        bg_class = styles.gas_bg
        status_class = styles.gas_status
        curr_class = styles.gas_curr
        sum_class = styles.gas_sum
        wrapHeight = 220
        break
      default:
        break
    }

    const { selectedNodes = [] } = this.props.data
    const saveImgName = selectedNodes.length ? `${selectedNodes.map(item => item.node.name).join('-')}用量监测` : '用量监测'
    return (
      <div className='scroll_page'>
        <LayoutCard style={{ marginBottom: 16 }}>
          <div className={styles.realTimePage_horizontalBoxWrap} style={{ height: wrapHeight }}>
            <Scrollbars autoHide autoHideTimeout={1000} autoHideDuration={200}>
              {
                data.map(item => {
                  return (
                    <div
                      key={item.Key}
                      onClick={() => this.showModal(item.Key, item.Hmi)}
                      className={styles.meter_box}
                    >
                      <div className={bg_class}>
                        <div
                          className={status_class}
                          style={{ backgroundColor: item.State === 0 ? '#a4abb6' : item.State === 1 ? '#70b603' : '#d9001b' }}
                        />
                        <div className={curr_class}>
                          <span>{item.VarName}({item.Unit})</span>
                          <span>{item.Value}</span>
                        </div>
                        <div className={sum_class}>
                          {
                            item.ShowData.map((attr, attrIndex) => {
                              const value = `${attr.Value}${attr.Unit === 'None' || attr.Unit === null ? '' : attr.Unit}`
                              return <p key={`${attr.Name}_${attrIndex}`} className={styles.sum_text}>{`${attr.Name}：${value}`}</p>
                            })
                          }
                        </div>
                        <Icon
                          type='delete'
                          className={styles.box_close}
                          onClick={(evt) => this.handleUnCheckNode(evt, item.Key)}
                        />
                      </div>
                      <p className={styles.meter_title}>{item.ApplianceName}</p>
                      <p className={styles.meter_detail}>{item.NodeName}</p>
                    </div>
                  )
                })
              }
            </Scrollbars>
          </div>
        </LayoutCard>
        <LayoutCard title='用量监测' style={{ textAlign: 'center' }}>
          <Radio.Group value={num} buttonStyle='solid' onChange={this.handleChange}>
            <Radio.Button value={0}>过去六小时</Radio.Button>
            <Radio.Button value={1}>过去十二小时</Radio.Button>
            <Radio.Button value={2}>过去二十四小时</Radio.Button>
          </Radio.Group>
          <CommonChart
            chartId='EmEnergyNodeRealTimePage'
            {...chartData}
            saveImgName={saveImgName}
            style={{ height: 300 }}
          />
        </LayoutCard>
        <EnergyNodeModal onRef={this.onModalRef} />
      </div>
    )
  }
}

export default connect(({ login, app }) => ({ login, app }))(EmEnergyNodeRealTimePage)
