// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { Form, Row, Col, Radio, DatePicker, Select } from 'antd'
import { Search, IFComponent, LayoutCard } 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 KrEnergyStatisticsPage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      radio: [],
      select: '',
      data: [],
      dateType: 2,
      searchRules: { rules: [] },
      dateVlaue: [moment().add(-15, 'day'), moment()],
      chartData: {},
      statisticalDatas: []
    }
  }

  handleSearch = (value) => {
    this.setState({ searchRules: value }, this.getData)
  }

  getData = () => {
    const { searchRules, select, dateType, dateVlaue } = this.state
    const value = cloneDeep(searchRules)
    value.rules.push({
      field: "Parameter1",
      operator: 0,
      value: this.props.data.id,
      isCustom: true,
      isSysParam: false,
    })
    value.rules.push({
      field: 'Parameter2',
      operator: 0,
      value: dateType,
      isCustom: true,
      isSysParam: false,
    })
    value.rules.push({
      field: 'Parameter3',
      operator: 0,
      value: dateVlaue.map(item => item.format('YYYY-MM-DD')).join(','),
      isCustom: true,
      isSysParam: false,
    })
    value.rules.push({
      field: 'Parameter4',
      operator: 0,
      value: select,
      isCustom: true,
      isSysParam: false,
    })
    const { login, dispatch } = this.props
    const json = initFilter(login.OrgId)
    addRuleAndGroups(json, value)

    dispatch({
      type: 'app/getDataByPost',
      url: 'KR/Statistics/GetEnergyStatisticsData',
      payload: json
    }).then(res => {
      if (res && res.radio) {
        const { chartData } = res
        this.setState({
          ...res,
          chartData: {
            xAxis: chartData.XAxis[0].Data,
            yAxis: chartData.YAxis,
            data: chartData.Data
          }
        })
      }
    })
  };

  handleChartChange = (e) => {
    this.setState({
      select: this.state.searchRules.rules[0].value == 0 && e.target.value == "compre" ? "" : e.target.value
    }, this.getData)
  }

  handlePanelChange = (dateVlaue) => {
    if (this.state.dateType == 0) {
      if (dateVlaue[1].year() < dateVlaue[0].year()) {
        dateVlaue[1] = dateVlaue[0]
      }
    }
    this.setState({ dateVlaue })
  }

  handleChange = (dateType) => {
    let dateVlaue = []
    switch (dateType) {
      case 0:
        dateVlaue.push(moment('2020-01-01', 'YYYY-MM-DD'))
        dateVlaue.push(moment().set('month', 0).set('date', 1))
        break
      case 1:
        dateVlaue.push(moment().add(-6, 'month').set('date', 1))
        dateVlaue.push(moment().set('date', 1))
        break
      case 2:
        dateVlaue.push(moment().add(-15, 'day'))
        dateVlaue.push(moment())
        break
      default:
        break
    }
    this.setState({ dateType, dateVlaue })
  }

  render() {
    const { select, dateType, chartData, statisticalDatas } = this.state
    const { formId, formCode } = this.props

    let datePicker = ''
    switch (dateType) {
      case 0:
        datePicker = (
          <RangePicker
            allowClear={false}
            mode={['year', 'year']}
            format='YYYY'
            value={this.state.dateVlaue}
            onPanelChange={this.handlePanelChange}
            style={{ width: '100%' }}
          />
        )
        break
      case 1:
        datePicker = (
          <RangePicker
            allowClear={false}
            mode={['month', 'month']}
            format='YYYY-MM'
            value={this.state.dateVlaue}
            onPanelChange={this.handlePanelChange}
            style={{ width: '100%' }}
          />
        )
        break
      case 2:
        datePicker = (
          <RangePicker
            allowClear={false}
            value={this.state.dateVlaue}
            onChange={this.handlePanelChange}
            style={{ width: '100%' }}
          />
        )
        break
      default:
        break
    }

    return (
      <>
        <Search
          formId={formId}
          formCode={formCode}
          onSearch={this.handleSearch}
          extraSearch={[
            <Form.Item label='查询方式'>
              <Select
                value={dateType}
                onChange={this.handleChange}
              >
                <Option value={0}>年消耗</Option>
                <Option value={1}>月消耗</Option>
                <Option value={2}>日消耗</Option>
              </Select>
            </Form.Item>,
            <Form.Item label='日期'>
              {datePicker}
            </Form.Item>
          ]}
        />
        <LayoutCard title='消耗明细'>
          <Row gutter={16}>
            <Col span={19} style={{ textAlign: 'center' }}>
              <Radio.Group value={select} onChange={this.handleChartChange}>
                <IFComponent IF={this.state.searchRules.rules.length}>
                  {
                    this.state.searchRules.rules.map((item, index) => {
                      if (index == 0 && item.value == 1) {
                        return <Radio.Button value={"compre"} key={"KrEnergyStatisticsPage_Radio_t"}>综合</Radio.Button>
                      }
                      return null
                    })
                  }
                </IFComponent>
                {
                  this.state.radio.map((item, index) => {
                    return <Radio.Button value={item.CODE} key={"KrEnergyStatisticsPage_Radio_" + index}>用{item.NAME}</Radio.Button>
                  })
                }
              </Radio.Group>
              <CommonChart
                chartId='KrEnergyStatisticsPage'
                {...chartData}
                style={{ height: 400 }}
              />
            </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' : '0.15rem' }}>
                      <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>
      </>
    )
  }
}

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