// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { Table } from 'antd'
import { Search, ExportToExcel, LayoutCard } from '@woowalker/feui'
// 工具库
import { addRuleAndGroups, renderExportCell } from '../../../utils/common'

class EmEnergyLossPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      loading: false,
      columns: [],
      dataSource: []
    }
  }

  handleTreeData = (nodes, initStart = 0) => {
    nodes.forEach((item, index) => {
      item.start = nodes[index - 1] ? nodes[index - 1].start + nodes[index - 1].rowSpan : initStart
      item.rowSpan = item.childNodeKey || 1
      if (item.childNode && item.childNode.length) {
        this.handleTreeData(item.childNode, item.start)
      }
    })
  }

  recursiveNodes = (columns, nodes) => {
    columns.push({
      render: (value, row, index) => {
        for (let i = 0, j = nodes.length; i < j; i++) {
          if (index === nodes[i].start) {
            return {
              children: (
                <div>
                  <h2 style={{ margin: 0 }}>{nodes[i].name}</h2>
                  <p style={{ margin: 0 }}>用能：{nodes[i].value} {nodes[i].unit}</p>
                  <p style={{ margin: 0 }}>损耗量：{nodes[i].loss} {nodes[i].unit}</p>
                  <p style={{ margin: 0 }}>损耗率：{nodes[i].lossRate}%</p>
                </div>
              ),
              props: {
                valign: 'top',
                rowSpan: nodes[i].rowSpan,
                style: { border: '1px solid #e8e8e8' }
              }
            }
          }
        }
        return {
          children: null,
          props: {
            rowSpan: 0
          }
        }
      }
    })
    let nextNodes = []
    nodes.forEach(item => {
      item.childNode && item.childNode.length && (nextNodes = nextNodes.concat(item.childNode))
    })
    nextNodes.length && this.recursiveNodes(columns, nextNodes)
  }

  handleSearch = (value) => {
    const json = {
      OrgId: this.props.login.OrgId,
      Parameter1: this.props.formParam.Parameter1,
      TreeSelected: this.props.data.TreeSelected
    }
    addRuleAndGroups(json, value)

    this.setState({ loading: true })
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'EM/Monitoring/GetFlowListData',
      payload: json,
      onlyData: false,
      onComplete: (res) => {
        if (res && res.IsSuccessful && res.Data && res.Data.treeData) {
          const { dataSource, treeData } = res.Data
          this.handleTreeData([treeData])

          const columns = []
          this.recursiveNodes(columns, [treeData])

          this.setState({
            loading: false,
            dataSource,
            columns
          })
        }
        else {
          this.setState({ loading: false })
        }
      }
    })
  }

  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 { dataSource, columns, loading } = this.state
    const exportInserTitle = this.getInsertTitle()
    return (
      <div className='scroll_page'>
        <Search
          formId={formId}
          formCode={formCode}
          onSearch={this.handleSearch}
        />
        <LayoutCard style={{ textAlign: 'right' }}>
          <ExportToExcel
            fileName='流向监测列表'
            insertRows={[exportInserTitle]}
            tableId='EmEnergyLossPageTable'
          />
          <Table
            id='EmEnergyLossPageTable'
            showHeader={false}
            columns={columns}
            dataSource={dataSource}
            pagination={false}
            loading={loading}
            style={{ height: 'calc(100% - 47px)', overflowY: 'auto', marginTop: 8 }}
          />
        </LayoutCard>
      </div>
    )
  }
}

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