// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { Table, message } from 'antd'
import { Search, 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 EmHistoryHisPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      month: moment().format('YYYY-MM'),
      day: moment().format('YYYY-MM-DD'),
      redisDate: '', // redis 缓存存储接口返回的 date
      selectedRowKeys: [],
      monthsData: {}, // 存储鼠标移上对应展示 dataSource 的对象
      showColumns: [], // 展示的表格列配置
      showDataSource: [], // 展示的表格
      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: '1',
      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.id,
      isCustom: true,
      isSysParam: false,
    })

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

        const { chartData, select, date, dateDic, tableData } = res
        // 展示的 table 的列配置
        const showColumns = [
          { title: '状态', dataIndex: 'Status' },
          { title: '计量点名称', dataIndex: 'Name' },
          { title: '节点', dataIndex: 'NodeName' },
          { title: '月份', dataIndex: 'Month' },
          { title: '同比值', dataIndex: 'Yoy' },
          { title: '同比（比例%）', dataIndex: 'YoyRatio' },
          { title: '环比值', dataIndex: 'Mom' },
          { title: '环比（比例%）', dataIndex: 'MomRatio' },
          { title: '当前值', dataIndex: 'Current' }
        ]
        showColumns.forEach(item => {
          item.render = (text, record, index) => {
            const color = this.state.selectedRowKeys.indexOf(record.key) !== -1 ? 'inherit' : '#bfbfbf'
            return <span style={{ color }}>{text}</span>
          }
        })

        this.setState({
          redisDate: date.join(','),
          selectedRowKeys: select,
          monthsData: dateDic,
          showColumns,
          showDataSource: tableData,
          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 { monthsData } = this.state
    this.setState({ showDataSource: monthsData[evt.name] })
  }

  getInsertTitle = () => {
    const { formCode } = this.props
    const fieldConfigs = this.props.search.fieldConfigs[formCode] || []
    const exportInserTitle = ['按时间统计历史数据']
    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 { selectedRowKeys, chartData, showColumns, showDataSource } = this.state

    const { selectedNodes = [] } = this.props.data
    const titleText = selectedNodes.length ? `${selectedNodes.map(item => item.node.name).join('-')}` : ''
    return (
      <div className='scroll_page'>
        <Search
          formId={formId}
          formCode={formCode}
          onSearch={this.handleSearch}
        />
        <LayoutCard>
          <CommonChart
            chartId='EmHistoryHisPage'
            {...chartData}
            onMouseover={this.setShowDataSource}
            titleText={titleText}
            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 }))(EmHistoryHisPage)
