// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { Form, Button, DatePicker, Table, message, Icon, Upload, Select, Input } from 'antd'
import { ExportToExcel, LayoutCard } from '@woowalker/feui'
// 工具库
import moment from 'moment'
import { initFilter,addRuleAndGroups } from '../../../utils/common'
// 样式
import config from "../../../config"

const { Option } = Select

class EmImportHistDataPage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      importUrl: '',
      head: [],
      dataSource: [],
      data: [],
      selectedRowKeys: [],
      messages: "",
      energyType: "Electric",
      appName: "",
      nodeName: "",
      appGrade: "",
      dateYear: moment().format('YYYY'),
      option: []
    }
  }

  componentDidMount() {
    this.getConsumData()
    this.getTpye()
  }

  getTpye = () => {
    const { login, dispatch } = this.props
    const json = initFilter(login.OrgId)
    dispatch({
      type: 'app/getDataByPost',
      url: 'KR/Statistics/GetEnergyType',
      payload: json,
      onlyData: false,
      onComplete: (res) => {
        if (res && res.IsSuccessful && res.Data && res.Data) {
          this.setState({ option: res.Data.option })
        }
      }
    })
  }

  fillImportData = (ret) => {
    if (!ret) {
      this.setState({
        data: [],
        selectedRowKeys: [],
        messages: '',
      })
      return
    }
    if (ret.ErrorMessage) {
      this.setState({
        messages: ('错误：' + ret.ErrorMessage)
      })
    }
    let messages = ''
    if (ret.Data && ret.Data.MessageList && ret.Data.MessageList.length) {
      var tmps = []
      ret.Data.MessageList.forEach((n, i) => {
        tmps.push(n)
      })
      messages = tmps.join('\n')
    }
    const selectedRowKeys = []
    if (ret.Data && ret.Data.Data) {
      ret.Data.Data.forEach((n, i) => {
        selectedRowKeys.push(n.ID)
      })
    }
    this.setState({
      data: (ret.Data && ret.Data.Data ? ret.Data.Data : []),
      selectedRowKeys,
      messages
    })
  }

  getDataUpdate = (update) => {
    if (update) {
      this.setState({ importUrl: 'api/PF/Import/ImportHistData' })
    } else {
      this.setState({ importUrl: 'api/PF/Import/ImportHistData' })
    }
  }

  changeType = (value) => {
    this.setState({
      energyType: value
    })
  }

  changeGrade = (value) => {
    this.setState({
      appGrade: value
    })
  }

  onChangeApp = (value) => {
    this.setState({
      appName: value
    })
  }

  onChangeNode = (value) => {
    this.setState({
      nodeName: value
    })
  }

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

  dateYearChange = (dateYear, str) => {
    this.setState({ dateYear: moment(dateYear).format('YYYY') })
  }

  getConsumData = (value) => {
    const json = {
      OrgId: this.props.login.OrgId,
      Parameter1: this.state.energyType,
      Parameter3: this.state.dateYear,
      Parameter4: this.state.appName,
      Parameter5: this.state.nodeName,
      Parameter6: this.state.appGrade,
    }
    addRuleAndGroups(json, value)
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'EM/Monitoring/GetHistDosagesMonthData',
      payload: json,
      onlyData: false,
      onComplete: (res) => {
        if (res && res.IsSuccessful && res.Data && res.Data.tableHead && res.Data.tableData) {
          const { tableHead, tableData } = res.Data
          this.setState({
            head: tableHead,
            dataSource: tableData
          })
        }
      }
    })
  }



  render() {
    let url = this.state.importUrl
    const { head, dataSource ,option} = this.state
    const that = this
    const uploadProps = {
      showUploadList: false,
      name: 'file',
      action: config.serviceHost(url),
      data: { OrgId: that.props.login.OrgId, ImportConfigCode: 'configCode' },
      fileList: that.state.updateLoadFileList,
      accept: '.xls,.xlsx',
      onChange(info) {
        that.setState({
          updateLoadFileList: info.fileList,
        })

        if (info.file.status === 'done') {
          if (info.file.response.IsSuccessful) {
            that.setState({
              head: info.file.response.Data.Head,
              dataSource: info.file.response.Data.DataSource
            })
            if (url === 'api/PF/Import/ImportHistData') {
              message.info(`${info.file.name} 导入并保存成功`)
            }
            that.fillImportData(info.file.response)
          } else {
            message.error(`Excel单元格式不正确，无法识别！ `)
          }
        } else if (info.file.status === 'error') {
          if (info.file.response && info.file.response.ErrorMessage) {
            message.error(`${info.file.name} 导入错误，详情：${info.file.response.ErrorMessage}`)
          }
          else {
            message.error(`${info.file.name} 导入错误`)
          }
        }
      },
    }
    const columns = []
    head.forEach((n, i) => {
      var item = {
        title: n.Title, dataIndex: n.DataIndex
      }
      columns.push(item)
    })

    const paginationConfig = {
      pageSizeOptions: ['10', '20'],
      pageSize: 10,
      total: this.state.dataSource.length,
      showSizeChanger: true,
      size: 'small',
      showTotal: () => `共 ${this.state.dataSource.length} 条`
    }

    return (
      <>
        <LayoutCard style={{ marginBottom: '0.15rem' }}>
          <div className='advanced-search__form'>
            <Form>
              <Form.Item label="查询年份">
                <DatePicker
                  allowClear={false}
                  mode='year'
                  format='YYYY'
                  value={moment(this.state.dateYear, 'YYYY')}
                  onPanelChange={this.dateYearChange}
                  style={{ width: '100%' }}
                />
              </Form.Item>
              <Form.Item label='器具名称'>
                <Input placeholder="" value={this.state.appName} style={{ width: '100%' }} onChange={(evt) => this.onChangeApp(evt.target.value)} />
              </Form.Item>
              <Form.Item label='节点名称'>
                <Input placeholder="" value={this.state.nodeName} style={{ width: '100%' }} onChange={(evt) => this.onChangeNode(evt.target.value)} />
              </Form.Item>
              <Form.Item label='器具等级'>
                <Select style={{ width: '100%' }} onChange={this.changeGrade} allowClear={true}>
                  <Option value={0}>一级</Option>
                  <Option value={1}>二级</Option>
                  <Option value={2}>三级</Option>
                </Select>
              </Form.Item>
              <Form.Item label='矿山安全类型'>
                <Select style={{ width: '100%' }} defaultValue="电" onChange={this.changeType}>
                {option.map(item => <Option key={item.ID} value={item.CODE}>{item.NAME}</Option>)}               
                </Select>
              </Form.Item>
              <div className='advanced-search__btns-zone'>
                <Button type='primary' onClick={this.handleSearch}>查询</Button>
                <div className='advanced-search__tool-wrap'>
                  <div className='advanced-search__children'>
                    <Upload {...uploadProps}>
                      <Button type='primary' onClick={() => this.getDataUpdate(true)}> <Icon type="upload" /> 导入</Button>
                    </Upload>
                  </div>
                </div>
              </div>
            </Form>
          </div>
        </LayoutCard>
        <LayoutCard style={{ textAlign: 'right' }}>
          <ExportToExcel
            fileName={'导入历史数据#' + this.state.dateYear}
            insertRows={['导入历史数据#' + this.state.dateYear]}
            columns={columns}
            dataSource={dataSource}
          />
          <Table
            id='ImportHistDataTable'
            size='small'
            style={{ marginTop: 8 }}
            bordered
            columns={columns}
            dataSource={dataSource}
            scroll={{ x: '100%' }}
            pagination={paginationConfig}
          />
        </LayoutCard>
      </>
    )

  }

}

EmImportHistDataPage.propTypes = {
}

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