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

class KrConsumUseEnergyPage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      head: [],
      dataSource: [],
      typeIndex: 0,
      dateType: '0',
      searchRules: [],
      dateString: moment().format('YYYY'),
    }
  }

  handleSearch = (value) => {
    if (value && value.rules) {
      value.rules.push({
        field: 'Parameter1',
        operator: 0,
        value: this.state.dateType,
        isCustom: true,
        isSysParam: false,
      })
      value.rules.push({
        field: 'Parameter2',
        operator: 0,
        value: this.state.dateString,
        isCustom: true,
        isSysParam: false,
      })
      this.setState({
        searchRules: value,
      }, () => {
        this.getConsumData(value)
      })
    }
  }

  getConsumData = () => {
    const { login, dispatch } = this.props
    const json = initFilter(login.OrgId)
    addRuleAndGroups(json, this.state.searchRules)
    dispatch({
      type: 'app/getDataByPost',
      url: 'KR/Statistics/ConsumUseEnergy',
      payload: json,
      onlyData: false,
      onComplete: (res) => {
        if (res && res.IsSuccessful && res.Data) {
          this.setState({
            typeIndex: res.Data.Index,
            head: res.Data.Head,
            dataSource: res.Data.Data,
          })
        } else {
          if (res && !res.IsSuccessful) {
            message.error(res.ErrorMessage)
          }
        }
      }
    })
  }

  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 { dateString, dateType, typeIndex, head, dataSource } = this.state
    const length = dataSource.length
    const columns = []
    head.forEach((n, i) => {
      var item = {
        title: n.Title, dataIndex: n.DataIndex,
        render: (value, row, index) => {
          return {
            children: value,
          }
        }
      }
      if (i === 0) {
        item = {
          title: n.Title, dataIndex: n.DataIndex,
          render: (value, row, index) => {
            return {
              children: value,
              props: {
                rowSpan: index % (typeIndex + 3) === 0 ? (typeIndex + 3) : (index == length - 2 ? 1 : 0),
              },
            }
          }
        }
      }
      if (i === 1) {
        item = {
          title: n.Title, dataIndex: n.DataIndex,
          render: (value, row, index) => {
            return {
              children: value,
              props: {
                rowSpan: index < length - 2 ? (index % (typeIndex + 3) === 0 ? 4 : (index % (typeIndex + 3) > 0 && index % (typeIndex + 3) < 4 ? 0 : 1)) : 1,
              },
            }
          }
        }
      }

      columns.push(item)
    })

    const exportInserTitle = this.getInsertTitle()
    return (
      <>
        <Search
          formId={formId}
          formCode={formCode}
          onSearch={this.handleSearch}
          extraSearch={[
            <FullDatePicker
              dateType={dateType}
              dateString={dateString}
              onlyItem
              onChange={({ dateString, dateType }) => this.setState({ dateString, dateType })}
              options={['0', '1', '3']}
            />
          ]}
        />
        <LayoutCard style={{ textAlign: 'right', marginTop: '0.15rem' }}>
          <ExportToExcel
            fileName={'用能统计_' + this.state.dateString}
            insertRows={[exportInserTitle]}
            tableId='useEnergyDetails'
          />
          <Table
            id='useEnergyDetails'
            size='small'
            bordered
            columns={columns}
            dataSource={dataSource}
            pagination={false}
            scroll={{ x: '100%' }}
            style={{ marginTop: 8 }}
          />
        </LayoutCard>
      </>
    )
  }
}

KrConsumUseEnergyPage.propTypes = {
}

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