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

class EDPurchaseAnalysisPage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      head: [],
      data: [],
      chartData: {}
    }
  }

  handleSearch = (value) => {
    this.getTableData(value)
  }

  getTableData = (value) => {
    const { login, dispatch } = this.props
    const json = initFilter(login.OrgId)
    addRuleAndGroups(json, value)

    dispatch({
      type: 'app/getDataByPost',
      url: 'ED/EDEnergyPurchase/getTableData',
      payload: json,
      onlyData: false,
      onComplete: (res) => {
        if (res && res.IsSuccessful && res.Data && res.Data.chartData) {
          const { head, data, chartData } = res.Data
          this.setState({
            head: head,
            data: data,
            chartData: {
              xAxis: chartData.XAxis[0].Data,
              yAxis: chartData.YAxis,
              data: chartData.Data
            }
          })
        }
      }
    })
  };

  render () {
    const render = (value, row, index) => {
      const obj = {
        children: value,
        props: {},
      }
      obj.props.rowSpan = row.rowSpan
      return obj
    }

    const columns = []
    this.state.head.forEach((n, i) => {
      var item = {
        title: n.Title, dataIndex: n.DataIndex, render: i == 0 ? render : (value, row, index) => {
          if (index % 7 === 1 && row.alarm.indexOf(n.DataIndex) != -1) {
            return <a style={{ color: 'red' }}>{value}</a>
          }
          return value
        }
      }
      columns.push(item)
    })
    const { formId, formCode } = this.props
    return (
      <>
        <Search
          formId={formId}
          formCode={formCode}
          onSearch={this.handleSearch}
        />
        <LayoutCard  style={{ marginBottom: 16 }}>
          <CommonChart
            chartId='EDPurchaseAnalysisData'
            {...this.state.chartData}
            magicType={['line', 'bar']}
            style={{ height: 300 }}
          />
        </LayoutCard>
        <LayoutCard style={{ marginBottom: 16 }}>
          <Table size={"small"} columns={columns} dataSource={this.state.data} pagination={false} bordered />
        </LayoutCard>
      </>
    )
  }
}

export default connect(({ login, app }) => ({ login, app }))(Form.create()(EDPurchaseAnalysisPage))
