// 核心库
import React, { Component } from 'react'
import { connect } from 'dva'
// 组件库
import PieChart from './PieChart'
import SanChart from './SanChart'
import LineBarChart from './LineBarChart'
import { Row, Col } from 'antd'
// 工具库
import { initFilter, getRuleAndGroupByParseValue, addRuleAndGroups } from '../../utils/common'

class ChartPage extends Component {
  constructor (props) {
    super(props)
    this.state = {
      chartConfigs: []
    }
  }

  componentDidMount () {
    this.getChartConfig()
  }

  getChartConfig = () => {
    const { formCode, dispatch, login } = this.props
    const { OrgId: ORG_ID } = login
    const json = initFilter(ORG_ID, formCode, '', 0, 1)
    dispatch({
      type: 'chartPage/getChartPageConfigInfo',
      payload: json
    }).then(ret => {
      if (ret) {
        const { Nav_PageForm, Nav_PageCharts = [] } = ret
        const chartConfigs = Nav_PageCharts.map(chart => ({
          chart,
          id: chart.ID,
          code: chart.CODE,
          formCode: formCode,
          authOrgCodes: chart.AUTH_ORG_CODES || Nav_PageForm.AUTH_ORG_CODES
        }))

        this.setState({ chartConfigs })
      }
    })
  }

  getChartData = (id, value) => {
    const config = this.state.chartConfigs.find(item => item.id === id) || { chart: {} }
    const { ID, LABEL, CHART_TYPE, API_URL, FILTER_ORG_TYPE, Nav_Params, IGNORE_ORG_RULE } = config.chart
    if (!API_URL) return

    const { login, data, formParam, dispatch } = this.props
    // 请求参数
    const json = initFilter(login.OrgId)
    FILTER_ORG_TYPE && (json.OrgType = FILTER_ORG_TYPE)
    json.AuthOrgCodes = config.authOrgCodes
    value && addRuleAndGroups(json, value)
    data && addRuleAndGroups(json, data)
    data && data.id && (json.Keyword = data.id)
    data && data.TreeSelected && (json.TreeSelected = data.TreeSelected)
    IGNORE_ORG_RULE && (json.IgnoreOrgRule = IGNORE_ORG_RULE)
    Object.keys(formParam || {}).forEach(key => {
      json[key] = formParam[key]
    })

    if (Nav_Params && Nav_Params.length) {
      const ruleJson = {
        rules: [],
        groups: []
      }
      Nav_Params.forEach(param => {
        getRuleAndGroupByParseValue({
          ruleJson,
          field: param.FIELD_NAME,
          value: param.VALUE,
          operator: param.OPERATION,
          isCustom: param.IS_CUSTOM,
          user: login.user
        })
      })
      addRuleAndGroups(json, ruleJson)
    }

    // 请求图表配置
    dispatch({
      type: 'chartPage/getChartData',
      payload: json,
      url: API_URL
    }).then(ret => {
      this.setState({
        [ID]: this.getChartOption({ title: LABEL, type: CHART_TYPE, data: ret })
      })
    })
  }

  getChartOption = ({ title, type, data }) => {
    // 饼图
    if (type === 2) {
      const { XAxis = [], Data = [] } = data || {}
      return {
        // echarts option配置
        title,
        xAxis: XAxis.map(item => ({ data: item.Data || [] })),
        // 自定义数据存储
        data: 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
                }
              }
            })
          }
        })
      }
    }
    // 桑基图
    if (type === 3) {
      const { Links = [], Nodes = [], Levels } = data || {}
      return { title, Links, Nodes, Levels }
    }
    // 线图、柱状图
    const { XAxis = [], YAxis = [], Data = [] } = data || {}
    return {
      // echarts option配置
      title,
      xAxis: XAxis.map(item => ({ data: item.Data || [] })),
      yAxis: YAxis.map(item => {
        return {
          name: item.Name,
          max: item.Max,
          min: item.Min,
          inverse: item.IsInverse
        }
      }),
      // 自定义数据存储
      data: Data.map(item => {
        const { Name, ChartType, YAxisIndex, Stack } = item
        return {
          name: Name,
          type: ChartType == 0 ? 'line' : (ChartType == 1 ? 'bar' : (ChartType == 2 ? 'pie' : '')),
          yAxisIndex: YAxisIndex,
          stack: Stack,
          data: (item.Data || []).map(subData => ({ value: subData.Value }))
        }
      })
    }
  }

  renderChart = (config) => {
    const { ID, CHART_TYPE: type } = config.chart
    const props = {
      config,
      option: this.state[ID],
      type,
      getChartData: (val) => this.getChartData(ID, val),
      loading: this.props.loading
    }
    switch (type) {
      case 0:
      case 1:
        return <LineBarChart {...props} />
      case 2:
        return <PieChart {...props} />
      case 3:
        return <SanChart {...props} />
      default:
        return null
    }
  }

  render () {
    const { chartConfigs } = this.state
    return (
      <div className='scroll_page'>
        <Row>
          {
            chartConfigs.map(config => {
              const { chart } = config
              return (
                <Col key={config.id} span={chart && chart.SPAN ? chart.SPAN : 24}>
                  {this.renderChart(config)}
                </Col>
              )
            })
          }
        </Row>
      </div>
    )
  }
}

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