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

class KRUnitConsumPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      columns: [],
      parentId: '',
      path: [],
      dateType: '0',
      dateString: moment().format('YYYY')
    }
  }

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

  onClickRow = (id) => {
    if (id) {
      this.setState({
        parentId: id
      }, () => {
        this.getConsumData()
      })
    }
  }

  getConsumData = () => {
    const { login, dispatch } = this.props
    const json = initFilter(login.OrgId)
    addRuleAndGroups(json, this.state.searchRules)
    json["Parameter4"] = this.state.parentId
    dispatch({
      type: 'app/getDataByPost',
      url: 'KR/Statistics/Consum',
      payload: json,
      onlyData: false,
      onComplete: (res) => {
        if (res && res.IsSuccessful && res.Data) {
          this.setState({
            columns: res.Data.Colums || [],
            dataSource: res.Data.Data,
            path: res.Data.Path
          })
        } else {
          if (res && !res.IsSuccessful) {
            message.error(res.ErrorMessage)
          }
        }
      }
    })
  }

  getInsertTitle = () => {
    const inserDateTitle = this.state.dateType === '0' ? '年' : this.state.dateType === '1' ? '月' : '日'

    const { formCode } = this.props
    const fieldConfigs = this.props.search.fieldConfigs[formCode] || []
    const exportInserTitle = ['节点矿山安全统计', `${this.state.dateString + inserDateTitle}`]
    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 columns = this.state.columns.map((n) => {
      return {
        title: n.Title,
        dataIndex: n.DataIndex,
        key: n.DataIndex,
        width: 100,
        align: 'center',
        render: (value, row) => {
          return <a id={row.ID}>{value}</a>
        }
      }
    })

    const reversePath = cloneDeep(this.state.path || [])
    reversePath.reverse()
    const loading = this.props.loading.effects['app/getDataByPost']
    const exportInserTitle = this.getInsertTitle()
    return (
      <>
        <Search
          formId={formId}
          formCode={formCode}
          onSearch={this.handleSearch}
          extraSearch={[
            <FullDatePicker
              dateType={this.state.dateType}
              dateString={this.state.dateString}
              onlyItem
              onChange={({ dateString, dateType }) => this.setState({ dateString, dateType })}
              options={['0', '1', '3']}
            />
          ]}
        />
        <LayoutCard
          title={<span>当前节点：{
            reversePath.length
              ? (
                reversePath.map(n => {
                  return <a onClick={() => this.onClickRow(n.ID)}>{n.Name}/</a>
                })
              )
              : null
          }</span>}
          style={{ textAlign: 'right', marginTop: '0.15rem' }}
        >
          <ExportToExcel
            fileName={'节点矿山安全统计_' + this.state.dateString}
            insertRows={[exportInserTitle]}
            tableId='nodeDetails'
          />
          <Table
            id='nodeDetails'
            size='small'
            bordered
            columns={columns}
            dataSource={this.state.dataSource}
            pagination={false}
            loading={loading}
            onRow={(record) => ({
              onClick: () => {
                this.onClickRow(record.ID)
              }
            })}
            scroll={{ x: '100%' }}
            style={{ marginTop: 8 }}
          />
        </LayoutCard>
      </>
    )
  }

}

KRUnitConsumPage.propTypes = {
}

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