import React from 'react'
import { connect } from 'dva'
import { Modal, Table, Row, Col, Tag, Tabs } from 'antd'
import { LayoutCard } from '@woowalker/feui'
import RadarChart from '../../Chart/RadarChart'
import CommonChart from '../../Chart/CommonChart'
import TableChart from '../../Chart/TableChart'
import { getPieChartOption } from '../../Chart/PieChart'
import styles from './index.css'
const { TabPane } = Tabs

const tagColors = ['magenta', 'volcano', 'orange', 'gold', 'lime', 'green', 'cyan', 'blue', 'geekblue', 'purple']
class EnergyKpiDetailModal extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      visible: false,
      dateString: new Date().toLocaleDateString(),
      columns: [],
      dataSource: [],
      statistical: [],
      statisticalWeight: [],
      score: 0,
      radar: {},
      pieChartOption: {},
      trendChartData: {},
      tabsData: [],
      columnsScore: [
        { title: '起始值', dataIndex: 'START_VALUE' },
        { title: '结束值', dataIndex: 'END_VALUE' },
        { title: '分数', dataIndex: 'SCORE' },
      ],
      itemRatio: [],
      columnsRatio: [
        { title: '打分项', dataIndex: 'NAME' },
        { title: '最大分值', dataIndex: 'MaxScore' },
        { title: '权重', dataIndex: 'RATIO' }
      ],
      tabsIndex: 0,
      targetChartData: [],
      scoreChartData: [],
      targetChart: {},
      scoreChart: {}
    }
  }

  componentDidMount () {
    if (this.props.onRef) {
      this.props.onRef(this)
    }
  }

  showModal = (key, parentId, dateType, dateString) => {
    this.setState({
      visible: true,
      dateString
    }, () => {
      const json = {
        OrgId: this.props.login.OrgId,
        Keyword: key,
        Parameter1: dateType,
        Parameter2: dateString,
        Parameter3: parentId
      }

      this.props.dispatch({
        type: 'app/getDataByPost',
        url: 'ED/Calculate/GetMarkItemDetailData',
        payload: json
      }).then(res => {
        if (res && res.dataSource) {
          const { columns, dataSource, statistical, statisticalWeight, score, radar, pie, chartData, tabsData,
            itemRatio, scoreChartData, targetChartData } = res
          this.setState({
            columns,
            dataSource,
            statistical,
            statisticalWeight,
            score: score.toFixed(2),
            radar: {
              data: radar.Data,
              radar: radar.Radar
            },
            pieChartOption: getPieChartOption({
              // echarts option配置
              title: '加权分值',
              xAxis: pie.XAxis.map(item => ({ data: item.Data || [] })),
              // 自定义数据存储
              data: pie.Data.map(item => {
                return {
                  yAxisIndex: item.YAxisIndex,
                  data: (item.Data || []).map(subData => {
                    return {
                      value: subData.Value,
                      // 用作 pie -> series -> label.rich 富文本样式的配置
                      data: {
                        head: subData.Heads,
                        data: subData.Data
                      }
                    }
                  })
                }
              })
            }),
            trendChartData: {
              xAxis: chartData?.XAxis[0].Data,
              yAxis: [{ Name: '' }],
              data: chartData?.Data
            },
            tabsData,
            itemRatio,
            scoreChartData,
            targetChartData
          }, () => {
            this.buildChartData(this.state.tabsIndex)
          })
        }
      })
    })
  }

  handleCancel = () => {
    this.setState({ visible: false })
  }

  callback = (key) => {
    const index = +key.replace('EDMarkItemEnum_', '')
    this.setState({ tabsIndex: index }, () => {
      this.buildChartData(index)
    })

  }

  buildChartData = (tabsIndex) => {
    const { targetChartData, scoreChartData } = this.state
    this.setState({
      targetChart: {
        xAxis: targetChartData[tabsIndex].XAxis[0].Data,
        yAxis: [{ Name: '' }],
        data: targetChartData[tabsIndex].Data
      },
      scoreChart: {
        xAxis: scoreChartData[tabsIndex].XAxis[0].Data,
        yAxis: [{ Name: '' }],
        data: scoreChartData[tabsIndex].Data
      }
    })
  }

  render () {
    const { visible, dateString, columns, dataSource, statistical, statisticalWeight, score, radar, pieChartOption, trendChartData,
      tabsData, columnsScore, itemRatio, columnsRatio, targetChart, scoreChart } = this.state
    const { loading, data } = this.props
    return (
      <Modal
        title="详细信息"
        visible={visible}
        onCancel={this.handleCancel}
        footer={null}
        bodyStyle={{ backgroundColor: '#f2f2f2', padding: 8 }}
        className='antd-modal-fullscreen'
      >
        <Row gutter={8}>
          <Col span={10}>
            <LayoutCard title='初始分值'>
              <Row className={styles.chartWrap}>
                <Col className={styles.chart}>
                  <RadarChart {...radar} style={{ height: 230 }} />
                </Col>
                <Col className={styles.score}>
                  {
                    statistical.map(({ Name, Value }, index) => {
                      return (
                        <p style={{ marginLeft: 4 }}>
                          <span>{Name}：</span>
                          <Tag color={tagColors[index % tagColors.length]} style={{ fontSize: 20 }}>{Value.toFixed(2)}</Tag>
                        </p>
                      )
                    })
                  }
                </Col>
              </Row>
            </LayoutCard>
          </Col>
          <Col span={11}>
            <LayoutCard title='加权分值'>
              <Row className={styles.chartWrap}>
                <Col className={styles.chartWeight}>
                  <TableChart
                    type={2}
                    option={pieChartOption}
                    style={{ height: 230 }}
                  />
                </Col>
                <Col className={styles.scoreWeight}>
                  {
                    statisticalWeight.map(({ Name, Value, Value2 }, index) => {
                      return (
                        <p style={{ marginLeft: 4 }}>
                          <span>{Name}：</span>
                          <Tag color={tagColors[index % tagColors.length]} style={{ fontSize: 20 }}>{Value.toFixed(2)}</Tag>
                          <span> 权重：{Value2}</span>
                        </p>
                      )
                    })
                  }
                </Col>
              </Row>
            </LayoutCard>
          </Col>
          <Col span={3}>
            <LayoutCard title={<span>得分<strong>（满分：5分）</strong></span>}>
              <div className={styles.scoreWrap}>
                <p>{score}<i /><i /></p>
                <p>{dateString}</p>
              </div>
            </LayoutCard>
          </Col>
        </Row>
        <LayoutCard title='打分明细' style={{ marginTop: 8 }}>
          <CommonChart
            chartId='EDEnergyKpiDetailPage_line'
            {...trendChartData}
            saveImgName={'能耗Kpi明细'}
            style={{ height: 400 }}
          />
          <Table
            loading={loading.effects['app/getDataByPost']}
            size='small'
            columns={columns}
            dataSource={dataSource}
            pagination={false}
            scroll={{ x: '100%' }}
            style={{ marginTop: 8 }}
          />
        </LayoutCard>
        <LayoutCard>
          <Row gutter={16}>
            <Col span={12}>
              <CommonChart
                chartId='EDEnergyKpiItemPage_target_line'
                {...targetChart}
                saveImgName={'能耗Kpi指标'}
                style={{ height: 400 }}
              />
            </Col>
            <Col span={12}>
              <CommonChart
                chartId='EDEnergyKpiItemPage_score_line'
                {...scoreChart}
                saveImgName={'能耗Kpi分值'}
                style={{ height: 400 }}
              />
            </Col>
          </Row>
        </LayoutCard>
        <LayoutCard>
          <Tabs type="card" onChange={this.callback}>
            {
              tabsData.map((item, index) => {
                if (item.Data.length == 1) {
                  return (
                    <TabPane tab={item.Name} key={"EDMarkItemEnum_" + index}>
                      <Row gutter={16}>
                        <Col span={12}>
                          <Table
                            loading={loading.effects['app/getDataByPost']}
                            size='small'
                            columns={columnsScore}
                            dataSource={item.Data[0].Item}
                            pagination={false}
                            style={{ marginTop: 8 }}
                          />
                        </Col>
                        <Col span={12}>
                          <Table
                            loading={loading.effects['app/getDataByPost']}
                            size='small'
                            columns={columnsRatio}
                            dataSource={itemRatio}
                            pagination={false}
                            style={{ marginTop: 8 }}
                          />
                        </Col>
                      </Row>
                    </TabPane>
                  )
                }
                else {
                  return (
                    <TabPane tab={item.Name} key={"EDMarkItemEnum_" + index}>
                      <Tabs>
                        {
                          item.Data.map((it, index2) => {
                            return (
                              <TabPane tab={it.Name} key={"EDMarkItemEnum_Ele_" + index2}>
                                <Row gutter={16}>
                                  <Col span={12}>
                                    <Table
                                      loading={loading.effects['app/getDataByPost']}
                                      size='small'
                                      columns={columnsScore}
                                      dataSource={it.Item}
                                      pagination={false}
                                      scroll={{ x: '100%' }}
                                      style={{ marginTop: 8 }}
                                    />
                                  </Col>
                                  <Col span={12}>
                                    <Table
                                      loading={loading.effects['app/getDataByPost']}
                                      size='small'
                                      columns={columnsRatio}
                                      dataSource={itemRatio}
                                      pagination={false}
                                      style={{ marginTop: 8 }}
                                    />
                                  </Col>
                                </Row>
                              </TabPane>
                            )
                          })
                        }
                      </Tabs>
                    </TabPane>
                  )
                }
              })
            }
          </Tabs>
        </LayoutCard>
      </Modal>
    )
  }
}
export default connect(({ login, loading }) => ({ login, loading }))(EnergyKpiDetailModal)