// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { Form, Radio, Row, Col, Collapse } from 'antd'
import { IFComponent, LayoutCard } from '@woowalker/feui'
import CommonChart from '../../Chart/CommonChart'
// 工具库
import moment from 'moment'
// 样式
import styles from './index.css'

const { Panel } = Collapse

class EmAppRealTimePage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      data: [],
      realData: [],
      showData: [],
      chartData: {},
      heartbertData: [],
      num: 1,
      time: moment().add(-6, 'hour').format('YYYY-MM-DD HH:mm:ss') + "," + moment().format('YYYY-MM-DD HH:mm:ss')
    }
    this.timer = -1
    this._unmounted = false
  }

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

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

  getRealTimeData = () => {
    const json = {
      OrgId: this.props.login.OrgId,
      Parameter1: this.props.formParam.Parameter1,
      Parameter2: this.props.login.userId,
      Parameter3: this.props.data.id,
      Parameter4: this.props.data.isNode,
    }
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'EM/Monitoring/GetAppRealTimeData',
      payload: json
    }).then(res => {
      res && !this._unmounted && this.setState({
        data: res.Data,
        realData: res.realData,
        showData: res.showData,
        heartbertData: res.heartbertData
      })
    }).finally(() => {
      if (!this._unmounted) {
        // 一个接口请求完之后，再定时进行请求
        clearTimeout(this.timer)
        this.timer = setTimeout(this.getRealTimeData, 5000)
      }
    })
  }

  getChartData = () => {
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'EM/Monitoring/GetVarIdByApp',
      payload: {
        OrgId: this.props.login.OrgId,
        Parameter3: this.props.data.id,
        Parameter4: this.props.data.isNode
      }
    }).then(res => {
      if (res) {
        this.props.dispatch({
          type: 'app/getDataByPost',
          url: 'FM/FMSrcTag/GetchartPageApiEntities',
          payload: {
            OrgId: this.props.login.OrgId,
            Parameter1: this.state.time,
            Keyword: res
          }
        }).then(response => {
          if (response) {
            this.setState({
              chartData: {
                xAxis: response.XAxis[0].Data,
                yAxis: response.YAxis,
                data: response.Data
              }
            })
          }
        })
      }
    })
  }

  handleChange = (e) => {
    let time = ''
    const num = e.target.value
    switch (num) {
      case 1:
        time = moment().add(-6, 'hour').format('YYYY-MM-DD HH:mm:ss') + "," + moment().format('YYYY-MM-DD HH:mm:ss')
        break
      case 2:
        time = moment().add(-12, 'hour').format('YYYY-MM-DD HH:mm:ss') + "," + moment().format('YYYY-MM-DD HH:mm:ss')
        break
      case 3:
        time = moment().add(-1, 'day').format('YYYY-MM-DD HH:mm:ss') + "," + moment().format('YYYY-MM-DD HH:mm:ss')
        break
      default:
        break
    }
    this.setState({ num, time }, this.getChartData)
  }

  render () {
    let bg_class = styles.electric_bg
    let status_class = styles.electric_status
    let curr_class = styles.electric_curr
    let sum_class = styles.electric_sum

    switch (this.props.formParam.Parameter1) {
      case 'Water':
        bg_class = styles.water_bg
        status_class = styles.water_status
        curr_class = styles.water_curr
        sum_class = styles.water_sum
        break
      case 'Hot':
        bg_class = styles.hot_bg
        status_class = styles.hot_status
        curr_class = styles.hot_curr
        sum_class = styles.hot_sum
        break
      case 'Gas':
        bg_class = styles.gas_bg
        status_class = styles.gas_status
        curr_class = styles.gas_curr
        sum_class = styles.gas_sum
        break
      default:
        break
    }
    const { data, realData, chartData, showData } = this.state
    return (
      <div className='scroll_page'>
        <LayoutCard style={{ marginBottom: 16 }}>
          <Row gutter={16}>
            <Col span={4} style={{ marginTop: 48 }}>
              <div className={styles.realTimePage_boxWrap}>
                {
                  data.map(item => {
                    const color = item.State === 0 ? '#a4abb6' : item.State === 1 ? '#70b603' : '#d9001b'
                    return (
                      <div
                        key={item.Key}
                        className={styles.meter_box}
                      >
                        <div className={bg_class}>
                          <div className={status_class} style={{ backgroundColor: color }} />
                          <div className={curr_class}>
                            <span>{item.VarName}({item.Unit})</span>
                            <span>{item.Value}</span>
                          </div>
                          <div className={sum_class}>
                            {
                              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>
                        </div>
                        <p className={styles.meter_title}>{item.ApplianceName}</p>
                        <p className={styles.meter_detail}>{item.NodeName}</p>
                      </div>
                    )
                  })
                }
              </div>
            </Col>
            <Col span={20} style={{ textAlign: 'center' }}>
              <Radio.Group value={this.state.num} buttonStyle="solid" onChange={this.handleChange}>
                <Radio.Button value={1}>过去六小时</Radio.Button>
                <Radio.Button value={2}>过去十二小时</Radio.Button>
                <Radio.Button value={3}>过去二十四小时</Radio.Button>
              </Radio.Group>
              <CommonChart chartId='EmAppRealTimePage' {...chartData} style={{ height: 300 }} />
            </Col>
          </Row>
        </LayoutCard>
        <IFComponent IF={realData.length}>
          <LayoutCard title='器具属性实时数据'>
            <Collapse
              defaultActiveKey={realData.map((item, index) => `${item.Name}_${index}`)}
              style={{ marginTop: '0.15rem' }}
            >
              {
                realData.map((item, index) => {
                  return (
                    <Panel header={item.Name} key={`${item.Name}_${index}`}>
                      <Form labelCol={{ span: 10 }} wrapperCol={{ span: 14 }} colon={false}>
                        <Row>
                          {
                            item.Items.map((attr, attrIndex) => {
                              const value = `${attr.Value}${attr.Unit === 'None' || attr.Unit === null ? '' : attr.Unit}`
                              return (
                                <Col key={`${attr.Name}_${attrIndex}`} span={6}>
                                  <Form.Item
                                    label={<div title={attr.Name} className='text-ellipsis'>{attr.Name}</div>}
                                    style={{ marginBottom: 0 }}
                                  >
                                    <div title={value} className='text-ellipsis'>：<span className={styles.equipmentFont}>{value}</span></div>
                                  </Form.Item>
                                </Col>
                              )
                            })
                          }
                        </Row>
                      </Form>
                    </Panel>
                  )
                })
              }
            </Collapse>
          </LayoutCard>
        </IFComponent>
      </div>
    )
  }
}

export default connect(({ login }) => ({ login }))(EmAppRealTimePage)
