// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { Form, Button,DatePicker, Table, Radio, 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 { MonthPicker } = DatePicker
const { Option } = Select

class EmImportMeterReadDataPage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      importUrl: '',
      head: [],
      dataSource: [],
      selected: [],
      data: [],
      selectedRowKeys: [],
      messages: "",
      selects: '1',
      energyType: "Electric",
      appName: "",
      nodeName: "",
      appGrade: 0,
      dateYear: moment().format('YYYY'),
      dateMonth: moment().format('YYYY-MM'),
      dateDay: moment().format('YYYY-MM-DD'),
      option: []
    }
  }

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

  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 = (selects) => {
    if (selects === '1') {
      this.setState({ importUrl: 'api/PF/Import/ImportYearMeterReadData' })
    } else if(selects === '2') {
      this.setState({ importUrl: 'api/PF/Import/ImportMonthMeterReadData' })
    }else {
      this.setState({ importUrl: 'api/PF/Import/ImportDayMeterReadData' })
    }
  }

  handleChange = (e) => {
    this.setState({
      selects: e.target.value
    },
      this.getConsumData
    )
  }

  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') })
  }

  dateMonthChange = (dateMonth, str) => {
    this.setState({ dateMonth: str })
  }
  dateDayChange = (dateDay, str) => {
    this.setState({ dateDay: str })
  }

  getConsumData = (value) => {
    var dateType = this.state.dateYear
    switch (this.state.selects) {
      case "1":
        dateType = this.state.dateYear
        break
      case "2":
        dateType = this.state.dateMonth
        break
      case "3":
        dateType = this.state.dateDay
        break
      default:
        break
    }
    const json = {
      OrgId: this.props.login.OrgId,
      Parameter1: this.state.energyType,
      Parameter2: this.state.selects,
      Parameter3: dateType,
      Parameter4: this.state.appName,
      Parameter5: this.state.nodeName,
      Parameter6: this.state.appGrade,
    }
    addRuleAndGroups(json, value)
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'EM/Monitoring/GetMeterReadData',
      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, selects, dateYear, dateMonth,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) {
            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 date = selects === "1" ? dateYear : dateMonth
    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="查询年份" style={{ display: selects === "1" ? "flex" : "none" }}>
                <DatePicker
                  allowClear={false}
                  mode='year'
                  format='YYYY'
                  value={moment(this.state.dateYear, 'YYYY')}
                  onPanelChange={this.dateYearChange}
                  style={{ width: '100%' }}
                />
              </Form.Item>
              <Form.Item label='查询月份' style={{ display: selects === "2" ? "flex" : "none" }}>
                <MonthPicker
                  allowClear={false}
                  value={moment(this.state.dateMonth, 'YYYY-MM')}
                  format={'YYYY-MM'}
                  onChange={this.dateMonthChange}
                  style={{ width: '100%' }}
                />
              </Form.Item>
              <Form.Item label='查询日期' style={{ display: selects === "3" ? "flex" : "none" }}>
                <DatePicker
                  allowClear={false}
                  value={moment(this.state.dateDay, 'YYYY-MM-DD')}
                  format={'YYYY-MM-DD'}
                  onChange={this.dateDayChange}
                  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%' }} defaultValue={0} 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'>
                    <Radio.Group defaultValue="1" buttonStyle="solid" style={{ width: '100%' }} onChange={this.handleChange}>
                      <Radio.Button value="1">年抄表卡</Radio.Button>
                      <Radio.Button value="2">月抄表卡</Radio.Button>
                      <Radio.Button value="3">日抄表卡</Radio.Button>
                    </Radio.Group>
                  </div>
                  <div className='advanced-search__children'>
                    <Upload {...uploadProps}>
                      <Button type='primary' onClick={() => this.getDataUpdate(selects)}> <Icon type="upload" /> 导入</Button>
                    </Upload>
                  </div>
                </div>
              </div>
            </Form>
          </div>
        </LayoutCard>
        <LayoutCard style={{ textAlign: 'right' }}>
          <ExportToExcel
            fileName={'抄表卡#' + date}
            insertRows={['抄表卡#' + date]}
            columns={columns}
            dataSource={dataSource}
          />
          <Table
            id='ImportMeterReadDataTable'
            size='small'
            style={{ marginTop: 8 }}
            bordered
            columns={columns}
            dataSource={dataSource}
            scroll={{ x: '100%' }}
            pagination={paginationConfig}
          />
        </LayoutCard>
      </>
    )

  }

}

EmImportMeterReadDataPage.propTypes = {
}

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