// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { Radio, Table, Row, Col } from 'antd'
import { Search, ExportToExcel, IFComponent, LayoutCard } from '@woowalker/feui'
import CommonChart from '../../Chart/CommonChart'
import CostPieEchart from './CostPieEchart'
// 工具库
import { initFilter, addRuleAndGroups, renderExportCell } from '../../../utils/common'

const { GradientCard } = LayoutCard

class EMCostHisPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      statisticalDatas: [],
      num: 0,
      type: '电',
      head: [],
      data: [],
      chartDosageModel: {},
      chartPriceModel: {},
      chartEnergyModel: {},
      pies: [],
      chartData: {}
    }
  }

  handleSearch = (value) => {
    const { data, formParam, login, dispatch } = this.props
    const json = initFilter(login.OrgId)
    value.rules.push({
      field: 'Keyword',
      operator: 0,
      value: data.id,
      isCustom: true,
      isSysParam: false,
    })
    value.rules.push({
      field: 'Parameter1',
      operator: 0,
      value: formParam.Parameter1,
      isCustom: true,
      isSysParam: false,
    })
    addRuleAndGroups(json, value)

    dispatch({
      type: 'app/getDataByPost',
      url: 'EM/Monitoring/GetCostHisData',
      payload: json
    }).then(res => {
      if (res) {
        this.setState({
          ...res,
          chartData: this.getChartData(this.state.num, res)
        })
      }
    })
  }

  handleChartChange = (e) => {
    this.setState({
      num: e.target.value,
      chartData: this.getChartData(e.target.value)
    })
  }

  getChartData = (type, source) => {
    if (type === 3) return {}

    const { chartDosageModel, chartPriceModel, chartEnergyModel } = source || this.state
    let chartData = chartDosageModel
    switch (type) {
      case 0:
        chartData = chartDosageModel
        break
      case 1:
        chartData = chartPriceModel
        break
      case 2:
        chartData = chartEnergyModel
        break
      default:
        break
    }

    return {
      xAxis: chartData.XAxis[0].Data,
      yAxis: chartData.YAxis,
      data: chartData.Data
    }
  }

  getInsertTitle = () => {
    const { formCode } = this.props
    const fieldConfigs = this.props.search.fieldConfigs[formCode] || []
    const exportInserTitle = ['节点监测']
    fieldConfigs.forEach(fc => {
      const { label, value, dataSource } = fc
      const cellText = renderExportCell(value, dataSource, fc, this.props.app.enums || {})
      cellText && exportInserTitle.push(`${label}：${cellText}`)
    })
    return exportInserTitle.join(' ')
  }

  render () {
    const { formId, formCode } = this.props
    const { statisticalDatas, num, head, type, data, pies, chartData } = this.state
    const exportInserTitle = this.getInsertTitle()

    const { selectedNodes = [] } = this.props.data
    const titleText = selectedNodes.length ? `${selectedNodes.map(item => item.node.name).join('-')}` : ''
    return (
      <div className='scroll_page'>
        <Search
          formId={formId}
          formCode={formCode}
          onSearch={this.handleSearch}
        />
        <LayoutCard title='按节点统计' style={{ marginBottom: 16 }}>
          <Row gutter={16}>
            <Col span={19} style={{ textAlign: 'center' }}>
              <Radio.Group value={num} onChange={this.handleChartChange} style={{ marginBottom: 8 }}>
                <Radio.Button value={0} key="EMCostPage_EM_1">用{type}量</Radio.Button>
                <Radio.Button value={1} key="EMCostPage_EM_2">用{type}成本</Radio.Button>
                <Radio.Button value={2} key="EMCostPage_EM_3">用{type}耗能</Radio.Button>
                <Radio.Button value={3} key="EMCostPage_EM_4">用{type}占比</Radio.Button>
              </Radio.Group>
              <IFComponent
                IF={num === 3}
                ELSE={
                  <CommonChart
                    chartId='EMCostHisPage'
                    {...chartData}
                    markLineMax
                    markLineMin
                    rotateXAxisLabel
                    magicType={[]}
                    titleText={titleText}
                    style={{ height: 350 }}
                  />
                }
              >
                <Row>
                  {
                    pies.map((item, index) => {
                      return (
                        <Col
                          key={"EMCostPage_col_" + index}
                          span={Math.floor(24 / pies.length)}
                          style={{ width: `${100 / pies.length}%` }}
                        >
                          <CostPieEchart key={item.Key} data={item} />
                        </Col>
                      )
                    })
                  }
                </Row>
              </IFComponent>
            </Col>
            <Col span={5}>
              {
                statisticalDatas.map((item, index) => {
                  return (
                    <GradientCard
                      key={'EM-Cost-GradientCard' + index}
                      title={item.Name}
                      colorIndex={index}
                      style={{ marginBottom: index === statisticalDatas.length - 1 ? 0 : '15px' }}>
                      <span style={{ fontSize: 20, lineHeight: 1 }}>
                        {`${item.Value}${item.Unit ? ' ' + item.Unit : ''}`}
                      </span>
                      <IFComponent IF={!!item.Value2}>
                        <span style={{ marginTop: 5 }}><br />{item.Value2}</span>
                      </IFComponent>
                    </GradientCard>
                  )
                })
              }
            </Col>
          </Row>
        </LayoutCard>
        <LayoutCard style={{ textAlign: 'right' }}>
          <ExportToExcel
            tableId='EMCostHisPageTable'
            fileName='节点监测'
            insertRows={[exportInserTitle]}
          />
          <Table
            id='EMCostHisPageTable'
            rowKey='key'
            size='small'
            columns={head.map(({ Title: title, DataIndex: dataIndex }) => ({ title, dataIndex }))}
            dataSource={data}
            style={{ marginTop: 8 }}
          />
        </LayoutCard>
      </div>
    )
  }
}

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