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

// 表记节点 -> 历史监测
class EmHistoryPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      type: '1',
      month: moment().format('YYYY-MM'),
      day: moment().format('YYYY-MM-DD'),
      redisDate: '', // redis 缓存存储接口返回的 date
      selectedRowKeys: [],
      monthsData: {}, // 存储鼠标移上对应展示 dataSource 的对象
      showColumns: [], // 展示的表格列配置
      showDataSource: [], // 展示的表格
      exportColumns: [], // 用于导出数据的隐藏的表格列配置
      exportDataSource: [], // 用于导出数据的隐藏的表格
      chartData: {},
      searchRules: {}
    }
  }

  handleSearch = (value) => {
    this.state.searchRules = cloneDeep(value)

    value.rules.push({
      field: 'Parameter1',
      operator: 0,
      value: this.props.formParam.Parameter1,
      isCustom: true,
      isSysParam: false,
    })
    value.rules.push({
      field: 'Parameter2',
      operator: 0,
      value: this.state.type,
      isCustom: true,
      isSysParam: false,
    })
    value.rules.push({
      field: 'Parameter3',
      operator: 0,
      value: this.state.month,
      isCustom: true,
      isSysParam: false,
    })
    value.rules.push({
      field: 'Parameter4',
      operator: 0,
      value: this.state.day,
      isCustom: true,
      isSysParam: false,
    })
    value.rules.push({
      field: 'Parameter5',
      operator: 0,
      value: this.props.data.TreeSelected.join(','),
      isCustom: true,
      isSysParam: false,
    })

    const json = initFilter(this.props.login.OrgId)
    addRuleAndGroups(json, value)
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'EM/Monitoring/GetHistoryData',
      payload: json
    }).then(res => {
      if (res) {
        if (res.msg) {
          message.error(res.msg)
          return
        }

        const { chartData, headTitle, select, date, dateDic, tableData, dataSources } = res
        // 展示的 table 的列配置
        const showColumns = [
          { title: '序号', dataIndex: 'Index' },
          { title: '计量点名称', dataIndex: 'Name' },
          { title: '节点', dataIndex: 'NodeName' },
          { title: '最大值', dataIndex: 'Max' },
          { title: '最小值', dataIndex: 'Min' },
          { title: '平均值', dataIndex: 'Avg' },
          { title: '当前值', dataIndex: 'Current' }
        ]
        showColumns.forEach(item => {
          item.render = (text, record, index) => {
            return <span style={{ color: record.Color }}>{text}</span>
          }
        })
        // 导出的 table 的列配置
        const exportColumns = []
        headTitle.forEach((item, Index) => {
          const column = { title: item.Title, dataIndex: item.DataIndex }
          if (Index === 0) {
            column.render = (text, record, index) => {
              return {
                children: text,
                props: {
                  rowSpan: index % 3 === 0 ? 3 : 0
                }
              }
            }
          }
          exportColumns.push(column)
        })
        this.setState({
          redisDate: date.join(','),
          selectedRowKeys: select,
          monthsData: dateDic,
          showColumns,
          showDataSource: tableData,
          exportColumns,
          exportDataSource: dataSources,
          chartData: {
            xAxis: chartData.XAxis[0].Data,
            yAxis: chartData.YAxis,
            data: chartData.Data
          }
        })
      }
    })
  }

  saveRedis = () => {
    const { redisDate, selectedRowKeys } = this.state
    const json = {
      Code: this.props.formParam.Parameter1,
      Date: redisDate.split(',').map(item => moment(item).startOf('month').format('YYYY-MM-DD')).join(','),
      Ids: selectedRowKeys
    }

    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'EM/Monitoring/HistoryRedisSave',
      payload: json,
      onlyData: false,
      ignoreThrottle: true
    }).then(res => {
      if (res && res.IsSuccessful && res.Data) {
        this.handleSearch(this.state.searchRules)
      }
    })
  }

  onSelectChange = (selectedRowKeys) => {
    if (selectedRowKeys.length == 0) {
      message.error("至少选中1个计量点")
    } else {
      this.setState({ selectedRowKeys }, this.saveRedis)
    }
  }

  setShowDataSource = (evt) => {
    const { showDataSource, monthsData } = this.state
    showDataSource.forEach((item, index) => {
      item.Current = monthsData[evt.name][index]
    })
    this.setState({ showDataSource: [...showDataSource] })
  }

  throughClick = (evt) => {
    const { type, searchRules } = this.state
    switch (type) {
      case '1':
        this.setState({ month: evt.name, type: '2' }, () => {
          this.handleSearch(searchRules)
        })
        break
      case '2':
        this.setState({ day: evt.name, type: '3' }, () => {
          this.handleSearch(searchRules)
        })
        break
      default:
        break
    }
  }

  backClick = () => {
    const { type, searchRules } = this.state
    switch (type) {
      case '2':
        this.setState({ type: '1' }, () => {
          this.handleSearch(searchRules)
        })
        break
      case '3':
        this.setState({ type: '2' }, () => {
          this.handleSearch(searchRules)
        })
        break
      default:
        break
    }
  }

  beforeHandle = () => {
    const month = moment(this.state.month + '-1', 'YYYY-MM-DD')
    const day = moment(this.state.day, 'YYYY-MM-DD')

    switch (this.state.type) {
      case '2':
        this.setState({ month: month.add(-1, 'months').format('YYYY-MM') }, () => {
          this.handleSearch(this.state.searchRules)
        })
        break
      case '3':
        this.setState({ day: day.add(-1, 'days').format('YYYY-MM-DD') }, () => {
          this.handleSearch(this.state.searchRules)
        })
        break
      default:
        break
    }
  }

  afterHandle = () => {
    const month = moment(this.state.month + '-1', 'YYYY-MM-DD')
    const day = moment(this.state.day, 'YYYY-MM-DD')
    switch (this.state.type) {
      case '2':
        this.setState({ month: month.add(1, 'months').format('YYYY-MM') }, () => {
          this.handleSearch(this.state.searchRules)
        })
        break
      case '3':
        this.setState({ day: day.add(1, 'days').format('YYYY-MM-DD') }, () => {
          this.handleSearch(this.state.searchRules)
        })
        break
      default:
        break
    }
  }

  getInsertTitle = () => {
    const { formCode } = this.props
    const fieldConfigs = this.props.search.fieldConfigs[formCode] || []
    const exportInserTitle = ['历史数据']
    if (this.state.type === "1") {
      fieldConfigs.forEach(fc => {
        const { label, value, dataSource } = fc
        const cellText = renderExportCell(value, dataSource, fc, this.props.app.enums || {})
        cellText && exportInserTitle.push(`${label}：${cellText}`)
      })
    }
    else {
      exportInserTitle.push(`${this.state.month}`)
    }
    return exportInserTitle.join(' ')
  }

  render () {
    const { formId, formCode } = this.props
    const { selectedRowKeys, chartData, showColumns, showDataSource, exportColumns, exportDataSource } = this.state

    const exportToExcel = this.state.type === "1" ? "历史数据" : "历史数据" + this.state.month
    const exportInserTitle = this.getInsertTitle()
    const { selectedNodes = [] } = this.props.data
    const saveImgName = selectedNodes.length ? `${selectedNodes.map(item => item.node.name).join('-')}历史检测` : '历史检测'
    return (
      <div className='scroll_page'>
        <Search
          formId={formId}
          formCode={formCode}
          onSearch={this.handleSearch}
          iconEle={
            <IFComponent IF={this.state.type !== '1'}>
              <span
                style={{ cursor: 'pointer', marginRight: 8 }}
                onClick={this.backClick}>
                <Icon type="rollback" />
                <span>返回</span>
              </span>
            </IFComponent>
          }
        />
        <LayoutCard style={{ textAlign: 'center' }}>
          <IFComponent IF={this.state.type !== '3'}>
            <div style={{ textAlign: 'right', marginBottom: 8 }}>
              <ExportToExcel
                fileName={exportToExcel}
                insertRows={[exportInserTitle]}
                tableId="HistMonitorHistData"
              />
              <Table
                id='HistMonitorHistData'
                columns={exportColumns}
                dataSource={exportDataSource}
                pagination={false}
                style={{ display: 'none' }}
              />
            </div>
          </IFComponent>
          <IFComponent IF={this.state.type === '2'}>
            <Button.Group>
              <Button size='small' onClick={this.beforeHandle}><Icon type="left" />上个月</Button>
              <Button size='small' onClick={this.afterHandle}>下个月<Icon type="right" /></Button>
            </Button.Group>
          </IFComponent>
          <IFComponent IF={this.state.type === '3'}>
            <Button.Group>
              <Button size='small' onClick={this.beforeHandle}><Icon type="left" />上一天</Button>
              <Button size='small' onClick={this.afterHandle}>下一天<Icon type="right" /></Button>
            </Button.Group>
          </IFComponent>
          <CommonChart
            chartId='EmHistoryPage'
            {...chartData}
            onMouseover={this.setShowDataSource}
            onClick={this.throughClick}
            saveImgName={saveImgName}
            style={{ height: 300 }}
          />
          <Table
            size='small'
            rowSelection={{
              selectedRowKeys,
              onChange: this.onSelectChange
            }}
            columns={showColumns}
            dataSource={showDataSource}
            pagination={false}
            style={{ marginTop: 16 }}
          />
        </LayoutCard>
      </div>
    )
  }
}

export default connect(({ login, app, search }) => ({ login, app, search }))(EmHistoryPage)
