// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { Icon } from 'antd'
import { Scrollbars } from 'react-custom-scrollbars'
import { LocalSearch, FullDatePicker, LayoutCard } from '@woowalker/feui'
import TableChart from '../../Chart/TableChart'
import CommonChart from '../../Chart/CommonChart'
// 工具库
import { initFilter, addRuleAndGroups } from '../../../utils/common'
import { isEqual } from 'lodash'
import moment from 'moment'
// 样式
import styles from './index.css'

class EMPeakValleyPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      searchRule: null,
      dateType: '1',
      dateString: moment().format('YYYY-MM'),
      statisticalDatas: [],
      chartData: {},
      pieDatas: [],
      pieFeeDatas: []
    }
  }

  shouldComponentUpdate (nextProps, nextState) {
    return !isEqual(nextState.searchRule, this.state.searchRule)
  }

  handleSearch = (value) => {
    const { formParam, data } = this.props
    const { dateType, dateString } = this.state
    value.rules.push({
      field: 'Parameter1',
      operator: 0,
      value: formParam.Parameter1,
      isCustom: true,
      isSysParam: false,
    })
    value.rules.push({
      field: 'Parameter2',
      operator: 0,
      value: dateType,
      isCustom: true,
      isSysParam: false,
    })
    value.rules.push({
      field: 'Parameter3',
      operator: 0,
      value: dateString,
      isCustom: true,
      isSysParam: false,
    })
    value.rules.push({
      field: 'Parameter4',
      operator: 0,
      value: data.selectedNodes ? data.selectedNodes.map(item => item.node.id).join(',') : null,
      isCustom: true,
      isSysParam: false,
    })

    // 获取数据
    const { login, dispatch } = this.props
    const json = initFilter(login.OrgId)
    addRuleAndGroups(json, value)

    dispatch({
      type: 'app/getDataByPost',
      url: 'EM/Monitoring/GetPeakValleyData',
      payload: json
    }).then(res => {
      if (res) {
        const { statisticalDatas, chartDataModel, pieDatas, pieFeeDatas } = res
        this.setState({
          searchRule: json,
          statisticalDatas,
          chartData: {
            xAxis: chartDataModel?.XAxis[0].Data,
            yAxis: chartDataModel?.YAxis,
            data: chartDataModel?.Data
          },
          pieDatas: pieDatas.map(({ name, value, color }) => ({ name, value, itemStyle: { color } })),
          pieFeeDatas: pieFeeDatas.map(({ name, value, color }) => ({ name, value, itemStyle: { color } }))
        })
      }
    })
  }

  getOption = () => {
    return {
      tooltip: {
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
      },
      legend: {
        top: 20,
        textStyle: {
          color: '#8C8C8C'
        }
      },
      series: [
        {
          name: '用电时段',
          type: 'pie',
          radius: [0, 60],
          top: 66,
          label: {
            formatter: [
              '{title|{b}({d}%)}',
              '{detail|用量：{c}}'
            ].join('\n'),
            rich: {
              title: { fontSize: 12 },
              detail: { fontSize: 12 }
            }
          },
          data: this.state.pieDatas
        }
      ]
    }
  }

  getFeeOption = () => {
    return {
      tooltip: {
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
      },
      legend: {
        top: 20,
        textStyle: {
          color: '#8C8C8C'
        }
      },
      series: [
        {
          name: '用电费用',
          type: 'pie',
          radius: [0, 60],
          top: 66,
          label: {
            formatter: [
              '{title|{b}({d}%)}',
              '{detail|费用：{c}}'
            ].join('\n'),
            rich: {
              title: { fontSize: 12 },
              detail: { fontSize: 12 }
            }
          },
          data: this.state.pieFeeDatas
        }
      ]
    }
  }

  render () {
    const { statisticalDatas, chartData } = this.state

    return (
      <div className='scroll_page'>
        <LocalSearch
          isRemember
          shareKey='EMPeakValley'
          setExtraData={({ dateString, dateType }, callback) => this.setState({ dateString, dateType }, callback)}
          getExtraData={() => ({ dateType: this.state.dateType, dateString: this.state.dateString })}
          onSearch={this.handleSearch}
        >
          <FullDatePicker
            dateType={this.state.dateType}
            dateString={this.state.dateString}
            onlyItem
            onChange={({ dateString, dateType }) => this.setState({ dateString, dateType })}
            options={['0', '1', '4']}
          />
        </LocalSearch>
        <LayoutCard className={styles.peakPage_scrollWrap}>
          <Scrollbars autoHide autoHideTimeout={1000} autoHideDuration={200}>
            <div className={styles.peakPage_wrap}>
              {
                statisticalDatas.map((item, index) => (
                  <div className={styles.peakPage_section}>
                    <div key={`peakPage_chargeDetail_${index}`} className={styles.peakPage_data}>
                      <div className={styles.peakPage_title}>
                        <Icon type={index === 0 ? 'bar-chart' : 'money-collect'} style={{ fontSize: 42, color: '#35cdef' }} />
                        <span>{index === 0 ? '用电量' : '费用'}</span>
                      </div>
                      {
                        item.Items.map((t, i) => {
                          return (
                            <div key={`${t.name}_${i}`} className={styles.peakPage_detail}>
                              <span style={{ color: t.Color }}>{t.Name}（{t.Unit}）</span>
                              <span>{t.Value}</span>
                            </div>
                          )
                        })
                      }
                    </div>
                    <div className={styles.peakPage_charge}>
                      {
                        index === 0
                          ? <TableChart type={2} style={{ height: 240 }} option={this.getOption()} />
                          : <TableChart type={2} style={{ height: 240 }} option={this.getFeeOption()} />
                      }
                    </div>
                  </div>
                ))
              }
            </div>
          </Scrollbars>
        </LayoutCard>
        <LayoutCard>
          <CommonChart
            chartId='EMPeakValleyPage'
            {...chartData}
            style={{ height: 300 }}
          />
        </LayoutCard>
      </div>
    )
  }
}

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