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

const { Option } = Select

class KrMeasureReportPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      dataSource: [],
      option: [],
      val: '',
    }
  }

  componentDidMount () {
    this.getEnergyNode()
  }

  handleSearch = (value) => {
    value.rules.push({
      field: 'Parameter2',
      operator: 0,
      value: this.state.val,
      isCustom: true,
      isSysParam: false,
    })
    this.setState({
      searchRules: value
    }, () => {
      this.getRunData(value)
    })
  };

  handleNodeChange = (value) => {
    this.setState({ val: value })
  }

  getEnergyNode = () => {
    const { login, dispatch } = this.props
    const json = initFilter(login.OrgId)
    dispatch({
      type: 'app/getDataByPost',
      url: 'KR/Statistics/GetEnergyNode',
      payload: json,
      onlyData: false,
      onComplete: (res) => {
        if (res && res.IsSuccessful && res.Data && res.Data && res.Data.option) {
          const { option } = res.Data
          if (option.length > 0) {
            const val = res.Data.option[0].ID
            this.setState({ option, val })
          }
        }
      }
    })
  }

  getRunData = (value) => {
    const { login, dispatch } = this.props
    const json = initFilter(login.OrgId)
    addRuleAndGroups(json, value)
    dispatch({
      type: 'app/getDataByPost',
      url: 'KR/Statistics/GetRunMeasureData',
      payload: json,
      onlyData: false,
      onComplete: (res) => {
        if (res && res.IsSuccessful && res.Data) {
          const currState = {
            dataSource: res.Data,
          }
          this.setState(currState)
        }
      }
    })
  };

  getInsertTitle = () => {
    const { option, val } = this.state
    const targetVal = option.find(item => item.ID === val)

    const { formCode } = this.props
    const fieldConfigs = this.props.search.fieldConfigs[formCode] || []
    const exportInserTitle = ['电量测算原始记录表', `进线号：${targetVal ? targetVal.CODE : ''}`]
    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 { dataSource, option, val } = this.state
    const { formId, formCode } = this.props

    const columns = [
      {
        title: "参数",
        children: [{
          title: '日期',
          dataIndex: 'Time',
          key: 'Time',
          render: (value, row) => {
            return {
              children: value,
              props: {
                colSpan: row.ColSpan
              },
            }
          }
        }]
      },
      {
        title: "电表起始值",
        children: [{
          title: '有功',
          dataIndex: 'StartActive',
          key: 'StartActive',
          render: (value, row) => {
            return {
              children: value,
              props: {
                colSpan: row.ColSpan > 1 ? 0 : row.ColSpan
              },
            }
          }
        }, {
          title: '无功',
          dataIndex: 'StartReactive',
          key: 'StartReactive',
          render: (value, row) => {
            return {
              children: value,
              props: {
                colSpan: row.ColSpan2
              },
            }
          }
        }]
      },
      {
        title: "电表终止值",
        children: [{
          title: '有功',
          dataIndex: 'EndActive',
          key: 'EndActive',
          render: (value, row) => {
            return {
              children: value,
              props: {
                colSpan: row.ColSpan2 > 1 ? 0 : row.ColSpan2
              },
            }
          }
        }, {
          title: '无功',
          dataIndex: 'EndReactive',
          key: 'EndReactive',
          render: (value, row) => {
            return {
              children: value,
              props: {
                colSpan: row.ColSpan2 > 1 ? 0 : row.ColSpan2
              },
            }
          }
        }]
      },
      {
        title: "电量（KWh）",
        children: [{
          title: '有功',
          dataIndex: 'PowerActive',
          key: 'PowerActive',
          render: (value, row) => {
            return {
              children: value,
              props: {
                colSpan: row.ColSpan3
              },
            }
          }
        }, {
          title: '无功',
          dataIndex: 'PowerReactive',
          key: 'PowerReactive',
          render: (value, row) => {
            return {
              children: value,
              props: {
                colSpan: row.ColSpan3 > 1 ? 0 : row.ColSpan3
              },
            }
          }
        }]
      }
    ]
    const exportInserTitle = this.getInsertTitle()
    return (
      <>
        <Search
          formId={formId}
          formCode={formCode}
          onSearch={this.handleSearch}
          extraSearch={[
            <Form.Item label='进线号'>
              <Select
                value={val}
                onChange={this.handleNodeChange}
                style={{ width: '100%' }}
              >
                {
                  option.map((item) => {
                    return (
                      <Option value={item.ID}>{item.CODE}</Option>
                    )
                  })
                }
              </Select>
            </Form.Item>
          ]}
        />
        <LayoutCard style={{ textAlign: 'right' }}>
          <ExportToExcel
            fileName='电量测算原始记录表'
            insertRows={[exportInserTitle]}
            tableId='KrMeasureReportPageExport'
          />
          <Table
            id='KrMeasureReportPageExport'
            size='small'
            bordered
            columns={columns}
            dataSource={dataSource}
            pagination={false}
            scroll={{ x: '100%' }}
            style={{ marginTop: 8 }}
          />
        </LayoutCard>
      </>
    )
  }
}

KrMeasureReportPage.propTypes = {
}

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