// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { Form, DatePicker, Select, Radio, Row, Col, Table } from 'antd'
import { Search, LayoutCard, IFComponent } from '@woowalker/feui'
import CommonChart from '../../Chart/CommonChart'
// 工具库
import { initFilter, addRuleAndGroups } from '../../../utils/common'
import moment from 'moment'
import { cloneDeep } from 'lodash'

const { Option } = Select
const { RangePicker } = DatePicker
const { GradientCard } = LayoutCard

class KrEnergyClassRatioPage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      statisticalDatas: [],
      dateType: 0,
      dateValue: [moment().add(-5, 'month').startOf('month'), moment().startOf('month')],
      num: 0,
      option: [],
      type: '',
      currentData: {},
      monthErlierData: {},
      yearErlierData: {},
      columns: [],
      dataSource: [],
      nodeCount: 0,
    }
  }

  componentDidMount () {
    this.getTpye()
  }

  getTpye = () => {
    const { login, dispatch } = this.props
    const json = initFilter(login.OrgId)
    dispatch({
      type: 'app/getDataByPost',
      url: 'BD/BDEnergyClass/FilterOrderPaged',
      payload: json
    }).then(res => {
      if (res && res) {
        this.setState({ option: res })
      }
    })
  }

  handleSearch = (value) => {
    const { dateValue, type } = this.state
    value.rules.push({
      field: 'Parameter1',
      operator: 0,
      value: this.props.data.TreeSelected.join(','),
      isCustom: true,
      isSysParam: false,
    })
    value.rules.push({
      field: 'Parameter2',
      operator: 0,
      value: dateValue.map(item => item.format('YYYY-MM-DD')).join(','),
      isCustom: true,
      isSysParam: false,
    })
    value.rules.push({
      field: 'Parameter3',
      operator: 0,
      value: type,
      isCustom: true,
      isSysParam: false,
    })
    const { login, dispatch } = this.props
    const json = initFilter(login.OrgId)
    addRuleAndGroups(json, value)

    dispatch({
      type: 'app/getDataByPost',
      url: 'KR/Statistics/GetEnergyClassRatioData',
      payload: json
    }).then(res => {
      if (res) {
        this.setState({
          ...res,
          chartData: this.getChartData(this.state.num, res)
        })
      }
    })
  }

  getChartData = (type, source) => {
    if (type === 3) return {}

    const { yearErlierData, monthErlierData, currentData } = source || this.state
    let chartData = yearErlierData
    switch (type) {
      case 0:
        chartData = yearErlierData
        break
      case 1:
        chartData = monthErlierData
        break
      case 2:
        chartData = currentData
        break
      default:
        break
    }

    return {
      xAxis: chartData.XAxis[0].Data,
      yAxis: chartData.YAxis,
      data: chartData.Data
    }
  }

  handleChartChange = (e) => {
    this.setState({
      num: e.target.value,
      chartData: this.getChartData(e.target.value)
    })
  }

  handlePanelChange = (value) => {
    this.setState({ dateValue: value })
  }

  handleChange = (dateType) => {
    let dateValue = []
    switch (dateType) {
      case 0:
        dateValue.push(moment().add(-5, 'month').startOf('month'))
        dateValue.push(moment().startOf('month'))
        break
      case 1:
        dateValue.push(moment().startOf('quarter'))
        dateValue.push(moment().startOf('month'))
        break
      case 2:
        let current = moment().startOf('quarter')
        dateValue.push(cloneDeep(current.add(-3, 'month')))
        dateValue.push(cloneDeep(current.add(2, 'month')))
        break
      case 3:
        dateValue.push(moment().startOf('year'))
        dateValue.push(moment().startOf('month'))
        break
      default:
        break
    }
    this.setState({ dateType, dateValue })
  }

  handleTypeChange = (value) => {
    this.setState({ type: value })
  }

  render () {
    const { formId, formCode } = this.props
    const { dateType, dateValue, statisticalDatas, num, option, type, chartData, dataSource, nodeCount } = this.state
    const columns = [
      {
        title: '时间', dataIndex: 'Time', render: (value, row, index) => {
          return {
            children: value,
            props: { rowSpan: index % nodeCount === 0 ? nodeCount : 0 },
          }
        }
      },
      { title: '节点名称', dataIndex: 'Name' },
      { title: '本期能耗（tCe）', dataIndex: 'Current' },
      { title: '环比能耗（tCe）', dataIndex: 'MonthErlier' },
      { title: '环比百分比（%）', dataIndex: 'MonthRatio' },
      { title: '同比能耗（tCe）', dataIndex: 'YearErlier' },
      { title: '同比百分比（%）', dataIndex: 'YearRatio' },
    ]
    return (
      <>
        <Search
          formId={formId}
          formCode={formCode}
          onSearch={this.handleSearch}
          extraSearch={[
            <Form.Item label='矿山安全类型'>
              <Select
                value={type}
                onChange={this.handleTypeChange}
                style={{ width: '100%' }}
              >
                <Option value=''>综合能耗</Option>
                {
                  option.map((item) => {
                    return (
                      <Option value={item.ID}>{item.NAME}</Option>
                    )
                  })
                }
              </Select>
            </Form.Item>,
            <Form.Item label='查询方式'>
              <Select
                value={dateType}
                onChange={this.handleChange}
                style={{ width: '100%' }}
              >
                <Option value={0}>近六月</Option>
                <Option value={1}>本季度</Option>
                <Option value={2}>上季度</Option>
                <Option value={3}>本年度</Option>
              </Select>
            </Form.Item>,
            <Form.Item label='日期'>
              <RangePicker
                allowClear={false}
                mode={['month', 'month']}
                format='YYYY-MM'
                value={dateValue}
                onPanelChange={this.handlePanelChange}
                style={{ width: '100%' }}
              />
            </Form.Item>
          ]}
        />
        <LayoutCard style={{ marginBottom: 16 }}>
          <Row gutter={16}>
            <Col span={19} style={{ textAlign: 'center' }}>
              <Radio.Group value={num} onChange={this.handleChartChange}>
                <Radio.Button value={0} key="KrEnergyRatioPage_Radio_2">同比</Radio.Button>
                <Radio.Button value={1} key="KrEnergyRatioPage_Radio_1">环比</Radio.Button>
              </Radio.Group>
              <CommonChart
                chartId='KrEnergyRatioPage'
                {...chartData}
                style={{ height: 350 }}
              />
            </Col>
            <Col span={5}>
              {
                statisticalDatas.map((item, index) => {
                  return (
                    <GradientCard
                      key={'GradientCard' + index}
                      title={item.Name}
                      colorIndex={index}
                      style={{ marginBottom: index === statisticalDatas.length - 1 ? 0 : 10 }}>
                      <span style={{ fontSize: 20, lineHeight: 1 }}>
                        {`${item.Value}${item.Unit ? ' ' + item.Unit : ''}`}
                      </span>
                      <IFComponent IF={!!item.Value2}>
                        <span style={{ marginTop: 5 }}><br />{item.Value2}</span>
                      </IFComponent>
                    </GradientCard>
                  )
                })
              }
            </Col>
          </Row>
        </LayoutCard>
        <LayoutCard title='能耗同比环比'>
          <Table
            size='small'
            columns={columns}
            dataSource={dataSource}
            pagination={false}
            style={{ marginTop: 8 }}
          />
        </LayoutCard>
      </>
    )
  }
}

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