// 核心库
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 { guid, initFilter, addRuleAndGroups, renderExportCell } from '../../../utils/common'

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

  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,
      })
      value.rules.push({
        field: 'Parameter5',
        operator: 0,
        value: "WRITE_OFF",
        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: 'EM/EMEnergyDosage/AmortizationReportEnergy',
      payload: json,
      onlyData: false,
      onComplete: (res) => {
        if (res && res.IsSuccessful && res.Data) {
          this.setState({
            tableKey:guid(),
            columns: res.Data.Colums || [],
            dataSource: res.Data.Data,
          })
        } 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(' ')
  }

  onExpand = (expanded, record) => {
    if (!expanded)
      return;

    /* if (record.children && record.children.length > 0)
      return; */
    const { login, dispatch } = this.props
    const json = initFilter(login.OrgId)
    addRuleAndGroups(json, this.state.searchRules)
    json["Parameter4"] = record.ID
    dispatch({
      type: 'app/getDataByPost',
      url: 'EM/EMEnergyDosage/AmortizationReportEnergy',
      payload: json,
      onlyData: false,
      onComplete: (res) => {   
        if (res && res.IsSuccessful && res.Data) {
          record.children = res.Data.Data
        } else {
          if (res && !res.IsSuccessful) {
            message.error(res.ErrorMessage)
          }
        }
      }
    })
  }

  render() {
    const { formId, formCode } = this.props
    const { tableKey, dateType, dateString,dataSource } = this.state
    const columns = this.state.columns.map((n) => {
      return {
        title: n.Title,
        dataIndex: n.DataIndex,
        key: n.DataIndex,
        width: 100,
        render: (value, row) => {
          return <a id={row.ID}>{value}</a>
        }
      }
    })

    const rows = dataSource.map((n)=>{
      return n.key;
    })
    const loading = this.props.loading.effects['app/getDataByPost']
    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={'网络节点核销统计_' + dateString}
            insertRows={[exportInserTitle]}
            tableId='nodeDetails_tree'
          />
          <Table
            key={tableKey}
            id='nodeDetails_tree'
            size='small'
            bordered
            columns={columns}
            dataSource={dataSource}
            pagination={false}
            loading={loading}
            scroll={{ x: '100%' }}
            style={{ marginTop: 8 }}
            onExpand={this.onExpand}
            defaultExpandedRowKeys={rows}
          />
        </LayoutCard>
      </>
    )
  }

}

EMWriteOffReportPage.propTypes = {
}

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