// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { FullDatePicker, LocalSearch, LayoutCard } from '@woowalker/feui'
import { Row, Col, Table, Icon, message } from 'antd'
import CommonChart from '../../Chart/CommonChart'
import EnergyKpiModal from './EnergyKpiModal'
import EnergyKpiDetailModal from './EnergyKpiDetailModal'
// 工具库
import moment from 'moment'

class EDEnergyKpiPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      dateType: '0',
      dateString: moment().format('YYYY'),
      rankChartData: {},
      rankChartChangeData: {},
      trendChartData: {},
      chartLine: {},
      columns: [],
      dataSource: [],
      selectedRowKeys: []
    }
  }

  onModalRef = (ref) => {
    this.modalChild = ref
  }

  onDetailModalRef = (ref) => {
    this.detailModalChild = ref
  }

  showModal = () => {
    this.modalChild.showModal(this.props.data.TreeSelected.join(','))
  }

  showDetailModal = (key, parentId) => {
    const { dateType, dateString } = this.state
    this.detailModalChild.showModal(key, parentId, dateType, dateString)
  }

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

  chartLineSetValue = () => {
    const { chartLine, selectedRowKeys } = this.state
    const data = []
    chartLine.Data.forEach(item => {
      selectedRowKeys.indexOf(item.Key) !== -1 && data.push(item)
    })
    this.setState({
      trendChartData: {
        xAxis: chartLine?.XAxis[0].Data,
        yAxis: [{ Name: '' }],
        data
      }
    })
  }

  handleSearch = () => {
    const { dateType, dateString } = this.state
    const json = {
      Keyword: this.props.data.TreeSelected.join(','),
      OrgId: this.props.login.OrgId,
      Parameter1: dateType,
      Parameter2: dateString,
    }

    if (dateType == '0' && moment(dateString) > moment().startOf('year')) {
      message.error("选中的年份不能大于当前月！")
      this.setState({ dateString: moment().format('YYYY') })
      return
    }

    if (dateType == '1' && moment(dateString) > moment().startOf('month')) {
      message.error("选中的月份不能大于当前月！")
      this.setState({ dateString: moment().format('YYYY-MM') })
      return
    }

    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'ED/Calculate/GetMarkItemData',
      payload: json
    }).then(res => {
      if (res && res.chartLine) {
        const { data: dataSource, selectedRowKeys, chartLine, chartKpiModel, chartKpiChangeModel } = res

        // table 的列配置
        const columns = [
          { title: '序号', dataIndex: 'Index' },
          { title: '名称', dataIndex: 'Name' },
          { title: '最大值', dataIndex: 'Max' },
          { title: '最小值', dataIndex: 'Min' },
          { title: '平均值', dataIndex: 'Avg' }
        ]
        columns.forEach(item => {
          item.render = (text, record, index) => {
            const color = this.state.selectedRowKeys.indexOf(record.key) !== -1 ? 'inherit' : '#bfbfbf'
            return <span style={{ color }}>{text}</span>
          }
        })
        columns.push({
          title: '操作',
          dataIndex: 'action',
          render: (text, record) => {
            return <a onClick={() => this.showDetailModal(record.key, record.ParentId)}><Icon type='radar-chart' /> 详情</a>
          }
        })

        this.setState({
          columns,
          dataSource,
          selectedRowKeys,
          chartLine,
          rankChartData: {
            xAxis: chartKpiModel?.XAxis[0].Data,
            yAxis: [{ Name: '' }],
            data: chartKpiModel?.Data
          },
          rankChartChangeData: {
            xAxis: chartKpiChangeModel?.XAxis[0].Data,
            yAxis: [{ Name: '%' }],
            data: chartKpiChangeModel?.Data
          }
        }, () => {
          this.chartLineSetValue()
        })
      }
    })
  }

  render () {
    const { data, loading } = this.props
    const { selectedNodes = [] } = data
    const { columns, dataSource, selectedRowKeys, rankChartData, rankChartChangeData, trendChartData } = this.state
    return (
      <div className='scroll_page'>
        <LocalSearch
          onSearch={this.handleSearch}
          isRemember
          shareKey='EDEnergyKpi'
          setExtraData={({ dateString, dateType }, callback) => this.setState({ dateString, dateType }, callback)}
          getExtraData={() => ({ dateType: this.state.dateType, dateString: this.state.dateString })}
          iconEle={
            <span
              style={{ cursor: 'pointer' }}
              onClick={this.showModal}>
              <Icon type="setting" />
              <span> 配置</span>
            </span>
          }
        >
          <FullDatePicker
            dateType={this.state.dateType}
            dateString={this.state.dateString}
            onlyItem
            onChange={({ dateString, dateType }) => this.setState({ dateString, dateType })}
            options={['0', '1']}
          />
        </LocalSearch>
        <LayoutCard title='排名区' style={{ marginBottom: 16 }}>
          <Row gutter={16}>
            <Col span={12}>
              <CommonChart
                chartId='EDEnergyKpiPage_bar'
                {...rankChartData}
                saveImgName={selectedNodes.length ? `${selectedNodes.map(item => item.node.name).join('-')}能耗Kpi排名` : '能耗Kpi排名'}
                style={{ height: 300 }}
              />
            </Col>
            <Col span={12} >
              <CommonChart
                chartId='EDEnergyKpiPage_bar_Change'
                {...rankChartChangeData}
                saveImgName={selectedNodes.length ? `${selectedNodes.map(item => item.node.name).join('-')}能耗Kpi变化率排名` : '能耗Kpi变化率排名'}
                style={{ height: 300 }}
              />
            </Col>
          </Row>
        </LayoutCard>
        <LayoutCard title='趋势区'>
          <CommonChart
            chartId='EDEnergyKpiPage_line'
            {...trendChartData}
            saveImgName={selectedNodes.length ? `${selectedNodes.map(item => item.node.name).join('-')}能耗Kpi` : '能耗Kpi'}
            style={{ height: 400 }}
          />
          <Table
            loading={loading.effects['app/getDataByPost']}
            rowSelection={{ selectedRowKeys, onChange: this.onSelectChange }}
            size='small'
            columns={columns}
            dataSource={dataSource}
            pagination={false}
          />
        </LayoutCard>
        <EnergyKpiModal onRef={this.onModalRef} />
        <EnergyKpiDetailModal onRef={this.onDetailModalRef} />
      </div>
    )
  }
}

export default connect(({ login, loading, app }) => ({ login, loading, app }))(EDEnergyKpiPage)
