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

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

class KrCostStatisticsPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      statisticalDatas: [],
      head: [],
      data: [],
      dateValue: [moment().startOf('year'), moment().startOf('month')],
      pies: []
    }
  }

  handleSearch = (value) => {
    const { dateValue } = this.state
    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: 'Parameter1',
      operator: 0,
      value: this.props.data.selectedNodes[0].node.id,
      isCustom: true,
      isSysParam: false,
    })
    const { login, dispatch } = this.props
    const json = initFilter(login.OrgId)
    addRuleAndGroups(json, value)

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

  handlePanelChange = (value) => {
    const { dateValue } = this.state
    if (value[0].year() != value[1].year()) {
      if (dateValue[0].year() != value[0].year()) {
        value[1] = cloneDeep(value[0]).endOf("year").startOf('month')
      }
      if (dateValue[1].year() != value[1].year()) {
        value[0] = cloneDeep(value[1]).startOf("year")
      }
      message.error("开始年份和结束年份必须一致！")
    }

    this.setState({ dateValue: value })
  }


  render () {
    const { statisticalDatas, head, data, pies, dateValue, chartData } = this.state
    const { formId, formCode } = this.props
    return (
      <>
        <Search
          formId={formId}
          formCode={formCode}
          onSearch={this.handleSearch}
          extraSearch={[
            <Form.Item label='日期'>
              <RangePicker
                allowClear={false}
                mode={['month', 'month']}
                format='YYYY-MM'
                value={dateValue}
                onPanelChange={this.handlePanelChange}
              />
            </Form.Item>
          ]}
        />
        <LayoutCard title='按时间统计' style={{ marginBottom: 16 }}>
          <Row gutter={16}>
            <Col span={19}>
              <CommonChart
                chartId='KrConsumptionStatisticsPage'
                {...chartData}
                style={{ height: 360 }}
              />
            </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>
        <IFComponent IF={pies.length}>
          <LayoutCard title='成本占比' style={{ marginBottom: 16 }}>
            <Row>
              {
                pies.map((item, index) => {
                  return (
                    <Col span={4} key={"KrConsumptionStatisticsPage_col_" + index}>
                      <PieEchart key={item.Key} data={item} />
                    </Col>
                  )
                })
              }
            </Row>
          </LayoutCard>
        </IFComponent>
        <LayoutCard title='成本同比'>
          <Table
            size='small'
            columns={head.map(({ Title: title, DataIndex: dataIndex }) => ({ title, dataIndex }))}
            dataSource={data}
            pagination={{ pageSize: 5 }}
            style={{ marginTop: 8 }}
          />
        </LayoutCard>
      </>
    )
  }
}

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